repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
blazysecon/houseprices
https://github.com/blazysecon/houseprices
25125f5f11310bb71e0d0e8852ffeafe7f970da4
ae908a9122275e757eee30e491f666cf13017f67
c5afc853ce8f889eed87bdc1a6aa3ea8d77affb9
refs/heads/master
2020-04-12T15:49:49.014418
2017-08-24T07:32:07
2017-08-24T07:32:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6296296119689941, "alphanum_fraction": 0.6326164603233337, "avg_line_length": 33.163265228271484, "blob_id": "b8489c090f033a271a08f53ed7f838b8e5c73286", "content_id": "fc030edbb97918a6d96d3386b60f4ab5cce035f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1674, "license_type": "no_license", "max_line_length": 81, "num_lines": 49, "path": "/src/models/evaluate_model.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "import click\nimport pandas as pd\nimport train_model\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_log_error\nfrom math import sqrt\n\[email protected]()\[email protected]('input_filepath', type=click.Path(exists=True))\[email protected]('output_filepath', required=False)\[email protected]('original_filepath', required=False)\ndef main(input_filepath, output_filepath=None, original_filepath=None):\n \"\"\"\n Reads input data, splits it into training and test data and makes prediction\n using model from train_model.py\n \"\"\"\n \n # read the processed data\n df = pd.read_csv(input_filepath)\n\n # remove target\n X = df.drop(['SalePrice'], axis=1)\n y = df['SalePrice'] \n \n # split in training and test data\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n pipe = train_model.build_fit_pipe(X_train.drop('Id', axis=1), y_train) \n pred = pipe.predict(X_test.drop('Id', axis=1))\n total = 0\n score = []\n for t,p in zip(y_test, pred):\n error = sqrt(mean_squared_log_error([t],[p])) \n score.append(error)\n print(\"truth : {}, prediction : {}, score: {} \".format(t, p, error))\n total = total + error\n print(total/float(len(y_test)))\n \n if (output_filepath != None) & (original_filepath != None):\n original = pd.read_csv(original_filepath)\n result = pd.DataFrame(X_test)\n result = result[['Id']]\n result = pd.merge(result, original, on='Id', how='inner')\n result['Prediction'] = pred\n result['Score'] = score\n result.to_csv(output_filepath)\n\nif __name__ == '__main__': \n main()\n" }, { "alpha_fraction": 0.6353276371955872, "alphanum_fraction": 0.6381766200065613, "avg_line_length": 23.928571701049805, "blob_id": "41ce5ca98bb68306aae471f8d697a97c523123b1", "content_id": "4ac9b328290214cbcca15cb766eaa3bdfdec5f44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 351, "license_type": "no_license", "max_line_length": 76, "num_lines": 14, "path": "/docs_mgt/index.rst", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": ".. HousePrices documentation master file, created by\n sphinx-quickstart.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nHousePrices documentation!\n==============================================\n\n.. toctree::\n :maxdepth: 2\n\n getting-started\n commands\n modules_classes\n\n\n" }, { "alpha_fraction": 0.6215421557426453, "alphanum_fraction": 0.6284578442573547, "avg_line_length": 36.56493377685547, "blob_id": "b36f6d8a5356e2f628b88787bcf9bd7e9aedda93", "content_id": "127bb907dc19d61d61f318f547d023d20368f958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5784, "license_type": "no_license", "max_line_length": 101, "num_lines": 154, "path": "/src/visualization/visualize.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport click\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib.ticker import FixedLocator\nfrom matplotlib.backends.backend_pdf import PdfPages\n\ndef classify_score(score):\n if score <= 0.1:\n return 0\n elif score <= 0.15:\n return 2\n elif score <= 0.2:\n return 3\n else:\n return 4\n\ndef transform_scores(scores):\n transformed = list(map(lambda x: classify_score(x), scores)) \n return transformed\n\n\ndef scatter_plot_by_group(groups, x, y, ax, title, xlabel, ylabel, diag=False):\n \"\"\" Adds grouped data to an existing axes instance resulting in colored scatter points.\n Color of data point depends on group they belong to.\n \n :param groups: grouped data\n :param x: name of column to use as x-coordinates\n :param y: name of column to use as y-coordinates\n :param ax: axes object on which to add plot\n :param title: title of plot\n :param xlabel: label of x-axis\n :param ylabel: label of y-axis\n :param diag: indicates whether a diagonal should be added to the plot or not\n :type groups: groupby object\n :type x, y: string\n :type title, xlabel, ylabel: string\n :return: void\n \"\"\"\n for name, group in groups:\n h, = ax.plot(group[x], group[y], marker='o', linestyle='', ms=3, label=name)\n ax.legend()\n #ax.set(adjustable='box-forced', aspect='equal')\n ax.set_xlabel(xlabel) \n ax.set_ylabel(ylabel) \n ax.set_title(title)\n #ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)\n if diag:\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n \n \ndef visualize_feature(x, y, color, cmap, ax, xlabel, ylabel, title, xnumeric):\n \"\"\" Adds data points to an existing axes instance resulting in a scatter plot.\n Can handle numeric and categorical data on the x axis, y axis is supposed numeric.\n Non-numeric data is always considered to be categorical.\n \n :param x: x-coordinates\n :param y: y-coordinates\n :param color: colors of cmap to use\n :param cmap: color map\n :param ax: axes object on which to add plot\n :param title: title of plot\n :param xlabel: label of x-axis\n :param ylabel: label of y-axis\n :param numeric: indicates whether x-axis data is numeric or categorical\n :type x, y: lists\n :type title, xlabel, ylabel, cmap: string\n :type color: list of ints\n :return: void\n \"\"\"\n if xnumeric == True: \n ax.scatter(x, y, c=color, cmap=cmap) \n labels = ax.get_xticklabels() \n for label in labels: \n label.set_rotation(45) \n else: \n integer_map = dict([(val, i) for i, val in enumerate(set(x))]) \n ax.scatter(x.apply(lambda z: integer_map[z]), y, c=color, cmap=cmap)\n fl = FixedLocator(range(len(integer_map)))\n ax.xaxis.set_major_locator(fl)\n ax.xaxis.set_ticklabels([str(k) for k in integer_map.keys()], rotation=45)\n ax.set_xlabel(xlabel) \n ax.set_ylabel(ylabel) \n ax.set_title(title)\n \n\ndef visualize_features(df, features, target, color, cmap, ncols, figsize, nplots_per_page, outpath):\n \"\"\" Plots the specified features against the target as scatter plots\n and adds them to a multicolumn (ncols) multi-page PDF document (nplots_per_page) \n at location specified by outpath\n \n :param df: input data\n :param features: names of feature columns\n :param target: name of target feature\n :param color: list used to determine colors using cmap\n :param cmap: color map to use\n :param ncols: number of individual plots per row\n :param figsize: size of individual plots\n :param nplots_per_page: number of individual plots to put on a page\n :param outpath: path to output file\n :type df: pandas dataframe\n :type features: list of strings\n :type target, cmap: string\n :type color: list of ints\n :type ncols, nplots_per_page: int\n :type figsize: tuple (int, int)\n :type outpath: string\n :return: void\n \"\"\"\n nplots = len(features)\n nrows = int(np.ceil(nplots_per_page / float(ncols)))\n npages = int(np.ceil(nplots / float(nplots_per_page)))\n\n pdf_pages = PdfPages(outpath)\n i = 0\n for pg in range(npages):\n to_plot = features[i:i+nplots_per_page]\n fig, axes = plt.subplots(nrows, ncols, figsize=figsize, dpi=10)\n for f, ax in zip(to_plot, axes.flatten()):\n if(df[f].dtype == np.object):\n visualize_feature(df[f], df[target], color, cmap, ax, f, target, f, False)\n else:\n visualize_feature(df[f], df[target], color, cmap, ax, f, target, f, True)\n axlist = axes.flatten() \n for unused in range(len(to_plot), len(axlist)): \n axlist[unused].axis('off') \n plt.tight_layout()\n pdf_pages.savefig(fig, dpi=10) \n i = i + nplots_per_page\n plt.close()\n pdf_pages.close()\n \n\[email protected]()\[email protected]('input_filepath', type=click.Path(exists=True))\[email protected]('output_filepath', type=click.Path())\[email protected]('--mode', type=click.Choice(['features', 'score']))\n\ndef main(input_filepath, output_filepath, mode):\n df = pd.read_csv(input_filepath)\n target = 'SalePrice'\n features = df.columns\n\n if mode == 'features':\n colors = [1 for i in range(0, len(df))]\n visualize_features(df, features, target, colors, 'viridis', 3, (15,15), 6, output_filepath) \n if mode == 'score': \n features = features[1:len(features)] \n ts = transform_scores(df['Score'])\n visualize_features(df, features, target, ts, 'autumn_r', 3, (15,15), 6, output_filepath)\n \nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.7274701595306396, "alphanum_fraction": 0.7274701595306396, "avg_line_length": 64.75, "blob_id": "f36d65a7bf773c7fe36812425fc847d4d8b611d9", "content_id": "6355e6f5801a33cc4e0d97fab9eab9331c1f1513", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1846, "license_type": "no_license", "max_line_length": 322, "num_lines": 28, "path": "/docs_mgt/commands.rst", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "Commands\n========\n\nThe Makefile contains the central entry points for common tasks related to this project.\n\nPreparing the data\n^^^^^^^^^^^^^^^^^^\n* `make features` will clean and transform the indicated file ($IN) and output the cleaned data in CSV format to the indicated ($OUT) path. There are different modes ($MODE):\n\t- train : data will be cleaned, transformed and outliers will be removed\n\t- eval : data will be cleaned and transformed\n\t- test : data will be cleaned and transformed \n\nEvaluating the model\n^^^^^^^^^^^^^^^^^^^^\n* `make evaluate` will take the input data ($IN), split it into a training and a test set. The model is fitted to the training set and used to predict the target of the test set. Since the data from a single input source is split into a training and a test set, this data should not have been treated with outlier removal.\nAdditionally one can write input data with the predictions and the score to a csv file ($OUT) (for visualizations for example). The path to the original untreated data has also to be provided ($ORIGINAL) to allow writing the original non-transformed features to the file. \n\n\nUsing the model to make predictions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n* `make predict` will take the training data ($TRAIN) and the testing data ($TEST), fit the model to the training set and use it to predict the target of the test set. The predictions are written to a csv file ($OUT).\n\n\nVisualizing the data\n^^^^^^^^^^^^^^^^^^^^\n* `make visualize` will take the input data ($IN) and plot the features against the target (the SalePrice) and print the plots to a PDF file ($OUT). There are two different modes:\n\t- features : all features are plotted in described fashion\n\t- score : all features are plotted in described fashion and the points are coloured in function of the additional data column ‘Score’ \n" }, { "alpha_fraction": 0.5027027130126953, "alphanum_fraction": 0.6981981992721558, "avg_line_length": 15.818181991577148, "blob_id": "b3fae11a137d36d67ca17482653f6af8cf86a2e3", "content_id": "c9e3f61749d182ec4855211b187d6947d6de240e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 31, "num_lines": 66, "path": "/requirements.txt", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "alabaster==0.7.10\nappnope==0.1.0\nastroid==1.4.9\nBabel==2.4.0\nbleach==1.5.0\nchardet==3.0.4\nclick==6.7\ncycler==0.10.0\ndecorator==4.1.2\ndocutils==0.13.1\nentrypoints==0.2.3\nhtml5lib==0.999\nimagesize==0.7.1\nipykernel==4.6.1\nipython==6.1.0\nipython-genutils==0.2.0\nisort==4.2.15\njedi==0.10.2\nJinja2==2.9.6\njsonschema==2.6.0\njupyter-client==5.1.0\njupyter-core==4.3.0\nlazy-object-proxy==1.3.1\nMarkupSafe==0.23\nmatplotlib==2.0.2\nmistune==0.7.4\nnbconvert==5.2.1\nnbformat==4.3.0\nnose==1.3.7\nnotebook==5.0.0\nnumpy==1.13.1\nnumpydoc==0.6.0\npandas==0.20.3\npandocfilters==1.4.1\npexpect==4.2.1\npickleshare==0.7.4\nprompt-toolkit==1.0.14\npsutil==5.2.2\nptyprocess==0.5.2\npycodestyle==2.3.1\npyflakes==1.5.0\nPygments==2.2.0\npylint==1.6.4\npyparsing==2.2.0\npython-dateutil==2.6.1\npytz==2017.2\npyzmq==16.0.2\nQtAwesome==0.4.4\nqtconsole==4.3.0\nQtPy==1.2.1\nrequests==2.14.2\nrope-py3k==0.9.4.post1\nscikit-learn==0.19.0\nscipy==0.19.1\nsimplegeneric==0.8.1\nsix==1.10.0\nsnowballstemmer==1.2.1\nSphinx==1.6.2\nsphinxcontrib-websupport==1.0.1\nspyder==3.2.0\nterminado==0.6\ntestpath==0.3\ntornado==4.5.1\ntraitlets==4.3.2\nwcwidth==0.1.7\nwrapt==1.10.10\n" }, { "alpha_fraction": 0.6297455430030823, "alphanum_fraction": 0.6489361524581909, "avg_line_length": 35.595420837402344, "blob_id": "9fc3c071056add5cee2638ce2fd801f94946edb5", "content_id": "4c5d16c2de4acb67fddcf70ad4f9ef72c0ae9bd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4794, "license_type": "no_license", "max_line_length": 104, "num_lines": 131, "path": "/src/models/predict_model-best.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "import click\nimport csv\nimport numpy as np\nimport pandas as pd\nimport train_model\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_selection import RFE\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.linear_model import Lasso\nfrom sklearn.svm import SVR\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neighbors import KNeighborsRegressor\n\n\[email protected]()\[email protected]('train_filepath', type=click.Path(exists=True))\[email protected]('test_filepath', type=click.Path(exists=True))\[email protected]('predict_filepath', type=click.Path())\ndef main(train_filepath, test_filepath, predict_filepath):\n \"\"\"\n Reads training data and trains model from train_model.py on it. Then reads test data\n and uses model to make prediction for test data. This prediction is then written to the output file.\n \"\"\"\n # read the prepared data\n X_train = pd.read_csv(train_filepath)\n X_test = pd.read_csv(test_filepath) \n \n # split training data in features and target\n y_train = X_train['SalePrice']\n X_train = X_train.drop(['SalePrice'], axis=1)\n\n # make sure test and training dataset have the same columns\n col_to_add = np.setdiff1d(X_train.columns, X_test.columns)\n col_to_rem = np.setdiff1d(X_test.drop('Id', axis=1).columns, X_train.columns)\n for c in col_to_add:\n X_test[c] = 0\n X_test = X_test.drop(col_to_rem, axis=1)\n\n # make sure column order is the same for training and test dataset\n X_test = X_test[X_train.columns]\n\n# features = ['LotFrontage', 'LotArea', 'OverallQual', 'OverallCond', 'YearBuilt',\n# 'YearRemodAdd', 'MasVnrArea', 'ExterQual', 'BsmtQual', 'BsmtExposure',\n# 'BsmtUnfSF', '1stFlrSF', '2ndFlrSF', 'GrLivArea', 'KitchenQual',\n# 'FireplaceQu', 'GarageYrBlt', 'GarageCars', 'GarageArea', 'WoodDeckSF',\n# 'OpenPorchSF', 'ScreenPorch', 'MSZoning_C (all)',\n# 'Neighborhood_Crawfor', 'Neighborhood_StoneBr', 'Condition1_Norm',\n# 'Exterior1st_BrkFace', 'Functional_Typ', 'SaleType_New',\n# 'SaleCondition_Abnorml', 'BsmtFinSF']\n\n# gbr = GradientBoostingRegressor(max_depth=4)\n# gbr.fit(X_train[features], y_train)\n# gbr_train = gbr.predict(X_train[features])\n#\n# \n# min_max_scaler = MinMaxScaler()\n# X_train_minmax = min_max_scaler.fit_transform(X_train[features])\n# X_test_minmax = min_max_scaler.transform(X_test[features])\n##\n# lasso = Lasso(alpha=0.01, max_iter=50000)\n# lasso.fit(X_train_minmax, y_train)\n# lasso_train = lasso.predict(X_train_minmax)\n#\n# svr_rbf = SVR(kernel='linear', C=1000)\n# svr_rbf.fit(X_train_minmax, y_train)\n# svr_train = svr_rbf.predict(X_train_minmax)\n#\n# knb = KNeighborsRegressor(n_neighbors=5)\n# knb.fit(X_train[features], y_train)\n# knn_train = knb.predict(X_train[features])\n#\n# training = pd.DataFrame(X_train[features])\n# training['GBR'] = gbr_train\n# training['LASSO'] = lasso_train\n# #training['SVR'] = svr_train\n# training['KNN'] = knn_train\n#\n#\n# gbr_test = gbr.predict(X_test[features])\n# lasso_test = lasso.predict(X_test_minmax)\n# svr_test = svr_rbf.predict(X_test_minmax)\n# knn_test = knb.predict(X_test[features])\n#\n# testing = pd.DataFrame(X_test[features])\n# testing['GBR'] = gbr_test\n# testing['LASSO'] = lasso_test\n# #testing['SVR'] = svr_test\n# testing['KNN'] = knn_test\n#\n# mkn = KNeighborsRegressor(n_neighbors=50, weights='distance')\n# mkn.fit(training, y_train)\n\n \n pipe = train_model.build_fit_pipe(X_train, y_train) \n prediction = pipe.predict(X_test)\n\n\n\n# prediction = []\n# for g,l in zip(gbr_prediction, lasso_prediction):\n # prediction.append(0.2*l + 0.8*g)\n \n #0.3 0.7 - 1708-lasso02 - 0.12963\n #0.2 0.8 - 1708-lasso03 - 0.12916 - improvement by using lasso on scaled data : 0.12858\n #0.1 0.9 - 1708-lasso04 - 0.13056\n \n#\n# rfegbr = GradientBoostingRegressor()\n# rfe = RFE(estimator=rfegbr, n_features_to_select=10, step=1) \n# gbr = GradientBoostingRegressor(max_depth=4, learning_rate=0.1)\n# pipe = Pipeline([(\"rfe\", rfe), (\"gbr\", gbr)])\n# pipe.fit(X_train, y_train)\n# prediction = pipe.predict(X_test)\n\n \n # build, fit and predict\n# model = train_model.build_fit_model(X_train.drop('Id', axis=1), y_train)\n# prediction = model.predict(X_test.drop('Id', axis=1))\n \n # write prediction to output file\n result = zip(X_test['Id'], prediction) \n with open(predict_filepath, 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow([\"Id\", \"SalePrice\"])\n for Id, pred in result:\n writer.writerow([Id, pred])\n print(\"ID: {}, P: {}\".format(Id, pred))\n \n\nif __name__ == '__main__': \n main()\n" }, { "alpha_fraction": 0.6634615659713745, "alphanum_fraction": 0.6668472290039062, "avg_line_length": 36.67346954345703, "blob_id": "e4368275ea220d8baff5ee600408b8a77aac83f0", "content_id": "bf49ac11caaeabd8a41f37360d5e6b1cd74ee5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7384, "license_type": "no_license", "max_line_length": 137, "num_lines": 196, "path": "/src/features/build_features.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "import click\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import IsolationForest\n\n\ndef read_raw_data(input_filepath):\n \"\"\"\n Reads CSV file from input_filepath and returns a Pandas dataframe\n \n :param input_filepath: path to csv file containing data to be read\n :type input_filepath: string\n :return: dataframe containing data from input_filepath\n :rtype: pandas dataframe\n \"\"\"\n return pd.read_csv(input_filepath) \n\n\ndef drop_columns(df, todrop):\n \"\"\"\n Returns a view of df with columns in list todrop removed\n \n :param df: dataframe from which a subset of columns should be dropped\n :type df: pandas dataframe \n :param todrop: list of column names to be dropped from df\n :type df: list of strings\n :return: view of the dataframe wihtout the columns listed in todrop\n :rtype: pandas dataframe \n \"\"\"\n return df.drop(todrop, axis=1)\n \n\ndef transform_ordinals(df): \n \"\"\"\n Returns view of df with nominal encodings of the ordinal features \n transformed to numeric encoding (in order to allow ordering).\n The list of features to be modified is hardcoded in the function.\n \n :param df: dataframe on which the encoding of ordinal features should be modified\n :type df: pandas dataframe \n :return: view of dataframe where ordinal features have been encoded numerically\n :rtype: pandas dataframe \n \"\"\"\n # transform ordinal features represented as categories to numeric\n # this allows the model to reason about the distance between different values\n ordinals = ['ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'HeatingQC',\n 'KitchenQual', 'FireplaceQu', 'GarageQual', 'GarageCond', 'PoolQC']\n \n # First uniformize the set of string values\n valmap = {'Mn': 'Po', 'No': np.nan} \n df[ordinals] = df[ordinals].replace(valmap)\n \n # replace the NA values with an empty string so they can be used as key\n # account in the next mapping\n df[ordinals] = df[ordinals].fillna('')\n \n valmap = {'': 0, 'Po': 1, 'Fa': 2, 'Av': 3, 'TA': 3, 'Gd': 4, 'Ex': 5} \n df[ordinals] = df[ordinals].replace(valmap)\n df[ordinals] = df[ordinals].astype(int)\n \n return df\n \n\ndef transform_categoricals(df):\n \"\"\"\n Returns tuple (v, catmap). Where v is view of df with categorical features \n having been replaced by multiple boolean features using One Hot Encoding; \n catmap is a dictionary mapping original feature to features it has been \n replaced with. \n \n :param df: dataframe on which the encoding of categorical features should be modified\n :type df: pandas dataframe \n :return: view of dataframe where categorical features have been one hot encoded\n :rtype: pandas dataframe \n \"\"\"\n df['MSSubClass'] = df['MSSubClass'].astype(str)\n oldcolumns = df.columns\n categoricals = df.select_dtypes(include=['object', 'category']).columns \n df = pd.get_dummies(df)\n cat_map = {}\n newcolumns = list(set(df.columns) - set(oldcolumns))\n for cat in categoricals:\n categories = filter(lambda x: x.startswith(str(cat+\"_\")), newcolumns)\n cat_map[cat] = list(categories)\n \n return df, cat_map\n\n\ndef correct_garageyrblt(df):\n \"\"\"\n Returns view of df where the year in which garage was built \n (feature GarageYrBlt), if smaller than year in which house was built \n (feature YearBuilt), is defaulted to the latter value\n \n :param df: dataframe on which value of the feature 'GarageYrBlt' should be corrected\n :type df: pandas dataframe \n :return: view of dataframe where concerned values have been corrected\n :rtype: pandas dataframe \n \"\"\"\n # default NAs to 0 \n df['GarageYrBlt'] = df['GarageYrBlt'].fillna(0)\n\n # correct the garage years\n df['GarageYrBlt'] = np.where((df['YearBuilt'] > df['GarageYrBlt']) & \n (df['GarageYrBlt'] > 0), df['YearBuilt'], df['GarageYrBlt'])\n df['GarageYrBlt'] = df['GarageYrBlt'].astype(int)\n \n return df\n\n\ndef aggregate_bsmt(df):\n \"\"\"\n Returns view of df where feature TotalBsmtSF, BsmtFinSF1, BsmtFinSF2 have \n been replace by sole feature BsmtFinSF\n \n :param df: dataframe on which columns relating to finished basement surface have been merged\n :type df: pandas dataframe \n :return: view of dataframe where original columns have been replaced\n :rtype: pandas dataframe \n \"\"\"\n df['BsmtFinSF'] = df['BsmtFinSF1'] + df['BsmtFinSF2']\n df = df.drop(['TotalBsmtSF', 'BsmtFinSF1', 'BsmtFinSF2'], axis=1)\n \n return df \n\n\ndef revert_to_original(transformed_df, categorical_map, original_features):\n \"\"\"\n Utility function allowing to revert a dataframe where categoricals have been\n transformed to dummy features to its original form with categoricals.\n \n :param transformed_df: dataframe which has been transformed using one hot encoding\n :param categorical_map: dictionary mapping original categorical features to dummy features\n :param original_features: list of column names of the original dataframe before transformation\n :type transformed_df: pandas dataframe \n :type categorical_map: dictionary key=original feature, value=list of corresponding dummy features \n :type original_features: list of strings\n :return: view of transformed_df where the dummy features encoding a category have been replaced with the original categorical feature\n :rtype: pandas dataframe \n\n note:: inspired by https://tomaugspurger.github.io/categorical-pipelines.html \n \"\"\" \n \n series = []\n categorical = [k for k in categorical_map.keys()]\n non_categorical = list(set(original_features) - set(categorical)) \n for col, dums in categorical_map.items(): \n code_dict = {k:v for (v,k) in enumerate(dums)} \n categories = transformed_df[dums].idxmax(axis=1)\n codes = [code_dict[k] for k in categories]\n cats = pd.Categorical.from_codes(codes, [d[len(col)+1:len(d)] for d in dums])\n series.append(pd.Series(cats, name=col)) \n cat_df = pd.DataFrame(series).T\n df = pd.concat([transformed_df[non_categorical], cat_df], axis=1) \n df = df[original_features]\n \n return df \n \n\[email protected]()\[email protected]('input_filepath', type=click.Path(exists=True))\[email protected]('output_filepath', type=click.Path())\[email protected]('--mode', type=click.Choice(['test', 'train', 'eval']))\ndef main(input_filepath, output_filepath, mode):\n\n # read original data into data frame\n df = read_raw_data(input_filepath) \n \n # represent ordinal features as numeric feature to allow\n # ordering between them \n df = transform_ordinals(df)\n\n # perform OneHotEncoding on categorical variables\n df, cat_map = transform_categoricals(df)\n \n df = aggregate_bsmt(df)\n \n # correct the garage years\n df = correct_garageyrblt(df)\n\n # default NAs to 0 \n df = df.fillna(0)\n\n if mode == 'train':\n # remove outliers for TRAINING DATA\n clf = IsolationForest(random_state=0)\n clf.fit(df)\n outlier = clf.predict(df) \n df = df[outlier == 1] \n \n # save the result of this processing as interim data\n df.to_csv(output_filepath, index=False)\n \n\nif __name__ == '__main__': \n main()\n" }, { "alpha_fraction": 0.5749506950378418, "alphanum_fraction": 0.5749506950378418, "avg_line_length": 38.72549057006836, "blob_id": "28a756ecd5f29d268e30ca4e4cf7b6ae2cb5c774", "content_id": "39622cd0a6de961d9887b5fafa094986b6ab1687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2228, "license_type": "no_license", "max_line_length": 200, "num_lines": 51, "path": "/README.md", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "HousePrices\n==============================\n\nKaggle competition - predict sales prices of houses sold in Ames, Iowa\n\nThis project contains the sources, notebooks and makefiles I used to generate submissions for the HousePrices Kaggle competition (https://www.kaggle.com/c/house-prices-advanced-regression-techniques).\n\nSource code documentation under : https://fmassen.github.io/houseprices/\n\n<p>Project based on the <a target=\"_blank\" href=\"https://drivendata.github.io/cookiecutter-data-science/\">cookiecutter data science project template</a>. #cookiecutterdatascience</p>\n\nProject Organization\n------------\n\n ├── Makefile <- Makefile with commands like `make features` or `make predict`, …\n │\n ├── README.md <- The top-level README. \n │ \n ├── docs <- Sphinx documentation.\n │\n ├── models <- Predictions made using the model.\n │\n ├── notebooks <- Jupyter notebooks for data and model exploration.\n │\n ├── references <- Classification of input data.\n │\n ├── reports <- /\n │   └── figures <- Generated graphics and figures.\n │\n ├── requirements.txt <- The requirements file for reproducing the analysis environment, e.g.\n │ generated with `pip freeze > requirements.txt`\n │\n └─── src <- Source code for use in this project.\n    ├── __init__.py <- Makes src a Python module.\n │ │ │\n    ├── features <- Scripts to turn raw data into features for modeling.\n    │   └── build_features.py\n │\n    ├── models <- Scripts to train models and then use trained models to make \n │ │ predictions.\n    │   ├── StackingTransformer.py \n    │   ├── train_model.py \t\n    │   ├── evaluate_model.py\n    │   └── predict_model.py\n │\n    └── visualization <- Scripts to create exploratory and results oriented visualizations.\n    └── visualize.py\n \n\n\n--------\n\n\n" }, { "alpha_fraction": 0.6362107396125793, "alphanum_fraction": 0.6406950950622559, "avg_line_length": 36.16666793823242, "blob_id": "08f089df2904fe9da9076d0c352c222517ca43ff", "content_id": "4e4ea163047a9b0842634c91a9bccddccd194afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 104, "num_lines": 48, "path": "/src/models/predict_model.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "import click\nimport csv\nimport numpy as np\nimport pandas as pd\nimport train_model\n\[email protected]()\[email protected]('train_filepath', type=click.Path(exists=True))\[email protected]('test_filepath', type=click.Path(exists=True))\[email protected]('predict_filepath', type=click.Path())\ndef main(train_filepath, test_filepath, predict_filepath):\n \"\"\"\n Reads training data and trains model from train_model.py on it. Then reads test data\n and uses model to make prediction for test data. This prediction is then written to the output file.\n \"\"\"\n # read the prepared data\n X_train = pd.read_csv(train_filepath)\n X_test = pd.read_csv(test_filepath) \n \n # split training data in features and target\n y_train = X_train['SalePrice']\n X_train = X_train.drop(['SalePrice'], axis=1)\n\n # make sure test and training dataset have the same columns\n col_to_add = np.setdiff1d(X_train.columns, X_test.columns)\n col_to_rem = np.setdiff1d(X_test.drop('Id', axis=1).columns, X_train.columns)\n for c in col_to_add:\n X_test[c] = 0\n X_test = X_test.drop(col_to_rem, axis=1)\n\n # make sure column order is the same for training and test dataset\n X_test = X_test[X_train.columns]\n \n pipe = train_model.build_fit_pipe(X_train.drop('Id', axis=1), y_train) \n prediction = pipe.predict(X_test.drop('Id', axis=1))\n \n # write prediction to output file\n result = zip(X_test['Id'], prediction) \n with open(predict_filepath, 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow([\"Id\", \"SalePrice\"])\n for Id, pred in result:\n writer.writerow([Id, pred])\n print(\"ID: {}, P: {}\".format(Id, pred))\n \n\nif __name__ == '__main__': \n main()\n" }, { "alpha_fraction": 0.7192727327346802, "alphanum_fraction": 0.7221817970275879, "avg_line_length": 41.9375, "blob_id": "c8de7fb37f42387262f0f2587134d948e948ea7d", "content_id": "cf6e8795684a4778e959feef21024079ddf38748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 129, "num_lines": 32, "path": "/src/models/train_model.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "from StackingTransformer import StackingTransformer\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_selection import RFECV\n\ndef build_fit_pipe(X, y): \n \"\"\"\n Builds and fits a 3-stage pipeline on the training data passed as argument\n Returns the fitted pipeline.\n \n The 3 stages of the pipe are:\n - Feature selection using Recursive Feature Elimination with Cross Validation\n - Transformation - this stage actually takes the features and produces predictions with up to 4 different models\n - Regression - a linear regression model is trained on the output of the different models and produces a final prediction\n\n The Transformation stage is executed using the custom Transformer StackingTransformer.\n \n :param X: feature data to which to fit the pipe\n :param y: target data to which to fit the pipe\n :return: fitted pipeline\n :rtype: Pipeline object fitted to X,y\n\n \n \"\"\" \n rfecvgbr = GradientBoostingRegressor()\n rfecv = RFECV(estimator=rfecvgbr, step=1) \n st = StackingTransformer(True, True, False, False) \n lr = LinearRegression() \n pipe = Pipeline([(\"reducer\", rfecv), (\"stackTransformer\", st), (\"linearRegression\", lr)]) \n pipe.fit(X, y)\n return pipe\n\n" }, { "alpha_fraction": 0.6057209968566895, "alphanum_fraction": 0.6095684170722961, "avg_line_length": 39.304054260253906, "blob_id": "090148a4ada78db8fae350dc3a2150a7e34815fa", "content_id": "6fa4e958ed3f6c80245b1091e77d310017e2f6e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5978, "license_type": "no_license", "max_line_length": 156, "num_lines": 148, "path": "/src/models/StackingTransformer.py", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "from sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.linear_model import Lasso\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.preprocessing import MinMaxScaler\nimport itertools as it\nimport numpy as np\nimport pandas as pd\n\nclass StackingTransformer(BaseEstimator, TransformerMixin):\n \"\"\"\n Custom Transformer that fits up to 4 different models and transforms input data\n into 4 different predictions. \n \n The 4 different models are : \n - Gradient Boosting Regressor\n - Lasso Regression\n - Support Vector Regressor\n - K-nearest Neighbors Regressor\n \n The models to use can be specified using boolean parameters.\n Caution : The parameters of the models have not been optimized, but have been set by hand. \n Some of them can be specified using the transformer's parameters.\n \"\"\"\n \n def __init__(self, dogbr=True, dolasso=False, dosvr=False, doknn=False, gbr_maxdepth=4, lasso_max_iter=50000, svr_kernel='linear', svr_C=1000, kn_n=20):\n \"\"\"\n Initializes the transformer object. The models are not yet initialized, this is done upon calling the fit method.\n \n :param dogbr: indicates whether gradient bossting regression should be used (True) or not (False)\n :param dolasso: indicates whether Lasso regression should be used (True) or not (False)\n :param dosvr: indicates whether support vector regression model should be used (True) or not (False)\n :param doknn: indicates whether k-nearest neighbors regression should be used (True) or not (False)\n :param gbr_maxdepth: maximum depth of gradient boosting regressor trees\n :param lasso_max_iter: maximum number of iterations for lasso regression\n :param svr_kernel: type of kernel to use with the support vector regression\n :param svr_C: value of penalty parameter C of the svm\n :param kn_n: number of neighbors (k) in the k-nearerst neighbors regression\n :type dogbr: boolean\n :type dolasso: boolean\n :type dosvr: boolean\n :type doknn: boolean\n :type gbr_maxdepth: int\n :type lasso_max_iter: int\n :type svr_kernel: string ('linear', 'polynomial', 'rbf')\n :type svr_C: int\n :type kn_n: int\n :return: void\n \"\"\"\n \n self.gbr_maxdepth = gbr_maxdepth\n self.lasso_max_iter = lasso_max_iter\n self.svr_kernel = svr_kernel\n self.svr_C = svr_C\n self.kn_n = kn_n\n self.dogbr = dogbr\n self.dolasso = dolasso\n self.dosvr = dosvr\n self.doknn = doknn\n\n\n def get_params(self, deep=True):\n # suppose this estimator has parameters \"alpha\" and \"recursive\"\n return {\"dogbr\": self.dogbr, \n \"dolasso\": self.dolasso,\n \"dosvr\": self.dosvr,\n \"doknn\": self.doknn,\n \"gbr_maxdepth\" : self.gbr_maxdepth,\n \"lasso_max_iter\" : self.lasso_max_iter,\n \"svr_kernel\" : self.svr_kernel,\n \"svr_C\" : self.svr_C,\n \"kn_n\" : self.kn_n\n }\n\n\n def set_params(self, **parameters):\n for parameter, value in parameters.items():\n self.__setattr__(parameter, value)\n return self\n\n\n\n def fit(self, X, y):\n \"\"\"\n Initializes the models and fits them to the data.\n Gradient Boosting Regressor and K-nearest Neighbors Regressor are fit on unscaled data.\n Lasso and Support Vector Regressor are fit on log-transformed y and scaled X.\n X is scaled using a MinMaxScaler\n \n :param X: feature data on which transformer is to be fit\n :param y: target data on which transformer is to be fit\n :return: self\n \"\"\"\n \n if self.dogbr:\n self.gbr_ = GradientBoostingRegressor(max_depth=self.gbr_maxdepth)\n if self.dolasso: \n self.lasso_ = Lasso(max_iter=self.lasso_max_iter, alpha=0.01)\n if self.dosvr: \n self.svr_ = SVR(kernel=self.svr_kernel, C=self.svr_C)\n if self.doknn: \n self.kn_ = KNeighborsRegressor(n_neighbors=self.kn_n, weights='distance')\n \n if self.dosvr | self.dolasso:\n y_log = np.log1p(y)\n self.scaler_ = MinMaxScaler() \n X_scaled = self.scaler_.fit_transform(X)\n \n if self.dogbr:\n self.gbr_.fit(X, y)\n if self.dolasso: \n self.lasso_.fit(X_scaled, y_log)\n if self.dosvr: \n self.svr_.fit(X_scaled, y_log)\n if self.doknn: \n self.kn_.fit(X, y)\n \n return self\n\n\n def transform(self, X):\n \"\"\"\n Makes predictions using the selected models and returns a dataframe containing those predictions.\n \n :param X: feature data based on which predictions are to be made\n :return: X_transformed - a dataframe with #columns = #selected models containing predictions\n :rtype: pandas dataframe\n \"\"\"\n\n models = ['GBR', 'LASSO', 'SVR', 'KNN']\n mask = [self.dogbr, self.dolasso, self.dosvr, self.doknn] \n columns = list(it.compress(models, mask))\n index = np.arange(0, len(np.asarray(X)))\n X_transformed = pd.DataFrame(columns=columns, index=index)\n X_transformed = X_transformed.fillna(0)\n if self.dosvr | self.dolasso:\n X_scaled = self.scaler_.transform(X) \n if self.dogbr:\n X_transformed['GBR'] = self.gbr_.predict(X)\n if self.dolasso: \n X_transformed['LASSO'] = np.expm1(self.lasso_.predict(X_scaled))\n if self.dosvr:\n X_transformed['SVR'] = np.expm1(self.svr_.predict(X_scaled))\n if self.doknn:\n X_transformed['KNN'] = self.kn_.predict(X)\n\n return X_transformed \n " }, { "alpha_fraction": 0.5195121765136719, "alphanum_fraction": 0.5195121765136719, "avg_line_length": 13.068965911865234, "blob_id": "465f4547960eeceba431cf0919df3a30441b2e31", "content_id": "a8ad858d7031ae187decf0eaa426e91884e23f39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 410, "license_type": "no_license", "max_line_length": 35, "num_lines": 29, "path": "/docs_mgt/modules_classes.rst", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "Modules and classes\n===================\n\nThe custom Transfomer\n------------------------\n\n.. automodule:: StackingTransformer\n\t:members:\n\n\nThe build_feature module\n------------------------\n\t\n.. automodule:: build_features\n\t:members:\n\n\nThe train_model module\n------------------------\n\n.. automodule:: train_model\n\t:members:\n\n\nThe visualize module\n------------------------\n\n.. automodule:: visualize\n\t:members:\n\n\n" }, { "alpha_fraction": 0.7661097645759583, "alphanum_fraction": 0.7661097645759583, "avg_line_length": 58.71428680419922, "blob_id": "faaf80f7cf4363fb823f83fdf1f3687fe3ad0e12", "content_id": "3711ae32179f0568068b2a637b360e53e4b8d6ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 423, "license_type": "no_license", "max_line_length": 186, "num_lines": 7, "path": "/docs_mgt/getting-started.rst", "repo_name": "blazysecon/houseprices", "src_encoding": "UTF-8", "text": "Getting started\n===============\n\nTrain and test data sets should be downloaded from Kaggle (https://www.kaggle.com/c/house-prices-advanced-regression-techniques) and put into data/raw/.\nNext the data needs to be prepared. Then the model can be evaluated on the training set or used to produce predictions on the test set. A small set of visualisations can also be created.\n\nAll commands are described under “Commands”\n\n" } ]
13
sizhu1994/myleetcode
https://github.com/sizhu1994/myleetcode
44793b1aee9a58ad10652cc39a0324f56302aa57
3141626700d0629a065b71707a4dd557311243cd
59303799c4f3cb985d6e2db9eddc6a7729b55d7d
refs/heads/master
2021-01-12T05:52:20.057837
2016-12-28T09:00:45
2016-12-28T09:00:45
77,222,266
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5169491767883301, "alphanum_fraction": 0.5240113139152527, "avg_line_length": 25.185184478759766, "blob_id": "481fca04eb80684f2dff27b4922345a4a26ac866", "content_id": "b89b3ae2d7235caca7dd9eaf5c01692645a2b5df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 86, "num_lines": 27, "path": "/Longest_Substring_Without_Repeating_Characters003.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nGiven a string, find the length of the longest substring without repeating characters.\n'''\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n lstsstr = ''\n left = 0\n cache = {}\n for index,value in enumerate(s):\n if value in cache and cache[value] >= left:\n left = cache[value] + 1\n cache[value] = index\n if len(lstsstr) < index - left + 1 :\n lstsstr = s[left:index+1]\n return lstsstr\n\n\nif __name__ == '__main__':\n s = Solution()\n l = 'pwwkew'\n print s.lengthOfLongestSubstring(l)\n\n" }, { "alpha_fraction": 0.43963783979415894, "alphanum_fraction": 0.454728364944458, "avg_line_length": 26.61111068725586, "blob_id": "ddd2e5d87b6c89805c85fe56822cc723670754a7", "content_id": "e779b920f7d03f96039adc392cdf51c42fd94ce0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 115, "num_lines": 36, "path": "/Longest_Palindromic_Substring005.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nGiven a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n'''\nclass Solution(object):\n def palindrome(self,s,left,right):\n while s[left] == s[right] :\n left -= 1\n right += 1\n if left<0 or right >= len(s):\n break\n return s[left+1:right]\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n maxs = ''\n for i in range(len(s)-1):\n if s[i] == s[i+1]:\n sm = self.palindrome(s,i,i+1)\n if len(maxs) < len(sm):\n maxs = sm\n for i in range(len(s)-2):\n if s[i] == s[i+2]:\n sm = self.palindrome(s,i,i+2)\n if len(maxs) < len(sm):\n maxs = sm\n return maxs\n\n\nif __name__ == '__main__':\n s = Solution()\n l = 'cbbd'\n print s.longestPalindrome(l)\n" }, { "alpha_fraction": 0.5698005557060242, "alphanum_fraction": 0.5840455889701843, "avg_line_length": 27.079999923706055, "blob_id": "a831325327b2c10f3a16f845b470ae408e0cfd94", "content_id": "9bff022ad4ca4e9057c5446537b3a3528c9d5dff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 105, "num_lines": 25, "path": "/Two_Sum_001.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nhttps://leetcode.com/problems/two-sum/\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\nYou may assume that each input would have exactly one solution.\n'''\n\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n hasbeen ={}\n for index, value in enumerate(nums):\n if target - value in hasbeen:\n return hasbeen[target-value],index+1\n hasbeen[value] = index + 1\n\n\nif __name__ == '__main__':\n s = Solution()\n print s.twoSum([2, 7, 11, 15],9)\n" }, { "alpha_fraction": 0.48249998688697815, "alphanum_fraction": 0.4983333349227905, "avg_line_length": 22.096153259277344, "blob_id": "ba975916167f55febda25b47cd67455a795259d9", "content_id": "4ab2e220f3cb5f66bbaed02fe1e9bca0fe27156b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "no_license", "max_line_length": 97, "num_lines": 52, "path": "/reverse-nodes-in-k-group025.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n'''\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\ndef setListNode(s):\n rel = ListNode(s[0])\n if len(s) == 1:\n return rel\n tail = rel\n for i in range(1,len(s)):\n tail.next = ListNode(s[i])\n tail = tail.next\n return rel\n\ndef getListNode(l):\n s = ''\n while l != None:\n s += l.val\n l = l.next\n return s\n\nclass Solution(object):\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n cur = head\n count = 0\n while cur != None and count != k:\n cur = cur.next\n count += 1\n if count == k :\n cur = self.reverseKGroup(cur, k)\n while count > 0:\n head.next, cur, head = cur, head, head.next\n count -= 1\n head = cur\n return head\n\nif __name__ == '__main__':\n s = Solution()\n l1 = setListNode('123456')\n l2 = s.reverseKGroup(l1,3)\n print getListNode(l2)" }, { "alpha_fraction": 0.45493561029434204, "alphanum_fraction": 0.4849785268306732, "avg_line_length": 19.30434799194336, "blob_id": "1794791757e57c2eb346de74ec31fea9f408a64d", "content_id": "fdaefe17ab88127af6a7c7c98a962bab8366b14c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 86, "num_lines": 23, "path": "/Palindrome_Number009.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nGiven a string, find the length of the longest substring without repeating characters.\n'''\n\nclass Solution(object):\n def isPalindrome(self, x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n newx = x\n s = 0\n while x != 0 :\n s = 10*s + x%10\n x /= 10\n return newx == s\n\nif __name__ == '__main__':\n s = Solution()\n x = 12332\n print s.isPalindrome(x)" }, { "alpha_fraction": 0.45843827724456787, "alphanum_fraction": 0.48740553855895996, "avg_line_length": 23.796875, "blob_id": "1a61d0565db3f892b2cd5433db12aba694fa8847", "content_id": "49c0767f70c46c0a86bb059a3696e27746ecab26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 138, "num_lines": 64, "path": "/Add_Two_Numbers_002.py", "repo_name": "sizhu1994/myleetcode", "src_encoding": "UTF-8", "text": "# coding:utf-8\n__author__ = '王丰宁'\n'''\nhttps://leetcode.com/problems/add-two-numbers/\nYou are given two linked lists representing two non-negative numbers.\nThe digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n'''\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\ndef setListNode(n):\n rel = ListNode(0)\n tail = rel\n while True:\n tail.val = n%10\n n /= 10\n if n != 0:\n tail.next = ListNode(0)\n tail = tail.next\n else:\n return rel\ndef getListNode(l):\n sums = 0\n pows = 1\n while l != None:\n sums += l.val * pows\n pows *= 10\n l = l.next\n return sums\n\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n rel = ListNode(0)\n tail = rel\n sum = 0\n while True:\n if l1 != None:\n sum += l1.val\n l1 = l1.next\n if l2 != None:\n sum += l2.val\n l2 = l2.next\n tail.val = sum % 10\n sum /= 10\n if ( l1 != None ) or ( l2 != None ) or ( sum != 0 ):\n tail.next = ListNode(0)\n tail = tail.next\n else :\n return rel\n\nif __name__ == '__main__':\n s = Solution()\n l1 = setListNode(342)\n l2 = setListNode(465)\n l3 = s.addTwoNumbers(l1,l2)\n print getListNode(l3)\n\n" } ]
6
aharley/neural_3d_mapping
https://github.com/aharley/neural_3d_mapping
20dd964fc8afe144eac8e05b5d6d8dc4140a4d40
8a60711bb39d0860f7ebf207aed77142f0fd3373
c7ea5ada88d37db67fdb75837c9a4101a3ff8e3b
refs/heads/master
2022-08-08T19:25:40.846794
2022-07-25T18:09:20
2022-07-25T18:09:20
240,620,738
35
4
null
null
null
null
null
[ { "alpha_fraction": 0.5367981791496277, "alphanum_fraction": 0.5532625317573547, "avg_line_length": 43.80952453613281, "blob_id": "bf580a61037d57777a8b9091ac9b0632265c557e", "content_id": "c9992bf366a6bcd41bdb5a0a4a7d11a4217ecd03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13180, "license_type": "no_license", "max_line_length": 143, "num_lines": 294, "path": "/model_carla_det.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import time\nimport torch\nimport torch.nn as nn\nimport hyperparams as hyp\nimport numpy as np\nimport os\n\nfrom model_base import Model\nfrom nets.feat3dnet import Feat3dNet\nfrom nets.detnet import DetNet\n\nimport utils.vox\nimport utils.samp\nimport utils.geom\nimport utils.misc\nimport utils.improc\nimport utils.basic\n# import utils.track\n# import frozen_flow_net\nimport utils.eval\n\n# from tensorboardX import SummaryWriter\n# from backend import saverloader, inputs\n# from torchvision import datasets, transforms\n\nnp.set_printoptions(precision=2)\nnp.random.seed(0)\n# EPS = 1e-6\n# MAX_QUEUE = 10 # how many items before the summaryWriter flushes\n\nclass CARLA_DET(Model):\n def initialize_model(self):\n print(\"------ INITIALIZING MODEL OBJECTS ------\")\n self.model = CarlaDetModel()\n if hyp.do_freeze_feat3d:\n self.model.feat3dnet.eval()\n self.set_requires_grad(self.model.feat3dnet, False)\n if hyp.do_freeze_det:\n self.model.detnet.eval()\n self.set_requires_grad(self.model.detnet, False)\n\nclass CarlaDetModel(nn.Module):\n def __init__(self):\n super(CarlaDetModel, self).__init__()\n if hyp.do_feat3d:\n self.feat3dnet = Feat3dNet(in_dim=4)\n if hyp.do_det:\n self.detnet = DetNet()\n \n def prepare_common_tensors(self, feed):\n results = dict()\n \n self.summ_writer = utils.improc.Summ_writer(\n writer=feed['writer'],\n global_step=feed['global_step'],\n log_freq=feed['set_log_freq'],\n fps=8,\n just_gif=True)\n global_step = feed['global_step']\n\n self.B = feed['set_batch_size']\n self.S = feed['set_seqlen']\n self.set_name = feed['set_name']\n\n # in det mode, we do not have much reason to have S>1\n assert(self.S==1)\n \n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n \n self.N = hyp.N\n self.Z, self.Y, self.X = hyp.Z, hyp.Y, hyp.X\n self.Z2, self.Y2, self.X2 = int(self.Z/2), int(self.Y/2), int(self.X/2)\n\n self.pix_T_cams = feed['pix_T_cams']\n set_data_format = feed['set_data_format']\n self.S = feed['set_seqlen']\n\n self.origin_T_camRs = feed['origin_T_camRs']\n self.origin_T_camXs = feed['origin_T_camXs']\n\n self.camX0s_T_camXs = utils.geom.get_camM_T_camXs(self.origin_T_camXs, ind=0)\n self.camXs_T_camX0s = __u(utils.geom.safe_inverse(__p(self.camX0s_T_camXs)))\n self.camR0s_T_camRs = utils.geom.get_camM_T_camXs(self.origin_T_camRs, ind=0)\n self.camRs_T_camR0s = __u(utils.geom.safe_inverse(__p(self.camR0s_T_camRs)))\n self.camRs_T_camXs = __u(torch.matmul(__p(self.origin_T_camRs).inverse(), __p(self.origin_T_camXs)))\n self.camXs_T_camRs = __u(__p(self.camRs_T_camXs).inverse())\n\n self.xyz_camXs = feed['xyz_camXs']\n \n if self.set_name=='test' or self.set_name=='val':\n scene_centroid_x = 0.0\n scene_centroid_y = 1.0\n scene_centroid_z = 18.0\n scene_centroid = np.array([scene_centroid_x,\n scene_centroid_y,\n scene_centroid_z]).reshape([1, 3])\n self.scene_centroid = torch.from_numpy(scene_centroid).float().cuda()\n self.vox_util = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=self.scene_centroid, assert_cube=True)\n else:\n # randomize a bit, as a form of data aug\n all_ok = False\n num_tries = 0\n while (not all_ok) and (num_tries < 100):\n scene_centroid_x = np.random.uniform(-8.0, 8.0)\n scene_centroid_y = np.random.uniform(-1.0, 3.0)\n scene_centroid_z = np.random.uniform(10.0, 26.0)\n scene_centroid = np.array([scene_centroid_x,\n scene_centroid_y,\n scene_centroid_z]).reshape([1, 3])\n self.scene_centroid = torch.from_numpy(scene_centroid).float().cuda()\n num_tries += 1\n all_ok = True\n self.vox_util = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=self.scene_centroid, assert_cube=True)\n # we want to ensure this gives us a few points inbound for each element\n inb = __u(self.vox_util.get_inbounds(__p(self.xyz_camXs), self.Z, self.Y, self.X, already_mem=False))\n # this is B x S x N\n num_inb = torch.sum(inb.float(), axis=2)\n # this is B x S\n \n if torch.min(num_inb) < 300:\n all_ok = False\n self.summ_writer.summ_scalar('centroid_sampling/num_tries', float(num_tries))\n self.summ_writer.summ_scalar('centroid_sampling/num_inb', torch.mean(num_inb).cpu().item())\n if num_tries >= 100:\n return False # not OK; do not train on this\n \n self.vox_size_X = self.vox_util.default_vox_size_X\n self.vox_size_Y = self.vox_util.default_vox_size_Y\n self.vox_size_Z = self.vox_util.default_vox_size_Z\n\n origin_T_camRs_ = self.origin_T_camRs.reshape(self.B, self.S, 1, 4, 4).repeat(1, 1, self.N, 1, 1).reshape(self.B*self.S, self.N, 4, 4)\n boxlists = feed['boxlists']\n self.scorelist_s = feed['scorelists']\n self.tidlist_s = feed['tidlists']\n boxlists_ = boxlists.reshape(self.B*self.S, self.N, 9)\n lrtlist_camRs_ = utils.misc.parse_boxes(boxlists_, origin_T_camRs_)\n self.lrtlist_camRs = lrtlist_camRs_.reshape(self.B, self.S, self.N, 19)\n self.lrtlist_camR0s = __u(utils.geom.apply_4x4_to_lrtlist(__p(self.camR0s_T_camRs), __p(self.lrtlist_camRs)))\n self.lrtlist_camXs = __u(utils.geom.apply_4x4_to_lrtlist(__p(self.camXs_T_camRs), __p(self.lrtlist_camRs)))\n self.lrtlist_camX0s = __u(utils.geom.apply_4x4_to_lrtlist(__p(self.camX0s_T_camXs), __p(self.lrtlist_camXs)))\n\n inbound_s = __u(utils.misc.rescore_lrtlist_with_inbound(\n __p(self.lrtlist_camX0s), __p(self.tidlist_s), self.Z, self.Y, self.X, self.vox_util))\n self.scorelist_s *= inbound_s\n\n for b in list(range(self.B)):\n if torch.sum(self.scorelist_s[:,0]) < (self.B/2): # not worth it; return early\n return False # not OK; do not train on this\n \n self.rgb_camXs = feed['rgb_camXs']\n self.summ_writer.summ_rgb('2d_inputs/rgb', self.rgb_camXs[:,0])\n \n # get 3d voxelized inputs\n self.occ_memXs = __u(self.vox_util.voxelize_xyz(__p(self.xyz_camXs), self.Z, self.Y, self.X))\n self.unp_memXs = __u(self.vox_util.unproject_rgb_to_mem(\n __p(self.rgb_camXs), self.Z, self.Y, self.X, __p(self.pix_T_cams)))\n # these are B x C x Z x Y x X\n self.summ_writer.summ_occs('3d_inputs/occ_memXs', torch.unbind(self.occ_memXs, dim=1))\n self.summ_writer.summ_unps('3d_inputs/unp_memXs', torch.unbind(self.unp_memXs, dim=1), torch.unbind(self.occ_memXs, dim=1))\n\n return True # OK\n \n def run_train(self, feed):\n total_loss = torch.tensor(0.0).cuda()\n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n results = dict()\n\n # eliminate the seq dim, to make life easier\n lrtlist_camX = self.lrtlist_camXs[:, 0]\n rgb_camX0 = self.rgb_camXs[:,0]\n occ_memX0 = self.occ_memXs[:,0]\n unp_memX0 = self.unp_memXs[:,0]\n tidlist_g = self.tidlist_s[:,0]\n scorelist_g = self.scorelist_s[:,0]\n\n if hyp.do_feat3d:\n # start with a 4-channel feature map;\n feat_memX0_input = torch.cat([\n occ_memX0,\n unp_memX0*occ_memX0,\n ], dim=1)\n\n # featurize\n feat3d_loss, feat_halfmemX0 = self.feat3dnet(\n feat_memX0_input,\n self.summ_writer)\n total_loss += feat3d_loss\n\n self.summ_writer.summ_feat('feat3d/feat_memX0_input', feat_memX0_input, pca=True)\n self.summ_writer.summ_feat('feat3d/feat_halfmemX0', feat_halfmemX0, pca=True)\n \n if hyp.do_det:\n # this detector can only handle axis-aligned boxes (like rcnn)\n # so first let's inflate the boxes to the nearest axis lines\n axlrtlist_camX = utils.geom.inflate_to_axis_aligned_lrtlist(lrtlist_camX)\n lrtlist_memX = self.vox_util.apply_mem_T_ref_to_lrtlist(lrtlist_camX, self.Z, self.Y, self.X)\n axlrtlist_memX = utils.geom.inflate_to_axis_aligned_lrtlist(lrtlist_memX)\n self.summ_writer.summ_lrtlist_bev(\n 'det/boxlist_g',\n occ_memX0[0:1],\n lrtlist_memX[0:1],\n scorelist_g,\n tidlist_g, \n self.vox_util, \n already_mem=True)\n self.summ_writer.summ_lrtlist_bev(\n 'det/axboxlist_g',\n occ_memX0[0:1],\n axlrtlist_memX[0:1],\n scorelist_g,\n tidlist_g, \n self.vox_util, \n already_mem=True)\n \n lrtlist_halfmemX = self.vox_util.apply_mem_T_ref_to_lrtlist(lrtlist_camX, self.Z2, self.Y2, self.X2)\n axlrtlist_halfmemX = utils.geom.inflate_to_axis_aligned_lrtlist(lrtlist_halfmemX)\n\n det_loss, boxlist_halfmemX_e, scorelist_e, tidlist_e, pred_objectness, sco, ove = self.detnet(\n axlrtlist_halfmemX,\n scorelist_g,\n feat_halfmemX0,\n self.summ_writer)\n total_loss += det_loss\n \n lrtlist_halfmemX_e = utils.geom.convert_boxlist_to_lrtlist(boxlist_halfmemX_e)\n lrtlist_camX_e = self.vox_util.apply_ref_T_mem_to_lrtlist(lrtlist_halfmemX_e, self.Z2, self.Y2, self.X2)\n\n lrtlist_e = lrtlist_camX_e[0:1]\n # lrtlist_g = lrtlist_camX[0:1] # true boxes\n lrtlist_g = axlrtlist_camX[0:1] # axis-aligned boxes \n scorelist_e = scorelist_e[0:1]\n scorelist_g = scorelist_g[0:1]\n lrtlist_e, lrtlist_g, scorelist_e, scorelist_g = utils.eval.drop_invalid_lrts(\n lrtlist_e, lrtlist_g, scorelist_e, scorelist_g)\n\n lenlist_e, _ = utils.geom.split_lrtlist(lrtlist_e)\n clist_e = utils.geom.get_clist_from_lrtlist(lrtlist_e)\n lenlist_g, _ = utils.geom.split_lrtlist(lrtlist_g)\n clist_g = utils.geom.get_clist_from_lrtlist(lrtlist_g)\n\n _, Ne, _ = list(lrtlist_e.shape)\n _, Ng, _ = list(lrtlist_g.shape)\n # only summ if there is at least one pred and one gt\n if Ne > 0 and Ng > 0:\n lrtlist_e_ = lrtlist_e.unsqueeze(2).repeat(1, 1, Ng, 1).reshape(1, Ne * Ng, -1)\n lrtlist_g_ = lrtlist_g.unsqueeze(1).repeat(1, Ne, 1, 1).reshape(1, Ne * Ng, -1)\n ious, _ = utils.geom.get_iou_from_corresponded_lrtlists(lrtlist_e_, lrtlist_g_)\n ious = ious.reshape(1, Ne, Ng)\n ious_e = torch.max(ious, dim=2)[0]\n self.summ_writer.summ_lrtlist(\n 'det/boxlist_eg',\n rgb_camX0[0:1],\n torch.cat((lrtlist_g, lrtlist_e), dim=1),\n torch.cat((ious_e.new_ones(1, Ng), ious_e), dim=1),\n torch.cat([torch.ones(1, Ng).long().cuda(),\n torch.ones(1, Ne).long().cuda()+1], dim=1),\n self.pix_T_cams[0:1, 0])\n self.summ_writer.summ_lrtlist_bev(\n 'det/boxlist_bev_eg',\n occ_memX0[0:1],\n torch.cat((lrtlist_g, lrtlist_e), dim=1),\n torch.cat((ious_e.new_ones(1, Ng), ious_e), dim=1),\n torch.cat([torch.ones(1, Ng).long().cuda(),\n torch.ones(1, Ne).long().cuda()+1], dim=1),\n self.vox_util, \n already_mem=False)\n\n ious = [0.3, 0.4, 0.5, 0.6, 0.7]\n maps_3d, maps_2d = utils.eval.get_mAP_from_lrtlist(lrtlist_e, scorelist_e, lrtlist_g, ious)\n for ind, overlap in enumerate(ious):\n self.summ_writer.summ_scalar('ap_3d/%.2f_iou' % overlap, maps_3d[ind])\n self.summ_writer.summ_scalar('ap_bev/%.2f_iou' % overlap, maps_2d[ind])\n\n \n self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n return total_loss, results, False\n \n \n def forward(self, feed):\n data_ok = self.prepare_common_tensors(feed)\n\n if not data_ok:\n # return early\n total_loss = torch.tensor(0.0).cuda()\n return total_loss, None, True\n else:\n if self.set_name=='train':\n return self.run_train(feed)\n else:\n print('not prepared for this set_name:', set_name)\n assert(False)\n\n \n" }, { "alpha_fraction": 0.5561292767524719, "alphanum_fraction": 0.5679547190666199, "avg_line_length": 36.061729431152344, "blob_id": "bc7f939ee66e81bde6466abf77b400ee38e23c35", "content_id": "343cb1debf1fb2f7611b55c0a5e99b081f2de98a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6004, "license_type": "no_license", "max_line_length": 135, "num_lines": 162, "path": "/model_carla_ego.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport hyperparams as hyp\nimport numpy as np\n# import imageio,scipy\n\nfrom model_base import Model\nfrom nets.feat3dnet import Feat3dNet\nfrom nets.egonet import EgoNet\n\nimport torch.nn.functional as F\n\nimport utils.vox\nimport utils.samp\nimport utils.geom\nimport utils.improc\nimport utils.basic\nimport utils.eval\nimport utils.misc\n\nnp.set_printoptions(precision=2)\nnp.random.seed(0)\n\nclass CARLA_EGO(Model):\n def initialize_model(self):\n print('------ INITIALIZING MODEL OBJECTS ------')\n self.model = CarlaEgoModel()\n if hyp.do_freeze_feat3d:\n self.model.feat3dnet.eval()\n self.set_requires_grad(self.model.feat3dnet, False)\n if hyp.do_freeze_ego:\n self.model.egonet.eval()\n self.set_requires_grad(self.model.egonet, False)\n \nclass CarlaEgoModel(nn.Module):\n def __init__(self):\n super(CarlaEgoModel, self).__init__()\n \n if hyp.do_feat3d:\n self.feat3dnet = Feat3dNet(in_dim=4)\n if hyp.do_ego:\n self.egonet = EgoNet(\n num_scales=hyp.ego_num_scales,\n num_rots=hyp.ego_num_rots,\n max_deg=hyp.ego_max_deg,\n max_disp_z=hyp.ego_max_disp_z,\n max_disp_y=hyp.ego_max_disp_y,\n max_disp_x=hyp.ego_max_disp_x)\n\n def prepare_common_tensors(self, feed):\n results = dict()\n \n self.summ_writer = utils.improc.Summ_writer(\n writer=feed['writer'],\n global_step=feed['global_step'],\n log_freq=feed['set_log_freq'],\n fps=8,\n just_gif=True)\n global_step = feed['global_step']\n\n self.B = feed['set_batch_size']\n self.S = feed['set_seqlen']\n self.set_name = feed['set_name']\n \n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n self.H, self.W, self.V, self.N = hyp.H, hyp.W, hyp.V, hyp.N\n self.PH, self.PW = hyp.PH, hyp.PW\n\n if self.set_name=='test':\n self.Z, self.Y, self.X = hyp.Z_test, hyp.Y_test, hyp.X_test\n elif self.set_name=='val':\n self.Z, self.Y, self.X = hyp.Z_val, hyp.Y_val, hyp.X_val\n else:\n self.Z, self.Y, self.X = hyp.Z, hyp.Y, hyp.X\n self.Z2, self.Y2, self.X2 = int(self.Z/2), int(self.Y/2), int(self.X/2)\n self.Z4, self.Y4, self.X4 = int(self.Z/4), int(self.Y/4), int(self.X/4)\n\n self.ZZ, self.ZY, self.ZX = hyp.ZZ, hyp.ZY, hyp.ZX\n self.pix_T_cams = feed['pix_T_cams']\n self.S = feed['set_seqlen']\n\n # in this mode, we never use R coords, so we can drop the R/X notation\n self.origin_T_cams = feed['origin_T_camXs']\n self.xyz_cams = feed['xyz_camXs']\n\n scene_centroid_x = 0.0\n scene_centroid_y = 1.0\n scene_centroid_z = 18.0\n scene_centroid = np.array([scene_centroid_x,\n scene_centroid_y,\n scene_centroid_z]).reshape([1, 3])\n self.scene_centroid = torch.from_numpy(scene_centroid).float().cuda()\n self.vox_util = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=self.scene_centroid, assert_cube=True)\n \n self.vox_size_X = self.vox_util.default_vox_size_X\n self.vox_size_Y = self.vox_util.default_vox_size_Y\n self.vox_size_Z = self.vox_util.default_vox_size_Z\n \n self.rgb_cams = feed['rgb_camXs']\n\n # get 3d voxelized inputs\n self.occ_mems = __u(self.vox_util.voxelize_xyz(__p(self.xyz_cams), self.Z, self.Y, self.X))\n self.unp_mems = __u(self.vox_util.unproject_rgb_to_mem(\n __p(self.rgb_cams), self.Z, self.Y, self.X, __p(self.pix_T_cams)))\n # these are B x C x Z x Y x X\n self.summ_writer.summ_occs('3d_inputs/occ_mems', torch.unbind(self.occ_mems, dim=1))\n self.summ_writer.summ_unps('3d_inputs/unp_mems', torch.unbind(self.unp_mems, dim=1), torch.unbind(self.occ_mems, dim=1))\n \n return True # OK\n\n def run_train(self, feed):\n total_loss = torch.tensor(0.0).cuda()\n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n results = dict()\n\n assert(hyp.do_ego)\n assert(self.S==2)\n\n origin_T_cam0 = self.origin_T_cams[:, 0]\n origin_T_cam1 = self.origin_T_cams[:, 1]\n cam0_T_cam1 = utils.basic.matmul2(utils.geom.safe_inverse(origin_T_cam0), origin_T_cam1)\n\n feat_mems_input = torch.cat([\n self.occ_mems,\n self.occ_mems*self.unp_mems,\n ], dim=2)\n feat_loss, feat_halfmems_ = self.feat3dnet(__p(feat_mems_input), self.summ_writer)\n feat_halfmems = __u(feat_halfmems_)\n total_loss += feat_loss\n \n ego_loss, cam0_T_cam1_e, _ = self.egonet(\n feat_halfmems[:,0],\n feat_halfmems[:,1],\n cam0_T_cam1,\n self.vox_util,\n self.summ_writer)\n total_loss += ego_loss\n\n # try aligning the frames, for a qualitative result\n occ_mem0_e = self.vox_util.apply_4x4_to_vox(cam0_T_cam1_e, self.occ_mems[:,1])\n self.summ_writer.summ_occs('ego/occs_aligned', [occ_mem0_e, self.occ_mems[:,0]])\n self.summ_writer.summ_occs('ego/occs_unaligned', [self.occ_mems[:,0], self.occ_mems[:,1]])\n\n self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n return total_loss, results, False\n \n def forward(self, feed):\n data_ok = self.prepare_common_tensors(feed)\n\n if not data_ok:\n # return early\n total_loss = torch.tensor(0.0).cuda()\n return total_loss, None, True\n else:\n if self.set_name=='train':\n return self.run_train(feed)\n else:\n print('not prepared for this set_name:', set_name)\n assert(False)\n" }, { "alpha_fraction": 0.5045303702354431, "alphanum_fraction": 0.5719336867332458, "avg_line_length": 25.30813980102539, "blob_id": "8ea47a842e67c095ad86abbd6ba176eb2b04c3ab", "content_id": "219f264f77b98f750801aa3f740068c4f0883b99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4525, "license_type": "no_license", "max_line_length": 137, "num_lines": 172, "path": "/exp_carla_static.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "from exp_base import *\n\n############## choose an experiment ##############\n\ncurrent = 'builder'\ncurrent = 'trainer'\n# current = 'tester_basic'\n\nmod = '\"sta00\"' # nothing; builder\nmod = '\"sta01\"' # just prep and return\nmod = '\"sta02\"' # again, fewer prints\nmod = '\"sta03\"' # run feat3d forward; drop the sparse stuff\nmod = '\"sta04\"' # really run it\nmod = '\"sta05\"' # again\nmod = '\"sta06\"' # warp; show altfeat\nmod = '\"sta07\"' # ensure either ==1 or a==b\nmod = '\"sta08\"' # try emb\nmod = '\"sta09\"' # train a while\nmod = '\"sta10\"' # \nmod = '\"sta11\"' # show altfeat input\nmod = '\"sta12\"' # \nmod = '\"sta13\"' # train occ\nmod = '\"sta14\"' # move things to R\nmod = '\"sta14\"' # do view\nmod = '\"sta15\"' # encode in X0\nmod = '\"sta16\"' # \nmod = '\"sta17\"' # show rgb_camX1, so i can understand the inbound idea better\nmod = '\"sta18\"' # show inbound separately\nmod = '\"sta19\"' # allow 0 to 32m\nmod = '\"sta20\"' # builder\nmod = '\"sta21\"' # show occ_memXs\nmod = '\"sta22\"' # wider bounds please\nmod = '\"sta23\"' # properly combine bounds with centorid\nmod = '\"sta24\"' # train a hwile\nmod = '\"sta25\"' # same but encode in Xs and warp to R then X0\nmod = '\"sta26\"' # use resnet3d \nmod = '\"sta27\"' # skipnet; randomize the centroid a bit\nmod = '\"sta28\"' # wider rand, and inbound check\nmod = '\"sta29\"' # handle the false return\nmod = '\"sta30\"' # add emb2d\nmod = '\"sta31\"' # freeze the slow model\nmod = '\"sta32\"' # 2d parts\nmod = '\"sta33\"' # fewer prints\nmod = '\"sta34\"' # nice suffixes; JUST 2d learning\nmod = '\"sta35\"' # fix bug\nmod = '\"sta36\"' # better summ suffix\nmod = '\"sta37\"' # tell me about neg pool size\nmod = '\"sta38\"' # fix small bug in the hyp lettering\nmod = '\"sta39\"' # cleaned up hyps\nmod = '\"sta40\"' # weak smooth coeff on feats\nmod = '\"sta41\"' # run occnet on altfeat instead\nmod = '\"sta42\"' # redo\nmod = '\"sta43\"' # replication padding\nmod = '\"sta44\"' # pret 170k 02_s2_m128x32x128_p64x192_1e-3_F2_d32_F3_d32_s.01_O_c1_s.01_V_d32_e1_E2_e.1_n4_d32_c1_E3_n2_c1_mags7i3t_sta41\nmod = '\"sta45\"' # inspect and maybe fix the loading; log10\nmod = '\"sta46\"' # init slow in model base after saverloader\nmod = '\"sta47\"' # zero padding; log500\nmod = '\"sta48\"' # replication padding; log500\nmod = '\"sta49\"' # repeat after deleting some code\nmod = '\"sta50\"' # pret 02_s2_m128x32x128_1e-3_F3_d32_s.01_O_c2_s.1_E3_n2_c.1_mags7i3t_sta48\nmod = '\"sta51\"' # same deal after some cleanup\n\n############## exps ##############\n\nexps['builder'] = [\n 'carla_static', # mode\n 'carla_multiview_10_data', # dataset\n '16-4-16_bounds', \n '3_iters',\n 'lr0',\n 'B1',\n 'no_shuf',\n 'train_feat3d',\n # 'train_occ',\n # 'train_view',\n # 'train_emb2d',\n # 'train_emb3d',\n 'log1',\n]\nexps['trainer'] = [\n 'carla_static', # mode\n 'carla_multiview_train_data', # dataset\n '16-4-16_bounds', \n '300k_iters',\n 'lr3',\n 'B2',\n 'pretrained_feat3d', \n 'pretrained_occ', \n 'train_feat3d',\n 'train_emb3d',\n 'train_occ',\n # 'train_view',\n # 'train_feat2d',\n # 'train_emb2d',\n 'log500',\n]\n\n############## groups ##############\n\ngroups['carla_static'] = ['do_carla_static = True']\n\ngroups['train_feat2d'] = [\n 'do_feat2d = True',\n 'feat2d_dim = 32',\n # 'feat2d_smooth_coeff = 0.1',\n]\ngroups['train_occ'] = [\n 'do_occ = True',\n 'occ_coeff = 2.0',\n 'occ_smooth_coeff = 0.1',\n]\ngroups['train_view'] = [\n 'do_view = True',\n 'view_depth = 32',\n 'view_l1_coeff = 1.0',\n]\ngroups['train_emb2d'] = [\n 'do_emb2d = True',\n # 'emb2d_smooth_coeff = 0.01',\n 'emb2d_ce_coeff = 1.0',\n 'emb2d_l2_coeff = 0.1',\n 'emb2d_mindist = 32.0',\n 'emb2d_num_samples = 4',\n # 'do_view = True',\n # 'view_depth = 32',\n # 'view_l1_coeff = 1.0',\n]\ngroups['train_emb3d'] = [\n 'do_emb3d = True',\n 'emb3d_ce_coeff = 0.1',\n # 'emb3d_mindist = 8.0',\n # 'emb3d_l2_coeff = 0.1',\n 'emb3d_num_samples = 2',\n]\n############## datasets ##############\n\n# dims for mem\nSIZE = 32\nZ = int(SIZE*4)\nY = int(SIZE*1)\nX = int(SIZE*4)\nK = 2 # how many objects to consider\nS = 2\nH = 128\nW = 384\n# H and W for proj stuff\nPH = int(H/2.0)\nPW = int(W/2.0)\n\n\n############## verify and execute ##############\n\ndef _verify_(s):\n varname, eq, val = s.split(' ')\n assert varname in globals()\n assert eq == '='\n assert type(s) is type('')\n\nprint(current)\nassert current in exps\nfor group in exps[current]:\n print(\" \" + group)\n assert group in groups\n for s in groups[group]:\n print(\" \" + s)\n _verify_(s)\n exec(s)\n\ns = \"mod = \" + mod\n_verify_(s)\n\nexec(s)\n" }, { "alpha_fraction": 0.531296968460083, "alphanum_fraction": 0.5482532382011414, "avg_line_length": 41.974159240722656, "blob_id": "b48b568be8ee0565b78bc7160c3f32856926296e", "content_id": "cf0742c6ac7332fdf2b43cf798fd98f07f0ac18d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16631, "license_type": "no_license", "max_line_length": 143, "num_lines": 387, "path": "/model_carla_static.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport hyperparams as hyp\nimport numpy as np\n# import imageio,scipy\n\nfrom model_base import Model\nfrom nets.occnet import OccNet\nfrom nets.feat2dnet import Feat2dNet\nfrom nets.feat3dnet import Feat3dNet\nfrom nets.emb2dnet import Emb2dNet\nfrom nets.emb3dnet import Emb3dNet\nfrom nets.viewnet import ViewNet\n\nimport torch.nn.functional as F\n\nimport utils.vox\nimport utils.samp\nimport utils.geom\nimport utils.improc\nimport utils.basic\nimport utils.eval\nimport utils.misc\n\nnp.set_printoptions(precision=2)\nnp.random.seed(0)\n\nclass CARLA_STATIC(Model):\n def initialize_model(self):\n print('------ INITIALIZING MODEL OBJECTS ------')\n self.model = CarlaStaticModel()\n if hyp.do_freeze_feat3d:\n self.model.feat3dnet.eval()\n self.set_requires_grad(self.model.feat3dnet, False)\n if hyp.do_freeze_view:\n self.model.viewnet.eval()\n self.set_requires_grad(self.model.viewnet, False)\n if hyp.do_freeze_occ:\n self.model.occnet.eval()\n self.set_requires_grad(self.model.occnet, False)\n if hyp.do_freeze_emb2d:\n self.model.emb2dnet.eval()\n self.set_requires_grad(self.model.emb2dnet, False)\n\n if hyp.do_emb2d:\n # freeze the slow model\n self.model.feat2dnet_slow.eval()\n self.set_requires_grad(self.model.feat2dnet_slow, False)\n if hyp.do_emb3d:\n # freeze the slow model\n self.model.feat3dnet_slow.eval()\n self.set_requires_grad(self.model.feat3dnet_slow, False)\n \nclass CarlaStaticModel(nn.Module):\n def __init__(self):\n super(CarlaStaticModel, self).__init__()\n if hyp.do_occ:\n self.occnet = OccNet()\n if hyp.do_view:\n self.viewnet = ViewNet()\n\n if hyp.do_feat2d:\n self.feat2dnet = Feat2dNet()\n if hyp.do_emb2d:\n self.emb2dnet = Emb2dNet()\n # make a slow net\n self.feat2dnet_slow = Feat2dNet(in_dim=3)\n \n if hyp.do_feat3d:\n self.feat3dnet = Feat3dNet(in_dim=4)\n if hyp.do_emb3d:\n self.emb3dnet = Emb3dNet()\n # make a slow net\n self.feat3dnet_slow = Feat3dNet(in_dim=4)\n\n def prepare_common_tensors(self, feed):\n results = dict()\n \n self.summ_writer = utils.improc.Summ_writer(\n writer=feed['writer'],\n global_step=feed['global_step'],\n log_freq=feed['set_log_freq'],\n fps=8,\n just_gif=True)\n global_step = feed['global_step']\n\n self.B = feed['set_batch_size']\n self.S = feed['set_seqlen']\n self.set_name = feed['set_name']\n \n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n self.H, self.W, self.V, self.N = hyp.H, hyp.W, hyp.V, hyp.N\n self.PH, self.PW = hyp.PH, hyp.PW\n\n # if self.set_name=='test':\n # self.Z, self.Y, self.X = hyp.Z_test, hyp.Y_test, hyp.X_test\n # elif self.set_name=='val':\n # self.Z, self.Y, self.X = hyp.Z_val, hyp.Y_val, hyp.X_val\n # else:\n self.Z, self.Y, self.X = hyp.Z, hyp.Y, hyp.X\n self.Z2, self.Y2, self.X2 = int(self.Z/2), int(self.Y/2), int(self.X/2)\n self.Z4, self.Y4, self.X4 = int(self.Z/4), int(self.Y/4), int(self.X/4)\n\n self.ZZ, self.ZY, self.ZX = hyp.ZZ, hyp.ZY, hyp.ZX\n self.pix_T_cams = feed['pix_T_cams']\n set_data_format = feed['set_data_format']\n self.S = feed['set_seqlen']\n \n\n self.origin_T_camRs = feed['origin_T_camRs']\n self.origin_T_camXs = feed['origin_T_camXs']\n\n self.camX0s_T_camXs = utils.geom.get_camM_T_camXs(self.origin_T_camXs, ind=0)\n self.camR0s_T_camRs = utils.geom.get_camM_T_camXs(self.origin_T_camRs, ind=0)\n self.camRs_T_camR0s = __u(utils.geom.safe_inverse(__p(self.camR0s_T_camRs)))\n self.camRs_T_camXs = __u(torch.matmul(__p(self.origin_T_camRs).inverse(), __p(self.origin_T_camXs)))\n self.camXs_T_camRs = __u(__p(self.camRs_T_camXs).inverse())\n\n self.xyz_camXs = feed['xyz_camXs']\n self.xyz_camRs = __u(utils.geom.apply_4x4(__p(self.camRs_T_camXs), __p(self.xyz_camXs)))\n self.xyz_camX0s = __u(utils.geom.apply_4x4(__p(self.camX0s_T_camXs), __p(self.xyz_camXs)))\n \n if self.set_name=='test' or self.set_name=='val':\n # fixed centroid\n scene_centroid_x = 0.0\n scene_centroid_y = 1.0\n scene_centroid_z = 18.0\n else:\n # randomize a bit, as a form of data aug\n all_ok = False\n num_tries = 0\n while (not all_ok) and (num_tries < 100):\n scene_centroid_x = np.random.uniform(-8.0, 8.0)\n scene_centroid_y = np.random.uniform(-1.5, 3.0)\n scene_centroid_z = np.random.uniform(10.0, 26.0)\n scene_centroid = np.array([scene_centroid_x,\n scene_centroid_y,\n scene_centroid_z]).reshape([1, 3])\n self.scene_centroid = torch.from_numpy(scene_centroid).float().cuda()\n num_tries += 1\n all_ok = True\n self.vox_util = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=self.scene_centroid, assert_cube=True)\n # we want to ensure this gives us a few points inbound for each element\n inb = __u(self.vox_util.get_inbounds(__p(self.xyz_camX0s), self.Z, self.Y, self.X, already_mem=False))\n # this is B x S x N\n num_inb = torch.sum(inb.float(), axis=2)\n # this is B x S\n \n if torch.min(num_inb) < 300:\n all_ok = False\n self.summ_writer.summ_scalar('centroid_sampling/num_tries', float(num_tries))\n self.summ_writer.summ_scalar('centroid_sampling/num_inb', torch.mean(num_inb).cpu().item())\n if num_tries >= 100:\n return False\n \n self.vox_size_X = self.vox_util.default_vox_size_X\n self.vox_size_Y = self.vox_util.default_vox_size_Y\n self.vox_size_Z = self.vox_util.default_vox_size_Z\n \n origin_T_camRs_ = self.origin_T_camRs.reshape(self.B, self.S, 1, 4, 4).repeat(1, 1, self.N, 1, 1).reshape(self.B*self.S, self.N, 4, 4)\n boxlists = feed['boxlists']\n\n self.rgb_camXs = feed['rgb_camXs']\n\n ## get the projected depthmap and inbound mask\n self.depth_camXs_, self.valid_camXs_ = utils.geom.create_depth_image(__p(self.pix_T_cams), __p(self.xyz_camXs), self.H, self.W)\n self.dense_xyz_camXs_ = utils.geom.depth2pointcloud(self.depth_camXs_, __p(self.pix_T_cams))\n # we need to go to X0 to see what will be inbounds\n self.dense_xyz_camX0s_ = utils.geom.apply_4x4(__p(self.camX0s_T_camXs), self.dense_xyz_camXs_)\n self.inbound_camXs_ = self.vox_util.get_inbounds(self.dense_xyz_camX0s_, self.Z, self.Y, self.X).float()\n self.inbound_camXs_ = torch.reshape(self.inbound_camXs_, [self.B*self.S, 1, self.H, self.W])\n self.depth_camXs = __u(self.depth_camXs_)\n self.valid_camXs = __u(self.valid_camXs_) * __u(self.inbound_camXs_)\n self.summ_writer.summ_oned('2d_inputs/depth_camX0', self.depth_camXs[:,0], maxval=32.0)\n self.summ_writer.summ_oned('2d_inputs/valid_camX0', self.valid_camXs[:,0], norm=False)\n self.summ_writer.summ_rgb('2d_inputs/rgb_camX0', self.rgb_camXs[:,0])\n\n # get 3d voxelized inputs\n self.occ_memXs = __u(self.vox_util.voxelize_xyz(__p(self.xyz_camXs), self.Z, self.Y, self.X))\n self.unp_memXs = __u(self.vox_util.unproject_rgb_to_mem(\n __p(self.rgb_camXs), self.Z, self.Y, self.X, __p(self.pix_T_cams)))\n # these are B x C x Z x Y x X\n self.summ_writer.summ_occs('3d_inputs/occ_memXs', torch.unbind(self.occ_memXs, dim=1))\n self.summ_writer.summ_unps('3d_inputs/unp_memXs', torch.unbind(self.unp_memXs, dim=1), torch.unbind(self.occ_memXs, dim=1))\n \n return True # OK\n\n def run_train(self, feed):\n results = dict()\n\n global_step = feed['global_step']\n total_loss = torch.tensor(0.0).cuda()\n\n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n #####################\n ## run the nets\n #####################\n\n if hyp.do_feat2d:\n feat2d_loss, feat_camX0 = self.feat2dnet(\n self.rgb_camXs[:,0],\n self.summ_writer,\n )\n if hyp.do_emb2d:\n # for stability, we will also use a slow net here\n _, altfeat_camX0 = self.feat2dnet_slow(self.rgb_camXs[:,0])\n \n if hyp.do_feat3d:\n # start with a 4-channel feature map;\n feat_memXs_input = torch.cat([\n self.occ_memXs,\n self.unp_memXs*self.occ_memXs,\n ], dim=2)\n\n # featurize\n feat3d_loss, feat_memXs_ = self.feat3dnet(\n __p(feat_memXs_input[:,1:]), self.summ_writer)\n feat_memXs = __u(feat_memXs_)\n total_loss += feat3d_loss\n\n valid_memXs = torch.ones_like(feat_memXs[:,:,0:1])\n feat_memRs = self.vox_util.apply_4x4s_to_voxs(self.camRs_T_camXs[:,1:], feat_memXs)\n valid_memRs = self.vox_util.apply_4x4s_to_voxs(self.camRs_T_camXs[:,1:], valid_memXs)\n # these are B x S x C x Z2 x Y2 x X2\n\n feat_memR = utils.basic.reduce_masked_mean(\n feat_memRs, valid_memRs, dim=1)\n valid_memR = torch.max(valid_memRs, dim=1)[0]\n # these are B x C x Z2 x Y2 x X2\n self.summ_writer.summ_feat('feat3d/feat_output_agg', feat_memR, valid_memR, pca=True)\n\n if hyp.do_emb3d:\n _, altfeat_memR = self.feat3dnet_slow(feat_memXs_input[:,0])\n altvalid_memR = torch.ones_like(altfeat_memR[:,0:1])\n self.summ_writer.summ_feat('feat3d/altfeat_input', feat_memXs_input[:,0], pca=True)\n self.summ_writer.summ_feat('feat3d/altfeat_output', altfeat_memR, pca=True)\n \n if hyp.do_occ:\n assert(hyp.do_feat3d)\n occ_memR_sup, free_memR_sup, _, _ = self.vox_util.prep_occs_supervision(\n self.camRs_T_camXs,\n self.xyz_camXs,\n self.Z2, self.Y2, self.X2,\n agg=True)\n occ_loss, occ_memR_pred = self.occnet(\n feat_memR, \n occ_memR_sup,\n free_memR_sup,\n valid_memR, \n self.summ_writer)\n total_loss += occ_loss\n\n if hyp.do_view:\n assert(hyp.do_feat3d)\n # decode the perspective volume into an image\n view_loss, rgb_camX0_e, viewfeat_camX0 = self.viewnet(\n self.pix_T_cams[:,0],\n self.camXs_T_camRs[:,0],\n feat_memR, \n self.rgb_camXs[:,0],\n self.vox_util,\n valid=self.valid_camXs[:,0],\n summ_writer=self.summ_writer)\n total_loss += view_loss\n \n if hyp.do_emb2d:\n assert(hyp.do_feat2d)\n \n if hyp.do_view:\n # anchor against the bottom-up 2d net\n valid_camX0 = F.interpolate(self.valid_camXs[:,0], scale_factor=0.5, mode='nearest')\n emb2d_loss, _ = self.emb2dnet(\n viewfeat_camX0,\n feat_camX0,\n valid_camX0,\n summ_writer=self.summ_writer,\n suffix='_view')\n total_loss += emb2d_loss\n\n # anchor against the slow net\n emb2d_loss, _ = self.emb2dnet(\n feat_camX0,\n altfeat_camX0,\n torch.ones_like(feat_camX0[:,0:1]),\n summ_writer=self.summ_writer,\n suffix='_slow')\n total_loss += emb2d_loss\n\n if hyp.do_emb3d:\n assert(hyp.do_feat3d)\n # compute 3D ML\n emb3d_loss = self.emb3dnet(\n feat_memR,\n altfeat_memR,\n valid_memR.round(),\n altvalid_memR.round(),\n self.summ_writer)\n total_loss += emb3d_loss\n \n self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n return total_loss, results, False\n\n def run_test(self, feed):\n results = dict()\n\n global_step = feed['global_step']\n total_loss = torch.tensor(0.0).cuda()\n # total_loss = torch.autograd.Variable(0.0, requires_grad=True).cuda()\n\n __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n # get the boxes\n boxlist_camRs = feed['boxlists']\n tidlist_s = feed['tidlists'] # coordinate-less and plural\n scorelist_s = feed['scorelists'] # coordinate-less and plural\n \n lrtlist_camRs = __u(utils.geom.convert_boxlist_to_lrtlist(__p(boxlist_camRs))).reshape(self.B, self.S, self.N, 19)\n lrtlist_camXs = __u(utils.geom.apply_4x4_to_lrtlist(__p(self.camXs_T_camRs), __p(lrtlist_camRs)))\n # these are is B x S x N x 19\n\n self.summ_writer.summ_lrtlist('obj/lrtlist_camX0', self.rgb_camXs[:,0], lrtlist_camXs[:,0],\n scorelist_s[:,0], tidlist_s[:,0], self.pix_T_cams[:,0])\n self.summ_writer.summ_lrtlist('obj/lrtlist_camR0', self.rgb_camRs[:,0], lrtlist_camRs[:,0],\n scorelist_s[:,0], tidlist_s[:,0], self.pix_T_cams[:,0])\n # mask_memX0 = utils.vox.assemble_padded_obj_masklist(\n # lrtlist_camXs[:,0], scorelist_s[:,0], self.Z2, self.Y2, self.X2, coeff=1.0)\n # mask_memX0 = torch.sum(mask_memX0, dim=1).clamp(0, 1) \n # self.summ_writer.summ_oned('obj/mask_memX0', mask_memX0, bev=True)\n\n mask_memXs = __u(utils.vox.assemble_padded_obj_masklist(\n __p(lrtlist_camXs), __p(scorelist_s), self.Z2, self.Y2, self.X2, coeff=1.0))\n mask_memXs = torch.sum(mask_memXs, dim=2).clamp(0, 1)\n self.summ_writer.summ_oneds('obj/mask_memXs', torch.unbind(mask_memXs, dim=1), bev=True)\n\n for b in list(range(self.B)):\n for s in list(range(self.S)):\n mask = mask_memXs[b,s]\n if torch.sum(mask) < 2.0:\n # return early\n return total_loss, None, True\n \n # next: i want to treat features differently if they are in obj masks vs not\n # in particular, i want a different kind of retrieval metric\n \n if hyp.do_feat3d:\n # occXs is B x S x 1 x H x W x D\n # unpXs is B x S x 3 x H x W x D\n feat_memXs_input = torch.cat([self.occXs, self.occXs*self.unpXs], dim=2)\n feat_memXs_input_ = __p(feat_memXs_input)\n\n feat_memXs_, _, _ = self.feat3dnet(\n feat_memXs_input_,\n self.summ_writer,\n comp_mask=None,\n )\n feat_memXs = __u(feat_memXs_)\n \n self.summ_writer.summ_feats('3d_feats/feat_memXs_input', torch.unbind(feat_memXs_input, dim=1), pca=True)\n self.summ_writer.summ_feats('3d_feats/feat_memXs_output', torch.unbind(feat_memXs, dim=1), pca=True)\n\n mv_precision = utils.eval.measure_semantic_retrieval_precision(feat_memXs[0], mask_memXs[0])\n self.summ_writer.summ_scalar('semantic_retrieval/multiview_precision', mv_precision)\n ms_precision = utils.eval.measure_semantic_retrieval_precision(feat_memXs[:,0], mask_memXs[:,0])\n self.summ_writer.summ_scalar('semantic_retrieval/multiscene_precision', ms_precision)\n \n return total_loss, None, False\n \n def forward(self, feed):\n data_ok = self.prepare_common_tensors(feed)\n\n if not data_ok:\n # return early\n total_loss = torch.tensor(0.0).cuda()\n return total_loss, None, True\n else:\n if self.set_name=='train':\n return self.run_train(feed)\n elif self.set_name=='test':\n return self.run_test(feed)\n else:\n print('weird set_name:', set_name)\n assert(False)\n" }, { "alpha_fraction": 0.5629985332489014, "alphanum_fraction": 0.5987938642501831, "avg_line_length": 45.0059700012207, "blob_id": "187196252acd062f85a88ae7c4d58f6f1f7b48be", "content_id": "1f855bfaddbb5a31a85b07500aa56bd3274c4b76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15421, "license_type": "no_license", "max_line_length": 155, "num_lines": 335, "path": "/nets/detnet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.ops as ops\n\nimport utils.basic\nimport utils.geom\nimport utils.misc\nimport hyperparams as hyp\nimport archs.encoder3d\n\ndef smooth_l1_loss(deltas, targets, sigma=3.0):\n sigma2 = sigma * sigma\n diffs = deltas - targets\n\n smooth_l1_signs = (torch.abs(diffs) < 1.0 / sigma2).float() \n\n smooth_l1_option1 = diffs**2 * 0.5 * sigma2\n smooth_l1_option2 = torch.abs(diffs) - 0.5 / sigma2\n smooth_l1_add = smooth_l1_option1 * smooth_l1_signs + smooth_l1_option2 * (1 - smooth_l1_signs)\n smooth_l1 = smooth_l1_add\n\n return smooth_l1\n\ndef binarize(input, threshold):\n return torch.where(input < threshold, torch.zeros_like(input), torch.ones_like(input))\n\ndef meshgrid3d_xyz(B, Z, Y, X):\n grid_z, grid_y, grid_x = utils.basic.meshgrid3d(B, Z, Y, X, stack=False)\n # each one is shaped B x Z x Y x X\n grid_z = grid_z.permute(0, 3, 2, 1)\n grid_x = grid_x.permute(0, 3, 2, 1)\n grid_y = grid_y.permute(0, 3, 2, 1)\n # make each one axis order XYZ\n grid = torch.stack([grid_x, grid_y, grid_z], dim=-1)\n \n return grid\n\ndef anchor_deltas_to_bboxes(anchor_deltas, indices):\n # anchors deltas is num_objects x 6, first 3 for translation and last 3 for scale\n # grid_center is num_objects x 3\n\n grid_center = indices.float()\n object_center = grid_center + anchor_deltas[:, :3] * hyp.det_anchor_size\n object_min = object_center - 0.5 * torch.exp(anchor_deltas[:, 3:]) * hyp.det_anchor_size\n object_max = object_center + 0.5 * torch.exp(anchor_deltas[:, 3:]) * hyp.det_anchor_size\n return torch.stack([object_min, object_max], 2), torch.cat([object_center, object_max - object_min], 1) #these are N x 3 x 2 and N x 6, respectively\n\ndef overlap_graph(boxes1, boxes2): #tested\n # boxes1: batch x 3 x 2 (z1,z2,y1,y2,x1,x2)\n b1_bs = boxes1.shape[0] #batch_size\n b2_bs = boxes2.shape[0]\n\n if b1_bs == 0 or b2_bs == 0:\n # torch's repeat will fail, so let's return early\n return torch.zeros(b1_bs, b2_bs)\n\n boxes1 = boxes1.view(-1, 6)\n boxes2 = boxes2.view(-1, 6)\n\n b1 = boxes1.unsqueeze(1).repeat(1, b2_bs, 1).view(-1, 6) #this is (b1xb2) x 6\n b2 = boxes2.unsqueeze(0).repeat(b1_bs, 1, 1).view(-1, 6)\n\n b1_z1, b1_z2, b1_y1, b1_y2, b1_x1, b1_x2 = torch.chunk(b1, 6, dim=1)\n b2_z1, b2_z2, b2_y1, b2_y2, b2_x1, b2_x2 = torch.chunk(b2, 6, dim=1)\n\n z1 = torch.max(b1_z1, b2_z1)\n z2 = torch.min(b1_z2, b2_z2)\n y1 = torch.max(b1_y1, b2_y1)\n y2 = torch.min(b1_y2, b2_y2)\n x1 = torch.max(b1_x1, b2_x1)\n x2 = torch.min(b1_x2, b2_x2)\n\n intersection = torch.max(z2 - z1, torch.zeros_like(z1)) * torch.max(y2 - y1, torch.zeros_like(y1)) * torch.max(x2 - x1, torch.zeros_like(x1))\n\n b1_area = (b1_z2 - b1_z1) * (b1_y2 - b1_y1) * (b1_x2 - b1_x1)\n b2_area = (b2_z2 - b2_z1) * (b2_y2 - b2_y1) * (b2_x2 - b2_x1)\n union = b1_area + b2_area - intersection\n\n iou = intersection / union\n overlaps = iou.view(b1_bs, b2_bs)\n\n return overlaps\n\ndef box_refinement_graph(positive_rois, roi_gt_boxes):\n # roi_gt_boxes are N x 3 x 2\n gt_center = torch.mean(roi_gt_boxes, dim=2)\n pd_center = torch.mean(positive_rois, dim=2) #these are N x 3 (zyx order)\n\n delta_zyx = gt_center-pd_center\n\n len_gt = roi_gt_boxes[:,:,1] - roi_gt_boxes[:,:,0]\n len_pd = positive_rois[:,:,1] - positive_rois[:,:,0]\n\n delta_len = len_gt - len_pd\n\n return torch.cat([delta_zyx, delta_len], dim=1) # N x 6\n\ndef rpn_proposal_graph(pred_objectness, pred_anchor_deltas, valid_mask, corners_min_max_g, iou_thresh=0.5): #tested\n ######################## ROI generation ####################\n # object_bbox: batch_size x N x 3 x 2\n # pred_objectness: B x X x Y x Z\n # pred_anchor_deltas: B x X x Y x Z x 6\n # valid_mask: B x N\n # corners_min_max_g: B x N x 3 x 2, in xyz order\n\n P_THRES = 0.9\n high_prob_indices = torch.stack(torch.where(pred_objectness > P_THRES), dim=1) # this is ? x 4, last dim in bxyz order\n B = pred_objectness.shape[0]\n\n # build prediction target\n bs_selected_boxes_co = []\n bs_selected_scores = []\n bs_overlaps = []\n if len(high_prob_indices > 0):\n for i in list(range(B)):\n selected_boxes, selected_boxes_scores, overlaps, selected_boxes_co = detection_target_graph(i, high_prob_indices, \\\n corners_min_max_g, valid_mask, pred_objectness, pred_anchor_deltas, iou_thresh=iou_thresh)\n\n bs_selected_boxes_co.append(selected_boxes_co)\n bs_selected_scores.append(selected_boxes_scores)\n bs_overlaps.append(overlaps)\n return bs_selected_boxes_co, bs_selected_scores, bs_overlaps\n else:\n return None, None, None\n\ndef detection_target_graph(i, high_prob_indices, corners_min_max_g, valid_mask, pred_objectness, pred_anchor_deltas,\n iou_thresh=0.5): #tested\n\n batch_i_idxs = torch.stack(torch.where(high_prob_indices[:,0] == i), dim=1) # this is (?, 1)\n batch_i_indices = high_prob_indices[batch_i_idxs.squeeze(dim=1)] # this is ? x 4\n\n batch_i_scores = pred_objectness[batch_i_indices[:, 0], batch_i_indices[:, 1], batch_i_indices[:, 2], batch_i_indices[:, 3]] # this is (?, )\n batch_i_anchor_deltas = pred_anchor_deltas[batch_i_indices[:, 0], batch_i_indices[:, 1], batch_i_indices[:, 2], batch_i_indices[:, 3]] # this is (?, 6)\n\n # don't know why all out of a sudden order becomes zyx, but we follow this zyx order for the following code ...\n\n # co refers to center + offset parameterization\n batch_i_bboxes, batch_i_bboxes_co = anchor_deltas_to_bboxes(\n batch_i_anchor_deltas, batch_i_indices[:,1:]) \n # N x 3 x 2 and N x 6\n\n # print(batch_i_bboxes[:, 1:, :].permute(0, 2, 1).shape)\n\n selected_bboxes_idx_xy = ops.nms(\n batch_i_bboxes[:, 1:, :].permute(0, 2, 1).contiguous().view(-1, 4).cpu(), # view() fails, so we introduce this contiguous()\n batch_i_scores.cpu(),\n iou_thresh).cuda()\n selected_bboxes_idx_zx = ops.nms(\n batch_i_bboxes[:, [0,2], :].permute(0, 2, 1).contiguous().view(-1, 4).cpu(),\n batch_i_scores.cpu(),\n iou_thresh).cuda()\n selected_bboxes_idx = torch.unique(torch.cat([selected_bboxes_idx_xy, selected_bboxes_idx_zx], dim=0)) # this is (selected_bbox, )\n\n selected_3d_bboxes = batch_i_bboxes[selected_bboxes_idx] # this is (selected_bbox, 3, 2)\n\n selected_3d_bboxes_co = batch_i_bboxes_co[selected_bboxes_idx] # this is (selected_bbox, 6)\n selected_3d_bboxes_scores = batch_i_scores[selected_bboxes_idx]\n valid_inds = torch.stack(torch.where(valid_mask[i, :]), dim=1).squeeze(dim=1) # this is (valid_ids, )\n corners_min_max_g_i = corners_min_max_g[i, valid_inds] # (valid_ids, 3, 2)\n\n # calculate overlap in 3d\n overlaps = overlap_graph(selected_3d_bboxes, corners_min_max_g_i) # this is (selected_bbox, valid_ids)\n\n return selected_3d_bboxes, selected_3d_bboxes_scores, overlaps, selected_3d_bboxes_co\n\nclass DetNet(nn.Module):\n def __init__(self):\n print('DetNet...')\n\n super(DetNet, self).__init__()\n self.pred_dim = 7\n self.net = torch.nn.Conv3d(in_channels=hyp.feat3d_dim, out_channels=self.pred_dim, kernel_size=3, stride=1, padding=1).cuda()\n\n print(self.net)\n\n def forward(self,\n lrtlist_g,\n scores_g,\n feat_zyx,\n summ_writer\n ):\n total_loss = torch.tensor(0.0).cuda()\n\n B, C, Z, Y, X = feat_zyx.shape\n _, N, _ = lrtlist_g.shape\n\n pred_dim = self.pred_dim # total 7, 6 deltas, 1 objectness\n\n feat = feat_zyx.permute(0, 1, 4, 3, 2) # get feat in xyz order, now B x C x X x Y x Z\n\n corners = utils.geom.get_xyzlist_from_lrtlist(lrtlist_g) # corners is B x N x 8 x 3, last dim in xyz order\n corners_max = torch.max(corners, dim=2)[0] # B x N x 3\n corners_min = torch.min(corners, dim=2)[0]\n corners_min_max_g = torch.stack([corners_min, corners_max], dim=3) # this is B x N x 3 x 2\n\n # trim down, to save some time\n N = min(N, hyp.K)\n corners_min_max_g = corners_min_max_g[:,:N]\n scores_g = scores_g[:, :N] # B x N\n\n # boxes_g is [-0.5~63.5, -0.5~15.5, -0.5~63.5]\n centers_g = utils.geom.get_clist_from_lrtlist(lrtlist_g)\n # centers_g is B x N x 3\n grid = meshgrid3d_xyz(B, Z, Y, X)[0] # just one grid please, this is X x Y x Z x 3\n\n delta_positions_raw = centers_g.view(B, N, 1, 1, 1, 3) - grid.view(1, 1, X, Y, Z, 3)\n delta_positions = delta_positions_raw / hyp.det_anchor_size\n\n lengths_g = utils.geom.get_lenlist_from_lrtlist(lrtlist_g) # B x N x 3\n delta_lengths = torch.log(lengths_g / hyp.det_anchor_size)\n delta_lengths = torch.max(delta_lengths, -1e6 * torch.ones_like(delta_lengths)) # to avoid -infs turning into nans\n\n lengths_g = lengths_g.view(B, N, 1, 1, 1, 3).repeat(1, 1, X, Y, Z, 1) # B x N x X x Y x Z x 3\n delta_lengths = delta_lengths.view(B, N, 1, 1, 1, 3).repeat(1, 1, X, Y, Z, 1) # B x N x X x Y x Z x 3\n valid_mask = scores_g.view(B, N, 1, 1, 1, 1).repeat(1, 1, X, Y, Z, 1) # B x N x X x Y x Z x 1\n\n delta_gt = torch.cat([delta_positions, delta_lengths], -1) # B x N x X x Y x Z x 6\n\n object_dist = torch.max(torch.abs(delta_positions_raw)/(lengths_g * 0.5 + 1e-5), dim=5)[0] # B x N x X x Y x Z\n object_dist_mask = (torch.ones_like(object_dist) - binarize(object_dist, 0.5)).unsqueeze(dim=5) # B x N x X x Y x Z x 1\n object_dist_mask = object_dist_mask * valid_mask # B x N x X x Y x Z x 1\n object_neg_dist_mask = torch.ones_like(object_dist) - binarize(object_dist, 0.8)\n object_neg_dist_mask = object_neg_dist_mask * valid_mask.squeeze(dim=5) # B x N x X x Y x Z\n\n anchor_deltas_gt = None\n for obj_id in list(range(N)):\n if anchor_deltas_gt is None:\n anchor_deltas_gt = delta_gt[:, obj_id, :, :, :, :] * object_dist_mask[:, obj_id, :, :, :, :]\n current_mask = object_dist_mask[:, obj_id, :, :, :, :]\n else:\n # don't overwrite anchor positions that are already taken\n overlap = current_mask * object_dist_mask[:, obj_id, :, :, :, :]\n anchor_deltas_gt += (torch.ones_like(overlap)- overlap) * delta_gt[:, obj_id, :, :, :, :] * object_dist_mask[:, obj_id, :, :, :, :]\n current_mask = current_mask + object_dist_mask[:, obj_id, :, :, :, :]\n current_mask = binarize(current_mask, 0.5)\n\n pos_equal_one = binarize(torch.sum(object_dist_mask, dim=1), 0.5).squeeze(dim=4) # B x X x Y x Z\n neg_equal_one = binarize(torch.sum(object_neg_dist_mask, dim=1), 0.5) \n neg_equal_one = torch.ones_like(neg_equal_one) - neg_equal_one # B x X x Y x Z\n pos_equal_one_sum = torch.sum(pos_equal_one, [1,2,3]) # B\n neg_equal_one_sum = torch.sum(neg_equal_one, [1,2,3])\n\n summ_writer.summ_occ('det/pos_equal_one', pos_equal_one.unsqueeze(1))\n\n # set min to one in case no object, to avoid nan\n pos_equal_one_sum_safe = torch.max(pos_equal_one_sum, torch.ones_like(pos_equal_one_sum)) # B\n neg_equal_one_sum_safe = torch.max(neg_equal_one_sum, torch.ones_like(neg_equal_one_sum)) # B\n\n pred = self.net(feat) # this is B x 7 x X x Y x Z\n summ_writer.summ_feat('det/feat', feat, pca=False)\n summ_writer.summ_feat('det/pred', pred, pca=True)\n \n pred = pred.permute(0, 2, 3, 4, 1) # B x X x Y x Z x 7\n pred_anchor_deltas = pred[..., 1:] # B x X x Y x Z x 6\n pred_objectness_logits = pred[..., 0] # B x X x Y x Z\n pred_objectness = torch.nn.functional.sigmoid(pred_objectness_logits) # B x X x Y x Z\n\n alpha = 1.5\n beta = 1.0\n small_addon_for_BCE = 1e-6\n\n overall_loss = torch.nn.functional.binary_cross_entropy_with_logits(\n input=pred_objectness_logits,\n target=pos_equal_one,\n reduction='none',\n )\n cls_pos_loss = utils.basic.reduce_masked_mean(overall_loss, pos_equal_one)\n cls_neg_loss = utils.basic.reduce_masked_mean(overall_loss, neg_equal_one)\n loss_prob = torch.sum(alpha * cls_pos_loss + beta * cls_neg_loss)\n\n pos_mask = pos_equal_one.unsqueeze(dim=4) # B x X x Y x Z x 1\n loss_l1 = smooth_l1_loss(pos_mask * pred_anchor_deltas, pos_mask * anchor_deltas_gt) # B x X x Y x Z x 1\n loss_reg = torch.sum(loss_l1/pos_equal_one_sum_safe.view(-1, 1, 1, 1, 1))/float(B)\n\n total_loss = utils.misc.add_loss('det/detect_prob', total_loss, loss_prob, hyp.det_prob_coeff, summ_writer)\n total_loss = utils.misc.add_loss('det/detect_reg', total_loss, loss_reg, hyp.det_reg_coeff, summ_writer)\n\n # finally, turn the preds into hard boxes, with nms\n (\n bs_selected_boxes_co,\n bs_selected_scores,\n bs_overlaps,\n ) = rpn_proposal_graph(pred_objectness, pred_anchor_deltas, scores_g, corners_min_max_g,\n iou_thresh=0.2)\n # these are lists of length B, each one leading with dim \"?\", since there is a variable number of objs per frame\n\n N = hyp.K*2\n tidlist = torch.linspace(1.0, N, N).long().to('cuda')\n tidlist = tidlist.unsqueeze(0).repeat(B, 1)\n padded_boxes_e = torch.zeros(B, N, 9).float().cuda()\n padded_scores_e = torch.zeros(B, N).float().cuda()\n if bs_selected_boxes_co is not None: \n for b in list(range(B)):\n # make the boxes 1 x N x 9 (instead of B x ? x 6)\n padded_boxes0_e = bs_selected_boxes_co[b].unsqueeze(0)\n padded_scores0_e = bs_selected_scores[b].unsqueeze(0)\n\n padded_boxes0_e = torch.cat([padded_boxes0_e, torch.zeros([1, N, 6], device=torch.device('cuda'))], dim=1) # 1 x ? x 6\n padded_scores0_e = torch.cat([padded_scores0_e, torch.zeros([1, N], device=torch.device('cuda'))], dim=1) # pad out\n\n padded_boxes0_e = padded_boxes0_e[:,:N] # clip to N\n padded_scores0_e = padded_scores0_e[:,:N] # clip to N\n\n padded_boxes0_e = torch.cat([padded_boxes0_e, torch.zeros([1, N, 3], device=torch.device('cuda'))], dim=2)\n\n padded_boxes_e[b] = padded_boxes0_e[0]\n padded_scores_e[b] = padded_scores0_e[0]\n return total_loss, padded_boxes_e, padded_scores_e, tidlist, pred_objectness, bs_selected_scores, bs_overlaps\n\nif __name__ == \"__main__\":\n A = torch.randn(5, 10)\n B = torch.randn(5, 10)\n # print(smooth_l1_loss(A, A+1))\n # meshgrid3d_xyz(2, 64, 64, 64)\n\n boxes1 = torch.randn(2, 3, 1)\n boxes1 = boxes1.repeat(1, 1, 2) #2 x 3 x 2\n boxes1[:, :, 1] += 1.0\n boxes2 = boxes1 - 0.5\n\n # print(overlap_graph(boxes1, boxes2))\n # print(box_refinement_graph(boxes1, boxes2))\n\n # boxes3d = torch.zeros(2, 2, 9).cuda()\n\n pred_objectness = torch.zeros(2, 10, 10, 10)\n pred_objectness[0,1,1,1] = 1.0\n pred_anchor_deltas = torch.zeros(2, 10, 10, 10, 6)\n valid_mask = torch.ones(2, 1)\n corners_min_max_g = torch.tensor(np.array([[0.0, 1.5], [0.0, 1.5], [0.5, 1.5]])).view(1, 1, 3, 2).repeat(2, 1, 1, 1).float()\n\n bs_selected_boxes_co, bs_selected_scores, bs_overlaps = rpn_proposal_graph(pred_objectness, pred_anchor_deltas, valid_mask, corners_min_max_g)\n print(bs_overlaps)\n \n\n\n\n\n" }, { "alpha_fraction": 0.49603071808815, "alphanum_fraction": 0.5233359336853027, "avg_line_length": 19.994504928588867, "blob_id": "89245b3fc20e147f702b77fb2cdd22d238df0ef1", "content_id": "fb052daf0110064d5817e6b2e64e71768a7542ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11463, "license_type": "no_license", "max_line_length": 84, "num_lines": 546, "path": "/hyperparams.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import os\n# from munch import Munch\n\nH = 240 # height\nW = 320 # width\n\nZ = 128\nY = 64\nX = 128\nZ_val = 128\nY_val = 64\nX_val = 128\nZ_test = 128\nY_test = 64\nX_test = 128\n\nPH = int(128/4)\nPW = int(384/4)\n\nZY = 32\nZX = 32\nZZ = 32\n\nN = 8 # number of boxes per npz\nK = 1 # number of boxes to actually use\n# S = 2 # seq length\n# S_test = 3 # seq length\nT = 256 # height & width of birdview map\nV = 100000 # num velodyne points\n\n# metric bounds of mem space \nXMIN = -16.0 # right (neg is left)\nXMAX = 16.0 # right\nYMIN = -1.0 # down (neg is up)\nYMAX = 3.0 # down\nZMIN = 2.0 # forward\nZMAX = 34.0 # forward\nXMIN_val = -16.0 # right (neg is left)\nXMAX_val = 16.0 # right\nYMIN_val = -1.0 # down (neg is up)\nYMAX_val = 3.0 # down\nZMIN_val = 2.0 # forward\nZMAX_val = 34.0 # forward\nXMIN_test = -16.0 # right (neg is left)\nXMAX_test = 16.0 # right\nYMIN_test = -1.0 # down (neg is up)\nYMAX_test = 3.0 # down\nZMIN_test = 2.0 # forward\nZMAX_test = 34.0 # forward\nFLOOR = 2.65 # ground (2.65m downward from the cam)\nCEIL = (FLOOR-2.0) # \n\n#----------- loading -----------#\n\ndo_include_summs = False\ndo_include_vis = True\ndo_test = False\ndo_export_vis = False\ndo_export_stats = False\ndo_export_inds = False\n\nemb2d_init = \"\"\nfeat2d_init = \"\"\nfeat3d_init = \"\"\nflow_init = \"\"\nocc_init = \"\"\nview_init = \"\"\nego_init = \"\"\ndet_init = \"\"\n\ntotal_init = \"\"\nreset_iter = False\n\ndo_freeze_emb2d = False\ndo_freeze_feat2d = False\ndo_freeze_feat3d = False\ndo_freeze_occ = False\ndo_freeze_view = False\ndo_freeze_flow = False\ndo_freeze_ego = False\ndo_freeze_det = False\ndo_resume = False\n\n# by default, only backprop on \"train\" iters\nbackprop_on_train = True\nbackprop_on_val = False\nbackprop_on_test = False\n\n#----------- net design -----------#\n# by default, run nothing\ndo_emb2d = False\ndo_emb3d = False\ndo_feat2d = False\ndo_feat3d = False\ndo_occ = False\ndo_view = False\ndo_flow = False\ndo_ego = False\ndo_det = False\n\n#----------- general hypers -----------#\nlr = 0.0\n\n#----------- emb hypers -----------#\nemb2d_ml_coeff = 0.0\nemb3d_ml_coeff = 0.0\nemb2d_l2_coeff = 0.0\nemb3d_l2_coeff = 0.0\nemb2d_mindist = 0.0\nemb3d_mindist = 0.0\nemb2d_num_samples = 0\nemb3d_num_samples = 0\nemb2d_ce_coeff = 0.0\nemb3d_ce_coeff = 0.0\n\n#----------- feat3d hypers -----------#\nfeat3d_dim = 32\nfeat3d_smooth_coeff = 0.0\n\n#----------- feat2d hypers -----------#\nfeat2d_smooth_coeff = 0.0\nfeat2d_dim = 8\n\n#----------- occ hypers -----------#\nocc_coeff = 0.0\nocc_smooth_coeff = 0.0\n\n#----------- view hypers -----------#\nview_depth = 64\nview_accu_render = False\nview_accu_render_unps = False\nview_accu_render_gt = False\nview_pred_embs = False\nview_pred_rgb = False\nview_l1_coeff = 0.0\n\n#----------- det hypers -----------#\ndet_anchor_size = 12.0\ndet_prob_coeff = 0.0\ndet_reg_coeff = 0.0\n\n#----------- flow hypers -----------#\nflow_warp_coeff = 0.0\nflow_warp_g_coeff = 0.0\nflow_cycle_coeff = 0.0\nflow_smooth_coeff = 0.0\nflow_l1_coeff = 0.0\nflow_l2_coeff = 0.0\n# flow_synth_l1_coeff = 0.0\n# flow_synth_l2_coeff = 0.0\nflow_do_synth_rt = False\nflow_heatmap_size = 4\n\n#----------- ego hypers -----------#\n\nego_num_scales = 1\nego_num_rots = 0\nego_max_disp_z = 0\nego_max_disp_y = 0\nego_max_disp_x = 0\n\nego_max_deg = 0.0\nego_t_l2_coeff = 0.0\nego_deg_l2_coeff = 0.0\n\nego_synth_prob = 0.0\n\n#----------- det hypers -----------#\ndet_anchor_size = 12.0\ndet_prob_coeff = 0.0\ndet_reg_coeff = 0.0\n\n#----------- mod -----------#\n\nmod = '\"\"'\n\n############ slower-to-change hyperparams below here ############\n\n## logging\nlog_freq_train = 100\nlog_freq_val = 100\nlog_freq_test = 100\nsnap_freq = 10000\n\nmax_iters = 10000\nshuffle_train = True\nshuffle_val = True\nshuffle_test = True\n\ntrainset_format = 'seq'\nvalset_format = 'seq'\ntestset_format = 'seq'\n# should the seqdim be taken in consecutive order\ntrainset_consec = True\nvalset_consec = True\ntestset_consec = True\n\ntrainset_seqlen = 2\nvalset_seqlen = 2\ntestset_seqlen = 2\n\ntrainset_batch_size = 2\nvalset_batch_size = 1\ntestset_batch_size = 1\n\ndataset_name = \"\"\nseqname = \"\"\nind_dataset = ''\n\ntrainset = \"\"\nvalset = \"\"\ntestset = \"\"\n\ndataset_location = \"\"\ndataset_filetype = \"npz\"\n\n# mode selection\ndo_carla_static = False\ndo_carla_det = False\ndo_carla_ego = False\n\n############ rev up the experiment ############\n\nmode = os.environ[\"MODE\"]\nprint('os.environ mode is %s' % mode)\nif mode==\"CARLA_STATIC\":\n exec(compile(open('exp_carla_static.py').read(), 'exp_carla_static.py', 'exec'))\nelif mode==\"CARLA_DET\":\n exec(compile(open('exp_carla_det.py').read(), 'exp_carla_det.py', 'exec'))\nelif mode==\"CARLA_EGO\":\n exec(compile(open('exp_carla_ego.py').read(), 'exp_carla_ego.py', 'exec'))\nelse:\n assert(False) # what mode is this?\n\n############ make some final adjustments ############\n\ntrainset_path = \"%s/%s.txt\" % (dataset_location, trainset)\nvalset_path = \"%s/%s.txt\" % (dataset_location, valset)\ntestset_path = \"%s/%s.txt\" % (dataset_location, testset)\n\ndata_paths = {}\ndata_paths['train'] = trainset_path\ndata_paths['val'] = valset_path\ndata_paths['test'] = testset_path\n\nset_nums = {}\nset_nums['train'] = 0\nset_nums['val'] = 1\nset_nums['test'] = 2\n\nset_names = ['train', 'val', 'test']\n\nlog_freqs = {}\nlog_freqs['train'] = log_freq_train\nlog_freqs['val'] = log_freq_val\nlog_freqs['test'] = log_freq_test\n\nshuffles = {}\nshuffles['train'] = shuffle_train\nshuffles['val'] = shuffle_val\nshuffles['test'] = shuffle_test\n\ndata_formats = {}\ndata_formats['train'] = trainset_format\ndata_formats['val'] = valset_format\ndata_formats['test'] = testset_format\n\ndata_consecs = {}\ndata_consecs['train'] = trainset_consec\ndata_consecs['val'] = valset_consec\ndata_consecs['test'] = testset_consec\n\nseqlens = {}\nseqlens['train'] = trainset_seqlen\nseqlens['val'] = valset_seqlen\nseqlens['test'] = testset_seqlen\n\nbatch_sizes = {}\nbatch_sizes['train'] = trainset_batch_size\nbatch_sizes['val'] = valset_batch_size\nbatch_sizes['test'] = testset_batch_size\n\n\n############ autogen a name; don't touch any hypers! ############\n\ndef strnum(x):\n s = '%g' % x\n if '.' in s:\n s = s[s.index('.'):]\n return s\n\nif do_test:\n name = \"%02d_s%d\" % (testset_batch_size, trainset_seqlen)\n name += \"_m%dx%dx%d\" % (Z_test, Y_test, X_test)\nelse:\n name = \"%02d_s%d\" % (trainset_batch_size, trainset_seqlen)\n if do_feat3d:\n name += \"_m%dx%dx%d\" % (Z, Y, X)\n \nif do_view or do_emb2d:\n name += \"_p%dx%d\" % (PH,PW)\n\nif lr > 0.0:\n lrn = \"%.1e\" % lr\n # e.g., 5.0e-04\n lrn = lrn[0] + lrn[3:5] + lrn[-1]\n name += \"_%s\" % lrn\n\nif do_feat2d:\n name += \"_F2\"\n if do_freeze_feat2d:\n name += \"f\"\n coeffs = [\n feat2d_dim,\n feat2d_smooth_coeff,\n ]\n prefixes = [\n \"d\",\n \"s\",\n ]\n for l_, l in enumerate(coeffs):\n if l > 0:\n name += \"_%s%s\" % (prefixes[l_],strnum(l))\n \nif do_feat3d:\n name += \"_F3\"\n if do_freeze_feat3d:\n name += \"f\"\n coeffs = [\n feat3d_dim,\n feat3d_smooth_coeff,\n ]\n prefixes = [\n \"d\",\n \"s\",\n ]\n for l_, l in enumerate(coeffs):\n if l > 0:\n name += \"_%s%s\" % (prefixes[l_],strnum(l))\n\nif do_ego:\n name += '_G_%dx%dx%dx%dx%d' % (\n ego_num_scales,\n ego_num_rots,\n ego_max_disp_z, \n ego_max_disp_y, \n ego_max_disp_x,\n )\n if do_freeze_ego:\n name += \"f\"\n ego_coeffs = [\n ego_max_deg,\n ego_t_l2_coeff,\n ego_deg_l2_coeff,\n ego_synth_prob,\n ]\n ego_prefixes = [\n \"r\",\n \"t\",\n \"d\",\n \"p\",\n ]\n for l_, l in enumerate(ego_coeffs):\n if l > 0:\n name += \"_%s%s\" % (ego_prefixes[l_],strnum(l))\n\nif do_det:\n name += \"_D\"\n name += \"%d\" % det_anchor_size\n if do_freeze_det:\n name += \"f\"\n det_coeffs = [\n det_prob_coeff,\n det_reg_coeff,\n ]\n det_prefixes = [\n \"p\",\n \"r\",\n ]\n for l_, l in enumerate(det_coeffs):\n if l > 0:\n name += \"_%s%s\" % (det_prefixes[l_],strnum(l))\n\nif do_occ:\n name += \"_O\"\n if do_freeze_occ:\n name += \"f\"\n occ_coeffs = [\n occ_coeff,\n occ_smooth_coeff,\n ]\n occ_prefixes = [\n \"c\",\n \"s\",\n ]\n for l_, l in enumerate(occ_coeffs):\n if l > 0:\n name += \"_%s%s\" % (occ_prefixes[l_],strnum(l))\n\nif do_view:\n name += \"_V\"\n if view_pred_embs:\n name += \"e\"\n if view_pred_rgb:\n name += \"r\"\n if do_freeze_view:\n name += \"f\"\n view_coeffs = [\n view_depth,\n view_l1_coeff,\n ]\n view_prefixes = [\n \"d\",\n \"e\",\n ]\n for l_, l in enumerate(view_coeffs):\n if l > 0:\n name += \"_%s%s\" % (view_prefixes[l_],strnum(l))\n\nif do_det:\n name += \"_D\"\n name += \"%d\" % det_anchor_size\n if do_freeze_det:\n name += \"f\"\n det_coeffs = [\n det_prob_coeff,\n det_reg_coeff,\n ]\n det_prefixes = [\n \"p\",\n \"r\",\n ]\n for l_, l in enumerate(det_coeffs):\n if l > 0:\n name += \"_%s%s\" % (det_prefixes[l_],strnum(l))\n \nif do_emb2d:\n name += \"_E2\"\n if do_freeze_emb2d:\n name += \"f\"\n coeffs = [\n emb2d_ml_coeff,\n emb2d_l2_coeff,\n emb2d_num_samples,\n emb2d_mindist,\n emb2d_ce_coeff,\n ]\n prefixes = [\n \"m\",\n \"e\",\n \"n\",\n \"d\",\n \"c\",\n ]\n for l_, l in enumerate(coeffs):\n if l > 0:\n name += \"_%s%s\" % (prefixes[l_],strnum(l))\n \nif do_emb3d:\n name += \"_E3\"\n coeffs = [\n emb3d_ml_coeff,\n emb3d_l2_coeff,\n emb3d_num_samples,\n emb3d_mindist,\n emb3d_ce_coeff,\n ]\n prefixes = [\n \"m\",\n \"e\",\n \"n\",\n \"d\",\n \"c\",\n ]\n for l_, l in enumerate(coeffs):\n if l > 0:\n name += \"_%s%s\" % (prefixes[l_],strnum(l))\n \nif do_flow:\n name += \"_F\"\n if do_freeze_flow:\n name += \"f\"\n else:\n flow_coeffs = [flow_heatmap_size,\n flow_warp_coeff,\n flow_warp_g_coeff,\n flow_cycle_coeff,\n flow_smooth_coeff,\n flow_l1_coeff,\n flow_l2_coeff,\n # flow_synth_l1_coeff,\n # flow_synth_l2_coeff,\n ]\n flow_prefixes = [\"h\",\n \"w\",\n \"g\",\n \"c\",\n \"s\",\n \"e\",\n \"f\",\n # \"y\",\n # \"x\",\n ]\n for l_, l in enumerate(flow_coeffs):\n if l > 0:\n name += \"_%s%s\" % (flow_prefixes[l_],strnum(l))\n\n##### end model description\n\n# add some training data info\n\nsets_to_run = {}\nif trainset:\n name = \"%s_%s\" % (name, trainset)\n sets_to_run['train'] = True\nelse:\n sets_to_run['train'] = False\n\nif valset:\n name = \"%s_%s\" % (name, valset)\n sets_to_run['val'] = True\nelse:\n sets_to_run['val'] = False\n\nif testset:\n name = \"%s_%s\" % (name, testset)\n sets_to_run['test'] = True\nelse:\n sets_to_run['test'] = False\n\nsets_to_backprop = {}\nsets_to_backprop['train'] = backprop_on_train\nsets_to_backprop['val'] = backprop_on_val\nsets_to_backprop['test'] = backprop_on_test\n\nif (not shuffle_train) or (not shuffle_val) or (not shuffle_test):\n name += \"_ns\"\n\nif mod:\n name = \"%s_%s\" % (name, mod)\n\nif do_resume:\n name += '_gt'\n total_init = name\n\nprint(name)\n" }, { "alpha_fraction": 0.501198410987854, "alphanum_fraction": 0.5334221124649048, "avg_line_length": 22.03680992126465, "blob_id": "6683a729609e114288dfee10f421aba99577304e", "content_id": "2249188b3a096572d67e33a3d050784b44e15399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3755, "license_type": "no_license", "max_line_length": 83, "num_lines": 163, "path": "/exp_carla_ego.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "from exp_base import *\n\n############## choose an experiment ##############\n\ncurrent = 'builder'\ncurrent = 'debugger'\ncurrent = 'trainer'\n\nmod = '\"eg00\"' # nothing; builder\nmod = '\"eg01\"' # deleted junk\nmod = '\"eg02\"' # added hyps\nmod = '\"eg03\"' # train a while\nmod = '\"eg04\"' # 1 scale\nmod = '\"eg05\"' # no synth\nmod = '\"eg06\"' # consec=True\nmod = '\"eg07\"' # comment out the synth part < ok. but this npz has no motion\nmod = '\"eg08\"' # second file < a bit jumpier than i would like...\nmod = '\"eg09\"' # S = 3\nmod = '\"eg10\"' # make my own thing; assert S==2 < ok, much cleaner, but still jumpy\nmod = '\"eg11\"' # cleaned up summs\nmod = '\"eg12\"' # cleaned up summs; include the occ transform \nmod = '\"eg13\"' # removed the warp loss\nmod = '\"eg14\"' # add summ of the gt\nmod = '\"eg15\"' # fix the hyps\nmod = '\"eg16\"' # renamed DHW as ZYX\nmod = '\"eg17\"' # same, fewer prints\nmod = '\"eg18\"' # feed rgbd input\nmod = '\"eg19\"' # cleaned up\nmod = '\"eg20\"' # train a while\n\n############## exps ##############\n\nexps['builder'] = [\n 'carla_ego', # mode\n 'carla_traj_10_data', # dataset\n 'carla_bounds', \n '3_iters',\n 'lr0',\n 'B1',\n 'no_shuf',\n 'train_feat3d',\n 'train_ego',\n 'log1',\n]\nexps['debugger'] = [\n 'carla_ego', # mode\n 'carla_traj_1_data', # dataset\n 'carla_bounds', \n '1k_iters',\n 'lr4',\n 'B1',\n 'train_feat3d',\n 'train_ego',\n 'no_shuf',\n 'log10',\n]\nexps['trainer'] = [\n 'carla_ego', # mode\n 'carla_traj_train_data', # dataset\n 'carla_bounds', \n '100k_iters',\n 'lr4',\n 'B2',\n 'train_feat3d',\n 'train_ego',\n 'log50',\n]\n\n############## groups ##############\n\ngroups['carla_ego'] = ['do_carla_ego = True']\n\ngroups['train_feat3d'] = [\n 'do_feat3d = True',\n 'feat3d_dim = 32',\n]\ngroups['train_ego'] = [\n 'do_ego = True',\n 'ego_t_l2_coeff = 1.0',\n 'ego_deg_l2_coeff = 1.0',\n 'ego_num_scales = 2',\n 'ego_num_rots = 11',\n 'ego_max_deg = 4.0',\n 'ego_max_disp_z = 2',\n 'ego_max_disp_y = 1',\n 'ego_max_disp_x = 2',\n 'ego_synth_prob = 0.0',\n]\n\n############## datasets ##############\n\n# dims for mem\nSIZE = 32\nZ = int(SIZE*4)\nY = int(SIZE*1)\nX = int(SIZE*4)\nK = 2 # how many objects to consider\nN = 8 # how many objects per npz\nS = 2\nH = 128\nW = 384\n# H and W for proj stuff\nPH = int(H/2.0)\nPW = int(W/2.0)\n\ndataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"\n\ngroups['carla_traj_1_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"taqs100i2one\"',\n 'trainset_format = \"traj\"', \n 'trainset_consec = True', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_traj_10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"taqs100i2ten\"',\n 'trainset_format = \"traj\"', \n 'trainset_consec = True', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_traj_train_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"taqs100i2t\"',\n 'trainset_format = \"traj\"', \n 'trainset_consec = True', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\n\n############## verify and execute ##############\n\ndef _verify_(s):\n varname, eq, val = s.split(' ')\n assert varname in globals()\n assert eq == '='\n assert type(s) is type('')\n\nprint(current)\nassert current in exps\nfor group in exps[current]:\n print(\" \" + group)\n assert group in groups\n for s in groups[group]:\n print(\" \" + s)\n _verify_(s)\n exec(s)\n\ns = \"mod = \" + mod\n_verify_(s)\n\nexec(s)\n" }, { "alpha_fraction": 0.5635464787483215, "alphanum_fraction": 0.5858714580535889, "avg_line_length": 38.295597076416016, "blob_id": "9987e284b32a42ee848e15856c8766a796142a9f", "content_id": "54c48493d7ae2fd395895504e9c6bb40666f4731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6271, "license_type": "no_license", "max_line_length": 161, "num_lines": 159, "path": "/archs/encoder3d.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport time\nimport torch.nn.functional as F\nimport archs.pixelshuffle3d\n\nclass Skipnet3d(nn.Module):\n def __init__(self, in_dim, out_dim, chans=64):\n super(Skipnet3d, self).__init__()\n conv3d = []\n up_bn = [] # batch norm for deconv\n conv3d_transpose = []\n\n self.down_in_dims = [in_dim, chans, 2*chans]#, 4*chans]\n self.down_out_dims = [chans, 2*chans, 4*chans, 8*chans]\n self.down_ksizes = [4, 4, 4, 4]\n self.down_strides = [2, 2, 2, 2]\n padding = 1\n # print('down dims: ', self.down_out_dims)\n\n for i, (in_chan, out_chan, ksize, stride) in enumerate(zip(self.down_in_dims, self.down_out_dims, self.down_ksizes, self.down_strides)):\n conv3d.append(nn.Sequential(\n nn.ReplicationPad3d(padding),\n nn.Conv3d(in_channels=in_chan, out_channels=out_chan, kernel_size=ksize, stride=stride, padding=0),\n # nn.Conv3d(in_channels=in_chan, out_channels=out_chan, kernel_size=ksize, stride=stride, padding=padding),\n nn.LeakyReLU(),\n nn.BatchNorm3d(num_features=out_chan),\n ))\n self.conv3d = nn.ModuleList(conv3d)\n\n self.up_in_dims = [4*chans, 6*chans]\n self.up_out_dims = [4*chans, 4*chans]\n self.up_bn_dims = [6*chans, 5*chans]\n self.up_ksizes = [4, 4]\n self.up_strides = [2, 2]\n padding = 1 \n # print('up dims: ', self.up_out_dims)\n\n for i, (in_chan, bn_dim, out_chan, ksize, stride) in enumerate(zip(self.up_in_dims, self.up_bn_dims, self.up_out_dims, self.up_ksizes, self.up_strides)):\n conv3d_transpose.append(nn.Sequential(\n nn.ConvTranspose3d(in_channels=in_chan, out_channels=out_chan, kernel_size=ksize, stride=stride, padding=padding),\n nn.LeakyReLU(),\n ))\n up_bn.append(nn.BatchNorm3d(num_features=bn_dim))\n self.conv3d_transpose = nn.ModuleList(conv3d_transpose)\n self.up_bn = nn.ModuleList(up_bn)\n\n # final 1x1x1 conv to get our desired out_dim\n self.final_feature = nn.Conv3d(in_channels=self.up_bn_dims[-1], out_channels=out_dim, kernel_size=1, stride=1, padding=0)\n \n def forward(self, inputs):\n feat = inputs\n skipcons = []\n for conv3d_layer in self.conv3d:\n feat = conv3d_layer(feat)\n skipcons.append(feat)\n skipcons.pop() # we don't want the innermost layer as skipcon\n\n for i, (conv3d_transpose_layer, bn_layer) in enumerate(zip(self.conv3d_transpose, self.up_bn)):\n # print('feat before up', feat.shape)\n feat = conv3d_transpose_layer(feat)\n feat = torch.cat([feat, skipcons.pop()], dim=1) #skip connection by concatenation\n # print('feat before bn', feat.shape)\n feat = bn_layer(feat)\n\n feat = self.final_feature(feat)\n return feat\n\nclass Res3dBlock(nn.Module):\n def __init__(self, in_planes, out_planes, padding=1):\n super(Res3dBlock, self).__init__()\n self.res_branch = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=1, padding=padding),\n nn.BatchNorm3d(out_planes),\n nn.ReLU(True),\n nn.Conv3d(out_planes, out_planes, kernel_size=3, stride=1, padding=padding),\n nn.BatchNorm3d(out_planes)\n )\n assert(padding==1 or padding==0)\n self.padding = padding\n\n if in_planes == out_planes:\n self.skip_con = nn.Sequential()\n else:\n self.skip_con = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=1, padding=0),\n nn.BatchNorm3d(out_planes)\n )\n\n def forward(self, x):\n res = self.res_branch(x)\n # print('res', res.shape)\n skip = self.skip_con(x)\n if self.padding==0:\n # the data has shrunk a bit\n skip = skip[:,:,2:-2,2:-2,2:-2]\n # print('skip', skip.shape)\n return F.relu(res + skip, True)\n\nclass Conv3dBlock(nn.Module):\n def __init__(self, in_planes, out_planes, stride=1):\n super(Conv3dBlock, self).__init__()\n self.conv = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride, padding=0),\n nn.BatchNorm3d(out_planes),\n nn.ReLU(True),\n )\n\n def forward(self, x):\n return self.conv(x)\n\nclass Pool3dBlock(nn.Module):\n def __init__(self, pool_size):\n super(Pool3dBlock, self).__init__()\n self.pool_size = pool_size\n\n def forward(self, x):\n return F.max_pool3d(x, kernel_size=self.pool_size, stride=self.pool_size)\n\nclass Deconv3dBlock(nn.Module):\n def __init__(self, in_planes, out_planes):\n super(Deconv3dBlock, self).__init__()\n self.deconv = nn.Sequential(\n nn.ConvTranspose3d(in_planes, out_planes, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(),\n )\n\n def forward(self, x):\n return self.deconv(x)\n\nclass Resnet3d(nn.Module):\n def __init__(self, in_dim, out_dim, chans=32):\n super().__init__()\n\n self.encoder_layer0 = Res3dBlock(in_dim, chans)\n self.encoder_layer1 = Pool3dBlock(2)\n self.encoder_layer2 = Res3dBlock(chans, chans)\n self.encoder_layer3 = Res3dBlock(chans, chans)\n self.encoder_layer4 = Res3dBlock(chans, chans)\n self.encoder_layer5 = Pool3dBlock(2)\n self.encoder_layer6 = Res3dBlock(chans, chans)\n self.encoder_layer7 = Res3dBlock(chans, chans)\n self.encoder_layer8 = Res3dBlock(chans, chans)\n self.encoder_layer9 = Deconv3dBlock(chans, chans)\n self.final_layer = nn.Conv3d(in_channels=chans, out_channels=out_dim, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n x = self.encoder_layer0(x)\n x = self.encoder_layer1(x)\n x = self.encoder_layer2(x)\n x = self.encoder_layer3(x)\n x = self.encoder_layer4(x)\n x = self.encoder_layer5(x)\n x = self.encoder_layer6(x)\n x = self.encoder_layer7(x)\n x = self.encoder_layer8(x)\n x = self.encoder_layer9(x)\n x = self.final_layer(x)\n return x\n \n \n \n\n\n\n \n" }, { "alpha_fraction": 0.5247947573661804, "alphanum_fraction": 0.5303776860237122, "avg_line_length": 38.283870697021484, "blob_id": "39a32cea351724f5daccf24c8e2e4a1d529fc37c", "content_id": "85470a7b881f993042df357b0e9e7e4f3d04eafb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6090, "license_type": "no_license", "max_line_length": 109, "num_lines": 155, "path": "/backend/saverloader.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport os,pathlib\nimport hyperparams as hyp\nimport numpy as np\n\n\ndef load_total(model, optimizer):\n start_iter = 0\n if hyp.total_init:\n print(\"TOTAL INIT\")\n print(hyp.total_init)\n start_iter = load(hyp.total_init, model, optimizer)\n if start_iter:\n print(\"loaded full model. resuming from iter %08d\" % start_iter)\n else:\n print(\"could not find a full model. starting from scratch\")\n return start_iter\n\ndef load_weights(model, optimizer):\n if hyp.total_init:\n print(\"TOTAL INIT\")\n print(hyp.total_init)\n start_iter = load(hyp.total_init, model, optimizer)\n if start_iter:\n print(\"loaded full model. resuming from iter %08d\" % start_iter)\n else:\n print(\"could not find a full model. starting from scratch\")\n else:\n # if (1):\n start_iter = 0\n inits = {\"feat2dnet\": hyp.feat2d_init,\n \"feat3dnet\": hyp.feat3d_init,\n \"viewnet\": hyp.view_init,\n \"detnet\": hyp.det_init,\n \"flownet\": hyp.flow_init,\n \"egonet\": hyp.ego_init,\n \"occnet\": hyp.occ_init,\n }\n\n for part, init in list(inits.items()):\n # print('part', part)\n if init:\n if part == 'feat2dnet':\n model_part = model.feat2dnet\n elif part == 'feat3dnet':\n model_part = model.feat3dnet\n elif part == 'occnet':\n model_part = model.occnet\n elif part == 'flownet':\n model_part = model.flownet\n else:\n assert(False)\n if isinstance(model_part, list):\n for mp in model_part:\n iter = load_part([mp], part, init)\n else:\n iter = load_part(model_part, part, init)\n if iter:\n print(\"loaded %s at iter %08d\" % (init, iter))\n else:\n print(\"could not find a checkpoint for %s\" % init)\n if hyp.reset_iter:\n start_iter = 0\n return start_iter\n\n\ndef save(model, checkpoint_dir, step, optimizer, keep_latest=3):\n model_name = \"model-%08d.pth\"%(step)\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n prev_chkpts = list(pathlib.Path(checkpoint_dir).glob('model-*'))\n prev_chkpts.sort(key=lambda p: p.stat().st_mtime,reverse=True)\n if len(prev_chkpts) > keep_latest-1:\n for f in prev_chkpts[keep_latest-1:]:\n f.unlink()\n path = os.path.join(checkpoint_dir, model_name)\n torch.save({\n 'step': step,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()\n }, path)\n print(\"Saved a checkpoint: %s\"%(path))\n \ndef load(model_name, model, optimizer):\n print(\"reading full checkpoint...\")\n # checkpoint_dir = os.path.join(\"checkpoints/\", model_name)\n checkpoint_dir = os.path.join(\"saved_checkpoints/\", model_name)\n step = 0\n if not os.path.exists(checkpoint_dir):\n print(\"...ain't no full checkpoint here!\")\n else:\n ckpt_names = os.listdir(checkpoint_dir)\n steps = [int((i.split('-')[1]).split('.')[0]) for i in ckpt_names]\n if len(ckpt_names) > 0:\n step = max(steps)\n model_name = 'model-%08d.pth' % (step)\n path = os.path.join(checkpoint_dir, model_name)\n print(\"...found checkpoint %s\"%(path))\n\n checkpoint = torch.load(path)\n \n # # Print model's state_dict\n # print(\"Model's state_dict:\")\n # for param_tensor in model.state_dict():\n # print(param_tensor, \"\\t\", model.state_dict()[param_tensor].size())\n # input()\n\n # # Print optimizer's state_dict\n # print(\"Optimizer's state_dict:\")\n # for var_name in optimizer.state_dict():\n # print(var_name, \"\\t\", optimizer.state_dict()[var_name])\n # input()\n \n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n else:\n print(\"...ain't no full checkpoint here!\")\n return step\n\ndef load_part(model, part, init):\n print(\"reading %s checkpoint...\" % part)\n init_dir = os.path.join(\"saved_checkpoints\", init)\n print(init_dir)\n step = 0\n if not os.path.exists(init_dir):\n print(\"...ain't no %s checkpoint here!\"%(part))\n else:\n ckpt_names = os.listdir(init_dir)\n steps = [int((i.split('-')[1]).split('.')[0]) for i in ckpt_names]\n if len(ckpt_names) > 0:\n step = max(steps)\n ind = np.argmax(steps)\n model_name = ckpt_names[ind]\n path = os.path.join(init_dir, model_name)\n print(\"...found checkpoint %s\" % (path))\n\n checkpoint = torch.load(path)\n model_state_dict = model.state_dict()\n # print(model_state_dict.keys())\n for load_param_name, param in checkpoint['model_state_dict'].items():\n model_param_name = load_param_name[len(part)+1:]\n # print('load_param_name', load_param_name, 'model_param_name', model_param_name)\n if part+\".\"+model_param_name != load_param_name:\n continue\n else:\n if model_param_name in model_state_dict.keys():\n # print(model_param_name, load_param_name)\n # print('param in ckpt', param.data.shape)\n # print('param in state dict', model_state_dict[model_param_name].shape)\n model_state_dict[model_param_name].copy_(param.data)\n else:\n print('warning: %s is not in the state dict of the current model' % model_param_name)\n else:\n print(\"...ain't no %s checkpoint here!\"%(part))\n return step\n\n" }, { "alpha_fraction": 0.5522388219833374, "alphanum_fraction": 0.5522388219833374, "avg_line_length": 12.333333015441895, "blob_id": "519fd0f0d48804b3b1ee5f6dca4f5ff21b7c9708", "content_id": "5cbc400a6121c8d2fe538fd468419a5b968e98ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 201, "license_type": "no_license", "max_line_length": 24, "num_lines": 15, "path": "/carla_det_go.sh", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e # exit on error\n\necho \"-----\"\necho \"CARLA_DET GO\"\necho \"-----\"\n\nMODE=\"CARLA_DET\"\nexport MODE\npython -W ignore main.py\n\necho \"----------\"\necho \"CARLA_DET GO DONE\"\necho \"----------\"\n\n" }, { "alpha_fraction": 0.5729748606681824, "alphanum_fraction": 0.596717894077301, "avg_line_length": 39.30986022949219, "blob_id": "abf54e7952629ad166cd2580bb2e93175418b135", "content_id": "c3846dd6bd22c361f24bc92deb542f5981d695d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2864, "license_type": "no_license", "max_line_length": 159, "num_lines": 71, "path": "/archs/encoder2d.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\n\n# import hyperparams as hyp\n# from utils_basic import *\n\nclass Skipnet2d(nn.Module):\n def __init__(self, in_chans, mid_chans=64, out_chans=1):\n super(Skipnet2d, self).__init__()\n conv2d = []\n conv2d_transpose = []\n up_bn = []\n\n self.down_in_dims = [in_chans, mid_chans, 2*mid_chans]\n self.down_out_dims = [mid_chans, 2*mid_chans, 4*mid_chans]\n self.down_ksizes = [3, 3, 3]\n self.down_strides = [2, 2, 2]\n padding = 1\n\n for i, (in_dim, out_dim, ksize, stride) in enumerate(zip(self.down_in_dims, self.down_out_dims, self.down_ksizes, self.down_strides)):\n conv2d.append(nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=ksize, stride=stride, padding=padding),\n nn.LeakyReLU(),\n nn.BatchNorm2d(num_features=out_dim),\n ))\n self.conv2d = nn.ModuleList(conv2d)\n\n self.up_in_dims = [4*mid_chans, 6*mid_chans]\n self.up_bn_dims = [6*mid_chans, 3*mid_chans]\n self.up_out_dims = [4*mid_chans, 2*mid_chans]\n self.up_ksizes = [4, 4]\n self.up_strides = [2, 2]\n padding = 1 # Note: this only holds for ksize=4 and stride=2!\n print('up dims: ', self.up_out_dims)\n\n for i, (in_dim, bn_dim, out_dim, ksize, stride) in enumerate(zip(self.up_in_dims, self.up_bn_dims, self.up_out_dims, self.up_ksizes, self.up_strides)):\n conv2d_transpose.append(nn.Sequential(\n nn.ConvTranspose2d(in_channels=in_dim, out_channels=out_dim, kernel_size=ksize, stride=stride, padding=padding),\n nn.LeakyReLU(),\n ))\n up_bn.append(nn.BatchNorm2d(num_features=bn_dim))\n\n # final 1x1x1 conv to get our desired out_chans\n self.final_feature = nn.Conv2d(in_channels=3*mid_chans, out_channels=out_chans, kernel_size=1, stride=1, padding=0)\n self.conv2d_transpose = nn.ModuleList(conv2d_transpose)\n self.up_bn = nn.ModuleList(up_bn)\n \n def forward(self, inputs):\n feat = inputs\n skipcons = []\n for conv2d_layer in self.conv2d:\n feat = conv2d_layer(feat)\n skipcons.append(feat)\n\n skipcons.pop() # we don't want the innermost layer as skipcon\n\n for i, (conv2d_transpose_layer, bn_layer) in enumerate(zip(self.conv2d_transpose, self.up_bn)):\n feat = conv2d_transpose_layer(feat)\n feat = torch.cat([feat, skipcons.pop()], dim=1) # skip connection by concatenation\n feat = bn_layer(feat)\n\n feat = self.final_feature(feat)\n\n return feat\n\nif __name__ == \"__main__\":\n net = Skipnet2d(in_chans=4, mid_chans=32, out_chans=3)\n print(net.named_parameters)\n inputs = torch.rand(2, 4, 128, 384)\n out = net(inputs)\n print(out.size())\n\n\n" }, { "alpha_fraction": 0.3919999897480011, "alphanum_fraction": 0.6959999799728394, "avg_line_length": 34.71428680419922, "blob_id": "b22fdc393b09265744a158975f6d51e16070e1ae", "content_id": "c0ce64045dfd390f16b2c2e754d6794cf44a3485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 118, "num_lines": 7, "path": "/pretrained_nets_carla.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "ckpt = '02_s2_m128x32x128_p64x192_1e-3_F2_d32_F3_d32_s.01_O_c1_s.01_V_d32_e1_E2_e.1_n4_d32_c1_E3_n2_c1_mags7i3t_sta41'\nckpt = '02_s2_m128x32x128_1e-3_F3_d32_s.01_O_c2_s.1_E3_n2_c.1_mags7i3t_sta48'\n\nfeat3d_init = ckpt\nfeat3d_dim = 32\n\nocc_init = ckpt\n" }, { "alpha_fraction": 0.5534031391143799, "alphanum_fraction": 0.5539267063140869, "avg_line_length": 29.317461013793945, "blob_id": "9e1da0ba4e46f5670a75cf6da626195366179de8", "content_id": "abe1834ee988f6a1641e4c5b12862c0976c25bc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1910, "license_type": "no_license", "max_line_length": 62, "num_lines": 63, "path": "/main.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "from model_carla_static import CARLA_STATIC\nfrom model_carla_ego import CARLA_EGO\nfrom model_carla_det import CARLA_DET\n\nimport hyperparams as hyp\nimport os\nimport logging\n\nlogger = logging.Logger('catch_all')\n\ndef main():\n checkpoint_dir_ = os.path.join(\"checkpoints\", hyp.name)\n \n if hyp.do_carla_static:\n log_dir_ = os.path.join(\"logs_carla_static\", hyp.name)\n elif hyp.do_carla_ego:\n log_dir_ = os.path.join(\"logs_carla_ego\", hyp.name)\n elif hyp.do_carla_det:\n log_dir_ = os.path.join(\"logs_carla_det\", hyp.name)\n else:\n assert(False) # what mode is this?\n\n if not os.path.exists(checkpoint_dir_):\n os.makedirs(checkpoint_dir_)\n if not os.path.exists(log_dir_):\n os.makedirs(log_dir_)\n try:\n if hyp.do_carla_static:\n model = CARLA_STATIC(\n checkpoint_dir=checkpoint_dir_,\n log_dir=log_dir_)\n model.go()\n elif hyp.do_carla_ego:\n model = CARLA_EGO(\n checkpoint_dir=checkpoint_dir_,\n log_dir=log_dir_)\n model.go()\n elif hyp.do_carla_det:\n model = CARLA_DET(\n checkpoint_dir=checkpoint_dir_,\n log_dir=log_dir_)\n model.go()\n else:\n assert(False) # what mode is this?\n except (Exception, KeyboardInterrupt) as ex:\n logger.error(ex, exc_info=True)\n log_cleanup(log_dir_)\n\ndef log_cleanup(log_dir_):\n log_dirs = []\n for set_name in hyp.set_names:\n log_dirs.append(log_dir_ + '/' + set_name)\n\n for log_dir in log_dirs:\n for r, d, f in os.walk(log_dir):\n for file_dir in f:\n file_dir = os.path.join(log_dir, file_dir)\n file_size = os.stat(file_dir).st_size\n if file_size == 0:\n os.remove(file_dir)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5628505945205688, "alphanum_fraction": 0.5954869985580444, "avg_line_length": 41.16666793823242, "blob_id": "f24b64e5e7eb72e79fa5988fb484edfd8ffa4ad5", "content_id": "3b7161aaff26cb0baa3f4d08b100af45b0fa1eef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7844, "license_type": "no_license", "max_line_length": 121, "num_lines": 186, "path": "/nets/flownet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# from spatial_correlation_sampler import SpatialCorrelationSampler\nimport numpy as np\n\n# import sys\n# sys.path.append(\"..\")\n\nimport archs.encoder3D\nimport hyperparams as hyp\nimport utils_basic\nimport utils_improc\nimport utils_misc\nimport utils_samp\nimport math\n\nclass FlowNet(nn.Module):\n def __init__(self):\n super(FlowNet, self).__init__()\n\n print('FlowNet...')\n\n self.debug = False\n # self.debug = True\n \n self.heatmap_size = hyp.flow_heatmap_size\n # self.scales = [0.0625, 0.125, 0.25, 0.5, 0.75, 1.0]\n # self.scales = [1.0]\n # self.scales = [0.25, 0.5, 1.0]\n # self.scales = [0.125, 0.25, 0.5, 0.75, 1.0]\n self.scales = [0.25, 0.5, 0.75, 1.0]\n self.num_scales = len(self.scales)\n\n # self.compress_dim = 16\n # self.compressor = nn.Sequential(\n # nn.Conv3d(in_channels=hyp.feat_dim, out_channels=self.compress_dim, kernel_size=1, stride=1, padding=0),\n # )\n\n self.correlation_sampler = SpatialCorrelationSampler(\n kernel_size=1,\n patch_size=self.heatmap_size,\n stride=1,\n padding=0,\n dilation_patch=1,\n ).cuda()\n \n self.flow_predictor = nn.Sequential(\n nn.Conv3d(in_channels=(self.heatmap_size**3), out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1),\n nn.Conv3d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1),\n nn.Conv3d(in_channels=64, out_channels=3, kernel_size=1, stride=1, padding=0),\n ).cuda()\n \n self.smoothl1 = torch.nn.SmoothL1Loss(reduction='none')\n self.smoothl1_mean = torch.nn.SmoothL1Loss(reduction='mean')\n self.mse = torch.nn.MSELoss(reduction='none')\n self.mse_mean = torch.nn.MSELoss(reduction='mean')\n\n print(self.flow_predictor)\n\n def generate_flow(self, feat0, feat1, sc):\n B, C, D, H, W = list(feat0.shape)\n utils_basic.assert_same_shape(feat0, feat1)\n\n if self.debug:\n print('scale = %.2f' % sc)\n print('inputs:')\n print(feat0.shape)\n print(feat1.shape)\n\n if not sc==1.0:\n # assert(sc==0.5 or sc==0.25) # please only use 0.25, 0.5, or 1.0 right now\n feat0 = F.interpolate(feat0, scale_factor=sc, mode='trilinear', align_corners=False)\n feat1 = F.interpolate(feat1, scale_factor=sc, mode='trilinear', align_corners=False)\n D, H, W = int(D*sc), int(H*sc), int(W*sc)\n if self.debug:\n print('downsamps:')\n print(feat0.shape)\n print(feat1.shape)\n\n feat0 = feat0.contiguous()\n feat1 = feat1.contiguous()\n\n cc = self.correlation_sampler(feat0, feat1)\n if self.debug:\n print('cc:')\n print(cc.shape)\n cc = cc.view(B, self.heatmap_size**3, D, H, W)\n\n cc = F.relu(cc) # relu works better than leaky relu here\n if self.debug:\n print(cc.shape)\n cc = utils_basic.l2_normalize(cc, dim=1)\n\n flow = self.flow_predictor(cc)\n if self.debug:\n print('flow:')\n print(flow.shape)\n\n if not sc==1.0:\n # note 1px here means 1px/sc at the real scale\n # first let's put the pixels in the right places\n flow = F.interpolate(flow, scale_factor=(1./sc), mode='trilinear', align_corners=False)\n # now let's correct the scale\n flow = flow/sc\n\n if self.debug:\n print('flow up:')\n print(flow.shape)\n \n return flow\n\n def forward(self, feat0, feat1, flow_g, mask_g, summ_writer=None):\n total_loss = torch.tensor(0.0).cuda()\n\n B, C, D, H, W = list(feat0.shape)\n utils_basic.assert_same_shape(feat0, feat1)\n\n # feats = torch.cat([feat0, feat1], dim=0)\n # feats = self.compressor(feats)\n # feats = utils_basic.l2_normalize(feats, dim=1)\n # feat0, feat1 = feats[:B], feats[B:]\n\n flow_total = torch.zeros_like(flow_g)\n feat1_aligned = feat1.clone()\n\n # summ_writer.summ_feats('flow/feats_aligned_%.2f' % 0.0, [feat0, feat1_aligned])\n feat_diff = torch.mean(utils_basic.l2_on_axis((feat1_aligned-feat0), 1, keepdim=True))\n utils_misc.add_loss('flow/feat_align_diff_%.2f' % 0.0, 0, feat_diff, 0, summ_writer)\n\n for sc in self.scales:\n flow = self.generate_flow(feat0, feat1_aligned, sc)\n flow_total = flow_total + flow\n\n # compositional LK: warp the original thing using the cumulative flow\n feat1_aligned = utils_samp.backwarp_using_3D_flow(feat1, flow_total)\n valid1_region = utils_samp.backwarp_using_3D_flow(torch.ones_like(feat1[:,0:1]), flow_total)\n # summ_writer.summ_feats('flow/feats_aligned_%.2f' % sc, [feat0, feat1_aligned],\n # valids=[torch.ones_like(valid1_region), valid1_region])\n feat_diff = utils_basic.reduce_masked_mean(\n utils_basic.l2_on_axis((feat1_aligned-feat0), 1, keepdim=True), valid1_region)\n utils_misc.add_loss('flow/feat_align_diff_%.2f' % sc, 0, feat_diff, 0, summ_writer)\n\n # ok done inference\n # now for losses/metrics:\n l1_diff_3chan = self.smoothl1(flow_total, flow_g)\n l1_diff = torch.mean(l1_diff_3chan, dim=1, keepdim=True)\n l2_diff_3chan = self.mse(flow_total, flow_g)\n l2_diff = torch.mean(l2_diff_3chan, dim=1, keepdim=True)\n\n nonzero_mask = ((torch.sum(torch.abs(flow_g), axis=1, keepdim=True) > 0.01).float())*mask_g\n yeszero_mask = (1.0-nonzero_mask)*mask_g\n l1_loss = utils_basic.reduce_masked_mean(l1_diff, mask_g)\n l2_loss = utils_basic.reduce_masked_mean(l2_diff, mask_g)\n l1_loss_nonzero = utils_basic.reduce_masked_mean(l1_diff, nonzero_mask)\n l1_loss_yeszero = utils_basic.reduce_masked_mean(l1_diff, yeszero_mask)\n l1_loss_balanced = (l1_loss_nonzero + l1_loss_yeszero)*0.5\n l2_loss_nonzero = utils_basic.reduce_masked_mean(l2_diff, nonzero_mask)\n l2_loss_yeszero = utils_basic.reduce_masked_mean(l2_diff, yeszero_mask)\n l2_loss_balanced = (l2_loss_nonzero + l2_loss_yeszero)*0.5\n\n clip = np.squeeze(torch.max(torch.abs(torch.mean(flow_g[0], dim=0))).detach().cpu().numpy()).item()\n if summ_writer is not None:\n summ_writer.summ_3D_flow('flow/flow_e_%.2f' % sc, flow_total*mask_g, clip=clip)\n summ_writer.summ_3D_flow('flow/flow_g_%.2f' % sc, flow_g, clip=clip)\n\n utils_misc.add_loss('flow/l1_loss_nonzero', 0, l1_loss_nonzero, 0, summ_writer)\n utils_misc.add_loss('flow/l1_loss_yeszero', 0, l1_loss_yeszero, 0, summ_writer)\n utils_misc.add_loss('flow/l1_loss_balanced', 0, l1_loss_balanced, 0, summ_writer)\n\n total_loss = utils_misc.add_loss('flow/l1_loss', total_loss, l1_loss, hyp.flow_l1_coeff, summ_writer)\n total_loss = utils_misc.add_loss('flow/l2_loss', total_loss, l2_loss, hyp.flow_l2_coeff, summ_writer)\n\n total_loss = utils_misc.add_loss('flow/warp', total_loss, feat_diff, hyp.flow_warp_coeff, summ_writer)\n\n # smooth loss\n dx, dy, dz = utils_basic.gradient3D(flow_total, absolute=True)\n smooth_vox = torch.mean(dx+dy+dx, dim=1, keepdims=True)\n if summ_writer is not None:\n summ_writer.summ_oned('flow/smooth_loss', torch.mean(smooth_vox, dim=3))\n smooth_loss = torch.mean(smooth_vox)\n total_loss = utils_misc.add_loss('flow/smooth_loss', total_loss, smooth_loss, hyp.flow_smooth_coeff, summ_writer)\n \n return total_loss, flow_total\n\n" }, { "alpha_fraction": 0.5483754277229309, "alphanum_fraction": 0.5698555707931519, "avg_line_length": 36.14765167236328, "blob_id": "955fe8d1d03968ee0a29d0b5f54cac330cd6f244", "content_id": "726b3652f26d117959fa2e5ff8c161f45a1ce32f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5540, "license_type": "no_license", "max_line_length": 118, "num_lines": 149, "path": "/archs/bottle2D.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport time\n# import hyperparams as hyp\n# from utils_basic import *\nimport torch.nn.functional as F\n\nclass Bottle2D(nn.Module):\n def __init__(self, in_channel, pred_dim, chans=64):\n super(Bottle2D, self).__init__()\n conv2d = []\n\n # self.out_chans = [chans, 2*chans, 4*chans, 8*chans, 16*chans]\n # self.out_chans = [chans, 2*chans, 4*chans, 8*chans]\n self.out_chans = [chans, 2*chans, 4*chans]\n \n n_layers = len(self.out_chans)\n \n for i in list(range(n_layers)):\n if i==0:\n in_dim = in_channel\n else:\n in_dim = self.out_chans[i-1]\n out_dim = self.out_chans[i]\n conv2d.append(nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=0),\n nn.LeakyReLU(),\n nn.BatchNorm2d(num_features=out_dim),\n ))\n self.conv2d = nn.ModuleList(conv2d)\n\n hidden_dim = 1024\n self.linear_layers = nn.Sequential(\n nn.Linear(self.out_chans[-1]*2*2*2, hidden_dim),\n nn.LeakyReLU(),\n nn.Linear(hidden_dim, pred_dim),\n )\n \n def forward(self, feat):\n B, C, Z, X = list(feat.shape)\n # print(feat.shape)\n for conv2d_layer in self.conv2d:\n feat = conv2d_layer(feat)\n # print('bottle', feat.shape)\n feat = feat.reshape(B, -1)\n # print('bottle', feat.shape)\n # feat = self.linear_layers(feat)\n return feat\n\nclass ResNetBottle2D(nn.Module):\n def __init__(self, in_channel, pred_dim, chans=64):\n super(ResNetBottle2D, self).__init__()\n # first lqyer - downsampling\n in_dim, out_dim, ksize, stride, padding = in_channel, chans, 4, 2, 1\n self.down_sampler0 = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n )\n\n in_dim, out_dim, ksize, stride, padding = chans, chans, 3, 1, 1\n self.res_block1 = self.generate_block(in_dim, out_dim, ksize, stride, padding)\n self.res_block2 = self.generate_block(in_dim, out_dim, ksize, stride, padding)\n self.res_block3 = self.generate_block(in_dim, out_dim, ksize, stride, padding)\n self.res_block4 = self.generate_block(in_dim, out_dim, ksize, stride, padding)\n\n self.down_sampler1 = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n )\n self.down_sampler2 = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n )\n self.down_sampler3 = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n )\n self.down_sampler4 = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n )\n\n self.lrelu = nn.LeakyReLU()\n\n # # final 1x1x1 conv to get our desired pred_dim\n # self.final_feature = nn.Conv2d(in_channels=chans, out_channels=pred_dim, kernel_size=1, stride=1, padding=0)\n\n self.linear_layers = nn.Sequential(\n nn.Linear(out_dim*2*2*2, 512),\n nn.LeakyReLU(),\n nn.Linear(64, pred_dim),\n )\n\n def generate_block(self, in_dim, out_dim, ksize, stride, padding):\n block = nn.Sequential(\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=1, stride=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=out_dim),\n nn.LeakyReLU(),\n nn.Conv2d(in_channels=in_dim, out_channels=out_dim, kernel_size=1, stride=1),\n nn.BatchNorm2d(num_features=out_dim),\n )\n return block\n\n def forward(self, feat):\n B, C, Z, Y, X = list(feat.shape)\n feat = self.down_sampler0(feat)\n # print(feat.shape)\n\n feat_before = feat\n feat_after = self.res_block1(feat)\n feat = feat_before + feat_after\n feat = self.lrelu(feat)\n feat = self.down_sampler1(feat)\n # print(feat.shape)\n\n feat_before = feat\n feat_after = self.res_block2(feat)\n feat = feat_before + feat_after\n feat = self.lrelu(feat)\n feat = self.down_sampler2(feat)\n # print(feat.shape)\n\n feat_before = feat\n feat_after = self.res_block3(feat)\n feat = feat_before + feat_after\n feat = self.lrelu(feat)\n feat = self.down_sampler3(feat)\n # print(feat.shape)\n\n feat_before = feat\n feat_after = self.res_block4(feat)\n feat = feat_before + feat_after\n feat = self.lrelu(feat)\n feat = self.down_sampler4(feat)\n print(feat.shape)\n\n feat = feat.reshape(B, -1)\n feat = self.linear_layers(feat)\n # print(feat.shape)\n\n return feat\n \n" }, { "alpha_fraction": 0.501987636089325, "alphanum_fraction": 0.5200822353363037, "avg_line_length": 43.175758361816406, "blob_id": "4488e22f941d74799735b917b4115484d4a671cc", "content_id": "9648e0c379761eb1816fcb9cafb53663e4338477", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7295, "license_type": "no_license", "max_line_length": 142, "num_lines": 165, "path": "/nets/emb2dnet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport sys\nsys.path.append(\"..\")\n\nimport archs.encoder2d as encoder2d\nimport hyperparams as hyp\nimport utils.basic\nimport utils.misc\nimport utils.improc\n\nclass Emb2dNet(nn.Module):\n def __init__(self):\n super(Emb2dNet, self).__init__()\n\n print('Emb2dNet...')\n self.batch_k = 2\n self.num_samples = hyp.emb2d_num_samples\n assert(self.num_samples > 0)\n self.sampler = utils.misc.DistanceWeightedSampling(batch_k=self.batch_k, normalize=False)\n self.criterion = utils.misc.MarginLoss() #margin=args.margin,nu=args.nu)\n self.beta = 1.2\n\n self.dict_len = 20000\n self.neg_pool = utils.misc.SimplePool(self.dict_len, version='pt')\n self.ce = torch.nn.CrossEntropyLoss()\n \n def sample_embs(self, emb0, emb1, valid, B, Y, X, mod='', do_vis=False, summ_writer=None):\n if hyp.emb2d_mindist == 0.0:\n # pure random\n perm = torch.randperm(B*Y*X)\n emb0 = emb0.reshape(B*Y*X, -1)\n emb1 = emb1.reshape(B*Y*X, -1)\n valid = valid.reshape(B*Y*X, -1)\n emb0 = emb0[perm[:self.num_samples*B]]\n emb1 = emb1[perm[:self.num_samples*B]]\n valid = valid[perm[:self.num_samples*B]]\n return emb0, emb1, valid\n else:\n emb0_all = []\n emb1_all = []\n valid_all = []\n for b in list(range(B)):\n sample_indices, sample_locs, sample_valids = utils.misc.get_safe_samples(\n valid[b], (Y, X), self.num_samples, mode='2d', tol=hyp.emb2d_mindist)\n emb0_s_ = emb0[b, sample_indices]\n emb1_s_ = emb1[b, sample_indices]\n # these are N x D\n emb0_all.append(emb0_s_)\n emb1_all.append(emb1_s_)\n valid_all.append(sample_valids)\n\n if do_vis and (summ_writer is not None):\n sample_mask = utils.improc.xy2mask_single(sample_locs, Y, X)\n summ_writer.summ_oned('emb2d/samples_%s/sample_mask' % mod, torch.unsqueeze(sample_mask, dim=0))\n summ_writer.summ_oned('emb2d/samples_%s/valid' % mod, torch.reshape(valid, [B, 1, Y, X]))\n emb0_all = torch.cat(emb0_all, axis=0)\n emb1_all = torch.cat(emb1_all, axis=0)\n valid_all = torch.cat(valid_all, axis=0)\n return emb0_all, emb1_all, valid_all\n\n def compute_margin_loss(self, B, C, Y, X, emb0_vec, emb1_vec, valid_vec, mod='', do_vis=False, summ_writer=None):\n emb0_vec, emb1_vec, valid_vec = self.sample_embs(\n emb0_vec,\n emb1_vec,\n valid_vec,\n B, Y, X,\n mod=mod,\n do_vis=do_vis,\n summ_writer=summ_writer)\n \n emb_vec = torch.stack((emb0_vec, emb1_vec), dim=1).view(B*self.num_samples*self.batch_k,C)\n # this tensor goes e,g,e,g,... on dim 0\n # note this means 2 samples per class; batch_k=2\n y = torch.stack([torch.arange(0,self.num_samples*B), torch.arange(0,self.num_samples*B)], dim=1).view(self.num_samples*B*self.batch_k)\n # this tensor goes 0,0,1,1,2,2,...\n\n a_indices, anchors, positives, negatives, _ = self.sampler(emb_vec)\n margin_loss, _ = self.criterion(anchors, positives, negatives, self.beta, y[a_indices])\n return margin_loss\n\n def compute_ce_loss(self, B, C, Y, X, emb_e_vec_all, emb_g_vec_all, valid_vec_all, mod='', do_vis=False, summ_writer=None):\n emb_e_vec, emb_g_vec, valid_vec = self.sample_embs(emb_e_vec_all,\n emb_g_vec_all,\n valid_vec_all,\n B, Y, X,\n mod=mod,\n do_vis=do_vis,\n summ_writer=summ_writer)\n _, emb_n_vec, _ = self.sample_embs(emb_e_vec_all,\n emb_g_vec_all,\n valid_vec_all,\n B, Y, X,\n mod=mod,\n do_vis=do_vis,\n summ_writer=summ_writer)\n emb_e_vec = emb_e_vec.view(B*self.num_samples, C)\n emb_g_vec = emb_g_vec.view(B*self.num_samples, C)\n emb_n_vec = emb_n_vec.view(B*self.num_samples, C)\n \n self.neg_pool.update(emb_n_vec.cpu())\n # print('neg_pool len:', len(self.neg_pool))\n emb_n = self.neg_pool.fetch().cuda()\n\n # print('emb_n', emb_n.shape)\n N2, C2 = list(emb_n.shape)\n assert (C2 == C)\n \n # l_negs = torch.mm(q.view(N, C), negs.view(C, N2)) # this is N x N2\n\n emb_q = emb_e_vec.clone()\n emb_k = emb_g_vec.clone()\n \n # print('emb_q', emb_q.shape)\n # print('emb_k', emb_k.shape)\n N = emb_q.shape[0]\n l_pos = torch.bmm(emb_q.view(N,1,-1), emb_k.view(N,-1,1))\n\n # print('l_pos', l_pos.shape)\n l_neg = torch.mm(emb_q, emb_n.T)\n # print('l_neg', l_neg.shape)\n \n l_pos = l_pos.view(N, 1)\n # print('l_pos', l_pos.shape)\n logits = torch.cat([l_pos, l_neg], dim=1)\n\n labels = torch.zeros(N, dtype=torch.long).cuda()\n\n temp = 0.07\n emb_loss = self.ce(logits/temp, labels)\n # print('emb_loss', emb_loss.detach().cpu().numpy())\n return emb_loss\n \n def forward(self, emb_e, emb_g, valid, summ_writer=None, suffix=''):\n total_loss = torch.tensor(0.0).cuda()\n\n if torch.isnan(emb_e).any() or torch.isnan(emb_g).any():\n assert(False)\n\n B, C, H, W = list(emb_e.shape)\n # put channels on the end\n emb_e_vec = emb_e.permute(0,2,3,1).reshape(B, H*W, C)\n emb_g_vec = emb_g.permute(0,2,3,1).reshape(B, H*W, C)\n valid_vec = valid.permute(0,2,3,1).reshape(B, H*W, 1)\n \n assert(self.num_samples < (B*H*W))\n # we will take num_samples from each one\n\n margin_loss = self.compute_margin_loss(B, C, H, W, emb_e_vec, emb_g_vec, valid_vec, 'all', True, summ_writer)\n total_loss = utils.misc.add_loss('emb2d/emb2d_ml_loss%s' % suffix, total_loss, margin_loss, hyp.emb2d_ml_coeff, summ_writer)\n\n ce_loss = self.compute_ce_loss(B, C, H, W, emb_e_vec, emb_g_vec.detach(), valid_vec, 'g', False, summ_writer)\n total_loss = utils.misc.add_loss('emb2d/emb_ce_loss', total_loss, ce_loss, hyp.emb2d_ce_coeff, summ_writer)\n \n l2_loss_im = utils.basic.sql2_on_axis(emb_e-emb_g.detach(), 1, keepdim=True)\n emb_l2_loss = utils.basic.reduce_masked_mean(l2_loss_im, valid)\n total_loss = utils.misc.add_loss('emb2d/emb2d_l2_loss%s' % suffix, total_loss, emb_l2_loss, hyp.emb2d_l2_coeff, summ_writer)\n\n if summ_writer is not None:\n summ_writer.summ_oned('emb2d/emb2d_l2_loss%s' % suffix, l2_loss_im)\n summ_writer.summ_feats('emb2d/embs_2d%s' % suffix, [emb_e, emb_g], pca=True)\n\n return total_loss, emb_g\n\n \n" }, { "alpha_fraction": 0.4902903735637665, "alphanum_fraction": 0.516460120677948, "avg_line_length": 40.11787033081055, "blob_id": "0c818a2673638ee5b8cc41d19a413bfe644998f2", "content_id": "833fb992bcced25f9ba580750e26a64e42c8a472", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10814, "license_type": "no_license", "max_line_length": 132, "num_lines": 263, "path": "/nets/egonet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import numpy as np\nimport hyperparams as hyp\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.ops as ops\n\nimport utils.basic\nimport utils.improc\nimport utils.geom\nimport utils.misc\nimport utils.samp\n\nEPS = 1e-6\n\n# acknowledgement:\n# Niles Christensen and Sohil Samir Savla developed the pytorch port of the original egonet.py, written in tensorflow\n\ndef eval_against_gt(loss, cam0_T_cam1_e, cam0_T_cam1_g,\n t_coeff=0.0, deg_coeff=0.0, sc=1.0,\n summ_writer=None):\n # cam0_T_cam1_e is B x 4 x 4\n # cam0_T_cam1_g is B x 4 x 4\n r_e, t_e = utils.geom.split_rt(cam0_T_cam1_e)\n r_g, t_g = utils.geom.split_rt(cam0_T_cam1_g)\n _, ry_e, _ = utils.geom.rotm2eul(r_e)\n _, ry_g, _ = utils.geom.rotm2eul(r_g)\n deg_e = torch.unsqueeze(utils.geom.rad2deg(ry_e), axis=-1)\n deg_g = torch.unsqueeze(utils.geom.rad2deg(ry_g), axis=-1)\n\n t_l2 = torch.mean(utils.basic.sql2_on_axis(t_e-t_g, 1))\n loss = utils.misc.add_loss('t_sql2_%.2f' % sc,\n loss,\n t_l2,\n t_coeff,\n summ_writer=summ_writer)\n\n deg_l2 = torch.mean(utils.basic.sql2_on_axis(deg_e-deg_g, 1))\n loss = utils.misc.add_loss('deg_sql2_%.2f' % sc,\n loss,\n deg_l2,\n deg_coeff,\n summ_writer=summ_writer)\n\n return loss\n\ndef cost_volume_3D(vox0, vox1,\n max_disp_z=4,\n max_disp_y=1,\n max_disp_x=4):\n # max_disp = max_displacement\n # vox0 is B x C x Z x Y x X \n # vox1 is B x C x Z x Y x X \n # return cost_vol, shaped B x E x Z x Y x X\n # E_i = max_disp_i*2 + 1\n # E = \\prod E_i\n\n # pad the top, bottom, left, and right of vox1\n ones = torch.ones_like(vox1)\n vox1_pad = F.pad(vox1,\n (max_disp_z, max_disp_z,\n max_disp_y, max_disp_y,\n max_disp_x, max_disp_x),\n 'constant', 0)\n \n ones_pad = F.pad(ones,\n (max_disp_z, max_disp_z,\n max_disp_y, max_disp_y,\n max_disp_x, max_disp_x),\n 'constant', 0)\n\n _, _, d, h, w = vox0.shape\n loop_range1 = max_disp_z * 2 + 1\n loop_range2 = max_disp_y * 2 + 1\n loop_range3 = max_disp_x * 2 + 1\n cost_vol = []\n for z in range(0, loop_range1):\n for y in range(0, loop_range2):\n for x in range(0, loop_range3):\n vox1_slice = vox1_pad[:, :, z:z+d, y:y+h, x:x+w]\n ones_slice = ones_pad[:, :, z:z+d, y:y+h, x:x+w]\n cost = utils.basic.reduce_masked_mean(vox0*vox1_slice, ones_slice, dim=1, keepdim=True)\n cost_vol.append(cost)\n cost_vol = torch.cat(cost_vol, axis=1)\n return cost_vol\n\nclass EgoNet(nn.Module):\n def __init__(self,\n num_scales=1,\n num_rots=3,\n max_deg=4,\n max_disp_z=1,\n max_disp_y=1,\n max_disp_x=1):\n print('EgoNet...')\n super(EgoNet, self).__init__()\n if num_scales:\n self.scales = [1]\n elif num_scales==2:\n self.scales = [0.5, 1]\n else:\n assert(False) # only 1-2 scales supported right now\n self.R = num_rots\n self.max_deg = max_deg # max degrees rotation, on either side of zero\n self.max_disp_z = max_disp_z\n self.max_disp_y = max_disp_y\n self.max_disp_x = max_disp_x\n \n self.E1 = self.max_disp_z*2 + 1\n self.E2 = self.max_disp_y*2 + 1\n self.E3 = self.max_disp_x*2 + 1\n self.E = self.E1*self.E2*self.E3\n\n self.first_layer = nn.Linear(self.R*self.E, 128).cuda()\n self.second_layer = nn.Linear(128, 128).cuda()\n self.third_layer = nn.Linear(128, 4).cuda()\n\n def forward(self, feat0, feat1, cam0_T_cam1_g, vox_util, summ_writer, reuse=False):\n total_loss = 0.0\n\n utils.basic.assert_same_shape(feat0, feat1)\n\n summ_writer.summ_feats('ego/feats', [feat0, feat1], pca=True)\n\n total_loss, cam0_T_cam1_e, feat1_warped = self.multi_scale_corr3Dr(\n total_loss, feat0, feat1, vox_util, summ_writer, cam0_T_cam1_g, reuse=reuse)\n\n return total_loss, cam0_T_cam1_e, feat1_warped\n\n def multi_scale_corr3Dr(self, total_loss, feat0, feat1, vox_util, summ_writer, cam0_T_cam1_g=None, reuse=False, do_print=False):\n # the idea here is:\n # at each scale, find the answer, and then warp\n # to make the next scale closer to the answer\n # this allows a small displacement to be effective at each scale\n\n alignments = []\n\n B, C, Z, Y, X = list(feat0.size())\n utils.basic.assert_same_shape(feat0, feat1)\n\n summ_writer.summ_feat('ego/feat0', feat0, pca=True)\n summ_writer.summ_feat('ego/feat1', feat1, pca=True)\n\n if (cam0_T_cam1_g is not None):\n eye = utils.geom.eye_4x4(B)\n _ = eval_against_gt(0, eye, cam0_T_cam1_g, sc=0.0, summ_writer=summ_writer)\n\n feat1_backup = feat1.clone()\n\n rots = torch.linspace(-self.max_deg, self.max_deg, self.R)\n rots = torch.reshape(rots, [self.R])\n\n rot_cam_total = torch.zeros([B])\n delta_cam_total = torch.zeros([B, 3])\n\n for sc in self.scales:\n Z_ = int(Z*sc)\n Y_ = int(Y*sc)\n X_ = int(X*sc)\n\n if not sc==1.0:\n feat0_ = F.interpolate(feat0, scale_factor=sc, mode='trilinear')\n feat1_ = F.interpolate(feat1, scale_factor=sc, mode='trilinear')\n else:\n feat0_ = feat0.clone()\n feat1_ = feat1.clone()\n\n # have a heatmap at least sized 3, so that an argmax is capable of returning 0\n valid_Z = Z_-self.max_disp_z*2\n valid_Y = Y_-self.max_disp_y*2\n valid_X = X_-self.max_disp_x*2\n assert(valid_Z >= 3)\n assert(valid_Y >= 3)\n assert(valid_X >= 3)\n\n summ_writer.summ_feat('ego/feat0_resized_%.3f' % sc, feat0_, pca=True)\n summ_writer.summ_feat('ego/feat1_resized_%.3f' % sc, feat1_, pca=True)\n\n ## now we want to rotate the features into all of the orientations\n # first we define the orientations\n r0 = torch.zeros([B*self.R])\n ry = torch.unsqueeze(rots, axis=0).repeat([B, 1]).reshape([B*self.R])\n r = utils.geom.eul2rotm(r0, utils.geom.deg2rad(ry), r0)\n t = torch.zeros([B*self.R, 3])\n # this will carry us from \"1\" coords to \"N\" (new) coords\n camN_T_cam1 = utils.geom.merge_rt(r, t)\n # this is B*R x 4 x 4\n # we want to apply this to feat1\n # we first need the feats to lead with B*R\n feat0_ = torch.unsqueeze(feat0_, axis=1).repeat([1, self.R, 1, 1, 1, 1])\n feat1_ = torch.unsqueeze(feat1_, axis=1).repeat([1, self.R, 1, 1, 1, 1])\n feat0_ = feat0_.reshape([B*self.R, C, Z_, Y_, X_])\n feat1_ = feat1_.reshape([B*self.R, C, Z_, Y_, X_])\n\n featN_ = vox_util.apply_4x4_to_vox(camN_T_cam1, feat1_)\n\n featN__ = featN_.reshape([B, self.R, C, Z_, Y_, X_])\n summ_writer.summ_feats('ego/featN_%.3f_postwarp' % sc, torch.unbind(featN__, axis=1), pca=False)\n\n cc = cost_volume_3D(feat0_,\n featN_,\n max_disp_z=self.max_disp_z,\n max_disp_y=self.max_disp_y,\n max_disp_x=self.max_disp_x)\n\n # cc is B*R x Z_ x Y_ x X_ x E,\n # i.e., each spatial location has a heatmap squished into the E dim\n\n # reduce along the spatial dims\n heat = torch.sum(cc, axis=[2,3,4])\n # flesh out the heatmaps\n heat = heat.reshape([B, self.R, 1, self.E1, self.E2, self.E3])\n # have a look\n summ_writer.summ_oned('ego/heat_%.3f' % sc, torch.mean(heat[0], axis=-2, keepdim=False))\n\n feat = heat.reshape([B, self.R*self.E])\n feat = F.leaky_relu(feat, negative_slope=0.1)\n # relja said normalizing helps:\n feat_norm = utils.basic.l2_on_axis(feat, 1, keepdim=True)\n feat = feat/(EPS+feat_norm)\n feat = self.first_layer(feat)\n feat = F.leaky_relu(feat, negative_slope=0.1)\n feat = self.second_layer(feat)\n feat = F.leaky_relu(feat, negative_slope=0.1)\n feat = self.third_layer(feat)\n r, y, x, z = torch.unbind(feat, axis=1)\n\n # convert the mem argmax into a translation in cam coords\n xyz_argmax_mem = torch.unsqueeze(torch.stack([x, y, z], axis=1), axis=1)\n xyz_zero_mem = torch.zeros([B, 1, 3])\n # in the transformation, use Y*sc instead of Y_, in case we cropped instead of scaled\n xyz_argmax_cam = vox_util.Mem2Ref(xyz_argmax_mem.cuda(), int(Z*sc), int(Y*sc), int(X*sc))\n xyz_zero_cam = vox_util.Mem2Ref(xyz_zero_mem.cuda(), int(Z*sc), int(Y*sc), int(X*sc))\n xyz_delta_cam = xyz_argmax_cam-xyz_zero_cam\n\n # mem is aligned with cam, and scaling does not affect rotation\n rot_cam = r.clone()\n\n summ_writer.summ_histogram('xyz_delta_cam', xyz_delta_cam)\n summ_writer.summ_histogram('rot_cam', rot_cam)\n\n delta_cam_total += xyz_delta_cam.reshape([B, 3]).cpu()\n rot_cam_total += rot_cam.cpu()\n\n r0 = torch.zeros([B])\n cam0_T_cam1_e = utils.geom.merge_rt(utils.geom.eul2rotm(r0,\n utils.geom.deg2rad(rot_cam_total),\n r0),\n -delta_cam_total)\n # bring feat1_backup into alignment with feat0, using the cumulative RT\n # if the estimate were perfect, this would yield feat0, but let's continue to call it feat1\n feat1 = vox_util.apply_4x4_to_vox(cam0_T_cam1_e, feat1_backup)\n # we will use feat1 in the next iteration of the loop\n\n if (cam0_T_cam1_g is not None):\n total_loss = eval_against_gt(total_loss, cam0_T_cam1_e, cam0_T_cam1_g,\n t_coeff=hyp.ego_t_l2_coeff*sc,\n deg_coeff=hyp.ego_deg_l2_coeff*sc,\n sc=sc,\n summ_writer=summ_writer)\n\n return total_loss, cam0_T_cam1_e, feat1\n" }, { "alpha_fraction": 0.5304718017578125, "alphanum_fraction": 0.556684136390686, "avg_line_length": 34.488372802734375, "blob_id": "35e08ee0d0dce77822f824d4a68eec50043e6642", "content_id": "a066ec22ade759f96f8fdc717073e032025a6c9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3052, "license_type": "no_license", "max_line_length": 128, "num_lines": 86, "path": "/nets/viewnet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport sys\nsys.path.append(\"..\")\n\nimport archs.renderer\nimport hyperparams as hyp\nfrom utils.basic import *\nimport utils.improc\nimport utils.basic\nimport utils.misc\nimport utils.geom\n\nclass ViewNet(nn.Module):\n def __init__(self):\n super(ViewNet, self).__init__()\n\n print('ViewNet...')\n\n self.net = archs.renderer.Net3d2d(hyp.feat3d_dim, 64, 32, hyp.view_depth, depth_pool=8).cuda()\n\n self.rgb_layer = nn.Sequential(\n nn.LeakyReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(),\n nn.Conv2d(32, 3, kernel_size=1, stride=1, padding=0),\n ).cuda()\n self.emb_layer = nn.Sequential(\n nn.LeakyReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(),\n nn.Conv2d(32, hyp.feat2d_dim, kernel_size=1, stride=1, padding=0),\n ).cuda()\n print(self.net)\n\n def forward(self, pix_T_cam0, cam0_T_cam1, feat_mem1, rgb_g, vox_util, valid=None, summ_writer=None, test=False, suffix=''):\n total_loss = torch.tensor(0.0).cuda()\n\n B, C, H, W = list(rgb_g.shape)\n\n PH, PW = hyp.PH, hyp.PW\n if (PH < H) or (PW < W):\n # print('H, W', H, W)\n # print('PH, PW', PH, PW)\n sy = float(PH)/float(H)\n sx = float(PW)/float(W)\n pix_T_cam0 = utils.geom.scale_intrinsics(pix_T_cam0, sx, sy)\n\n if valid is not None:\n valid = F.interpolate(valid, scale_factor=0.5, mode='nearest')\n rgb_g = F.interpolate(rgb_g, scale_factor=0.5, mode='bilinear')\n \n feat_proj = vox_util.apply_pixX_T_memR_to_voxR(\n pix_T_cam0, cam0_T_cam1, feat_mem1,\n hyp.view_depth, PH, PW)\n\n feat = self.net(feat_proj)\n rgb = self.rgb_layer(feat)\n emb = self.emb_layer(feat)\n emb = utils.basic.l2_normalize(emb, dim=1)\n\n if test:\n return None, rgb, None\n \n loss_im = utils.basic.l1_on_axis(rgb-rgb_g, 1, keepdim=True)\n if valid is not None:\n rgb_loss = utils.basic.reduce_masked_mean(loss_im, valid)\n else:\n rgb_loss = torch.mean(loss_im)\n\n total_loss = utils.misc.add_loss('view/rgb_l1_loss', total_loss, rgb_loss, hyp.view_l1_coeff, summ_writer)\n \n # vis\n if summ_writer is not None:\n summ_writer.summ_oned('view/rgb_loss', loss_im)\n summ_writer.summ_rgbs('view/rgb', [rgb.clamp(-0.5, 0.5), rgb_g])\n summ_writer.summ_rgb('view/rgb_e', rgb.clamp(-0.5, 0.5))\n summ_writer.summ_rgb('view/rgb_g', rgb_g.clamp(-0.5, 0.5))\n summ_writer.summ_feat('view/emb', emb, pca=True)\n if valid is not None:\n summ_writer.summ_rgb('view/rgb_e_valid', valid*rgb.clamp(-0.5, 0.5))\n summ_writer.summ_rgb('view/rgb_g_valid', valid*rgb_g.clamp(-0.5, 0.5))\n\n return total_loss, rgb, emb\n" }, { "alpha_fraction": 0.48909929394721985, "alphanum_fraction": 0.5412953495979309, "avg_line_length": 32.87601089477539, "blob_id": "b1797bb5b6fb518e2fd3d298c0ea0587ed5baf49", "content_id": "93e4407623b0ad4d168f1d771e5bbb60c84f46d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12568, "license_type": "no_license", "max_line_length": 84, "num_lines": 371, "path": "/exp_base.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import pretrained_nets_carla as pret_carla\n\nexps = {}\ngroups = {}\n############## training settings ##############\n\ngroups['train_feat3d'] = [\n 'do_feat3d = True',\n 'feat3d_dim = 32',\n # 'feat3d_smooth_coeff = 0.01',\n]\ngroups['train_det'] = [\n 'do_det = True',\n 'det_prob_coeff = 1.0',\n 'det_reg_coeff = 1.0',\n]\n\n############## dataset settings ##############\n\nH = 128\nW = 384\n\ngroups['seqlen1'] = [\n 'trainset_seqlen = 1',\n 'valset_seqlen = 1',\n]\n\ngroups['8-4-8_bounds'] = [\n 'XMIN = -8.0', # right (neg is left)\n 'XMAX = 8.0', # right\n 'YMIN = -4.0', # down (neg is up)\n 'YMAX = 4.0', # down\n 'ZMIN = -8.0', # forward (neg is backward)\n 'ZMAX = 8.0', # forward \n]\ngroups['16-4-16_bounds'] = [\n 'XMIN = -16.0', # right (neg is left)\n 'XMAX = 16.0', # right\n 'YMIN = -4.0', # down (neg is up)\n 'YMAX = 4.0', # down\n 'ZMIN = -16.0', # forward (neg is backward)\n 'ZMAX = 16.0', # forward \n]\ngroups['16-8-16_bounds'] = [\n 'XMIN = -16.0', # right (neg is left)\n 'XMAX = 16.0', # right\n 'YMIN = -8.0', # down (neg is up)\n 'YMAX = 8.0', # down\n 'ZMIN = -16.0', # forward (neg is backward)\n 'ZMAX = 16.0', # forward \n]\n\ndataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"\n\ngroups['carla_multiview_10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mags7i3ten\"',\n 'trainset_format = \"multiview\"', \n # 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mags7i3t\"',\n 'trainset_format = \"multiview\"', \n # 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_test_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'testset = \"mags7i3v\"',\n 'testset_format = \"multiview\"', \n # 'testset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_val_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mags7i3t\"',\n 'trainset_format = \"multiview\"', \n # 'trainset_seqlen = %d' % S, \n 'valset = \"mags7i3v\"',\n 'valset_format = \"multiview\"', \n # 'valset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\n\n\n############## other settings ##############\n\ngroups['include_summs'] = [\n 'do_include_summs = True',\n]\ngroups['decay_lr'] = ['do_decay_lr = True']\ngroups['clip_grad'] = ['do_clip_grad = True']\n# groups['quick_snap'] = ['snap_freq = 500']\n# groups['quicker_snap'] = ['snap_freq = 50']\n# groups['quickest_snap'] = ['snap_freq = 5']\ngroups['snap500'] = ['snap_freq = 500']\ngroups['snap1k'] = ['snap_freq = 1000']\ngroups['snap5k'] = ['snap_freq = 5000']\n\ngroups['no_shuf'] = ['shuffle_train = False',\n 'shuffle_val = False',\n 'shuffle_test = False',\n]\ngroups['time_flip'] = ['do_time_flip = True']\ngroups['no_backprop'] = ['backprop_on_train = False',\n 'backprop_on_val = False',\n 'backprop_on_test = False',\n]\ngroups['train_on_trainval'] = ['backprop_on_train = True',\n 'backprop_on_val = True',\n 'backprop_on_test = False',\n]\ngroups['B1'] = ['trainset_batch_size = 1']\ngroups['B2'] = ['trainset_batch_size = 2']\ngroups['B4'] = ['trainset_batch_size = 4']\ngroups['B6'] = ['trainset_batch_size = 6']\ngroups['B8'] = ['trainset_batch_size = 8']\ngroups['B10'] = ['trainset_batch_size = 10']\ngroups['B12'] = ['trainset_batch_size = 12']\ngroups['B16'] = ['trainset_batch_size = 16']\ngroups['B24'] = ['trainset_batch_size = 24']\ngroups['B32'] = ['trainset_batch_size = 32']\ngroups['B64'] = ['trainset_batch_size = 64']\ngroups['B128'] = ['trainset_batch_size = 128']\ngroups['vB1'] = ['valset_batch_size = 1']\ngroups['vB2'] = ['valset_batch_size = 2']\ngroups['vB4'] = ['valset_batch_size = 4']\ngroups['vB8'] = ['valset_batch_size = 8']\ngroups['lr0'] = ['lr = 0.0']\ngroups['lr1'] = ['lr = 1e-1']\ngroups['lr2'] = ['lr = 1e-2']\ngroups['lr3'] = ['lr = 1e-3']\ngroups['2lr4'] = ['lr = 2e-4']\ngroups['5lr4'] = ['lr = 5e-4']\ngroups['lr4'] = ['lr = 1e-4']\ngroups['lr5'] = ['lr = 1e-5']\ngroups['lr6'] = ['lr = 1e-6']\ngroups['lr7'] = ['lr = 1e-7']\ngroups['lr8'] = ['lr = 1e-8']\ngroups['lr9'] = ['lr = 1e-9']\ngroups['lr12'] = ['lr = 1e-12']\ngroups['1_iters'] = ['max_iters = 1']\ngroups['2_iters'] = ['max_iters = 2']\ngroups['3_iters'] = ['max_iters = 3']\ngroups['5_iters'] = ['max_iters = 5']\ngroups['6_iters'] = ['max_iters = 6']\ngroups['9_iters'] = ['max_iters = 9']\ngroups['21_iters'] = ['max_iters = 21']\ngroups['7_iters'] = ['max_iters = 7']\ngroups['10_iters'] = ['max_iters = 10']\ngroups['15_iters'] = ['max_iters = 15']\ngroups['20_iters'] = ['max_iters = 20']\ngroups['25_iters'] = ['max_iters = 25']\ngroups['30_iters'] = ['max_iters = 30']\ngroups['50_iters'] = ['max_iters = 50']\ngroups['100_iters'] = ['max_iters = 100']\ngroups['150_iters'] = ['max_iters = 150']\ngroups['200_iters'] = ['max_iters = 200']\ngroups['250_iters'] = ['max_iters = 250']\ngroups['300_iters'] = ['max_iters = 300']\ngroups['397_iters'] = ['max_iters = 397']\ngroups['400_iters'] = ['max_iters = 400']\ngroups['447_iters'] = ['max_iters = 447']\ngroups['500_iters'] = ['max_iters = 500']\ngroups['850_iters'] = ['max_iters = 850']\ngroups['1000_iters'] = ['max_iters = 1000']\ngroups['2000_iters'] = ['max_iters = 2000']\ngroups['2445_iters'] = ['max_iters = 2445']\ngroups['3000_iters'] = ['max_iters = 3000']\ngroups['4000_iters'] = ['max_iters = 4000']\ngroups['4433_iters'] = ['max_iters = 4433']\ngroups['5000_iters'] = ['max_iters = 5000']\ngroups['10000_iters'] = ['max_iters = 10000']\ngroups['1k_iters'] = ['max_iters = 1000']\ngroups['2k_iters'] = ['max_iters = 2000']\ngroups['5k_iters'] = ['max_iters = 5000']\ngroups['10k_iters'] = ['max_iters = 10000']\ngroups['20k_iters'] = ['max_iters = 20000']\ngroups['30k_iters'] = ['max_iters = 30000']\ngroups['40k_iters'] = ['max_iters = 40000']\ngroups['50k_iters'] = ['max_iters = 50000']\ngroups['60k_iters'] = ['max_iters = 60000']\ngroups['80k_iters'] = ['max_iters = 80000']\ngroups['100k_iters'] = ['max_iters = 100000']\ngroups['100k10_iters'] = ['max_iters = 100010']\ngroups['200k_iters'] = ['max_iters = 200000']\ngroups['300k_iters'] = ['max_iters = 300000']\ngroups['400k_iters'] = ['max_iters = 400000']\ngroups['500k_iters'] = ['max_iters = 500000']\n\ngroups['resume'] = ['do_resume = True']\ngroups['reset_iter'] = ['reset_iter = True']\n\ngroups['log1'] = [\n 'log_freq_train = 1',\n 'log_freq_val = 1',\n 'log_freq_test = 1',\n]\ngroups['log5'] = [\n 'log_freq_train = 5',\n 'log_freq_val = 5',\n 'log_freq_test = 5',\n]\ngroups['log10'] = [\n 'log_freq_train = 10',\n 'log_freq_val = 10',\n 'log_freq_test = 10',\n]\ngroups['log50'] = [\n 'log_freq_train = 50',\n 'log_freq_val = 50',\n 'log_freq_test = 50',\n]\ngroups['log500'] = [\n 'log_freq_train = 500',\n 'log_freq_val = 500',\n 'log_freq_test = 500',\n]\ngroups['log5000'] = [\n 'log_freq_train = 5000',\n 'log_freq_val = 5000',\n 'log_freq_test = 5000',\n]\n\n\n\ngroups['no_logging'] = [\n 'log_freq_train = 100000000000',\n 'log_freq_val = 100000000000',\n 'log_freq_test = 100000000000',\n]\n\n# ############## pretrained nets ##############\n\n# groups['pretrained_sigen3d'] = [\n# 'do_sigen3d = True',\n# 'sigen3d_init = \"' + pret_carla.sigen3d_init + '\"',\n# ]\n# groups['pretrained_conf'] = [\n# 'do_conf = True',\n# 'conf_init = \"' + pret_carla.conf_init + '\"',\n# ]\n# groups['pretrained_up3D'] = [\n# 'do_up3D = True',\n# 'up3D_init = \"' + pret_carla.up3D_init + '\"',\n# ]\n# groups['pretrained_center'] = [\n# 'do_center = True',\n# 'center_init = \"' + pret_carla.center_init + '\"',\n# ]\n# groups['pretrained_seg'] = [\n# 'do_seg = True',\n# 'seg_init = \"' + pret_carla.seg_init + '\"',\n# ]\n# groups['pretrained_motionreg'] = [\n# 'do_motionreg = True',\n# 'motionreg_init = \"' + pret_carla.motionreg_init + '\"',\n# ]\n# groups['pretrained_gen3d'] = [\n# 'do_gen3d = True',\n# 'gen3d_init = \"' + pret_carla.gen3d_init + '\"',\n# ]\n# groups['pretrained_vq2d'] = [\n# 'do_vq2d = True',\n# 'vq2d_init = \"' + pret_carla.vq2d_init + '\"',\n# 'vq2d_num_embeddings = %d' % pret_carla.vq2d_num_embeddings,\n# ]\n# groups['pretrained_vq3d'] = [\n# 'do_vq3d = True',\n# 'vq3d_init = \"' + pret_carla.vq3d_init + '\"',\n# 'vq3d_num_embeddings = %d' % pret_carla.vq3d_num_embeddings,\n# ]\n# groups['pretrained_feat2D'] = [\n# 'do_feat2D = True',\n# 'feat2D_init = \"' + pret_carla.feat2D_init + '\"',\n# 'feat2D_dim = %d' % pret_carla.feat2D_dim,\n# ]\ngroups['pretrained_feat3d'] = [\n 'do_feat3d = True',\n 'feat3d_init = \"' + pret_carla.feat3d_init + '\"',\n 'feat3d_dim = %d' % pret_carla.feat3d_dim,\n]\ngroups['pretrained_occ'] = [\n 'do_occ = True',\n 'occ_init = \"' + pret_carla.occ_init + '\"',\n]\n# groups['pretrained_match'] = [\n# 'do_match = True',\n# 'match_init = \"' + pret_carla.match_init + '\"',\n# ]\n# groups['pretrained_rigid'] = [\n# 'do_rigid = True',\n# 'rigid_init = \"' + pret_carla.rigid_init + '\"',\n# ]\n# # groups['pretrained_pri2D'] = [\n# # 'do_pri2D = True',\n# # 'pri2D_init = \"' + pret_carla.pri2D_init + '\"',\n# # ]\n# groups['pretrained_det'] = [\n# 'do_det = True',\n# 'det_init = \"' + pret_carla.det_init + '\"',\n# ]\n# groups['pretrained_forecast'] = [\n# 'do_forecast = True',\n# 'forecast_init = \"' + pret_carla.forecast_init + '\"',\n# ]\n# groups['pretrained_view'] = [\n# 'do_view = True',\n# 'view_init = \"' + pret_carla.view_init + '\"',\n# 'view_depth = %d' % pret_carla.view_depth,\n# 'feat2D_dim = %d' % pret_carla.feat2D_dim,\n# # 'view_use_halftanh = ' + str(pret_carla.view_use_halftanh),\n# # 'view_pred_embs = ' + str(pret_carla.view_pred_embs),\n# # 'view_pred_rgb = ' + str(pret_carla.view_pred_rgb),\n# ]\n# groups['pretrained_flow'] = ['do_flow = True',\n# 'flow_init = \"' + pret_carla.flow_init + '\"',\n# ]\n# # groups['pretrained_tow'] = ['do_tow = True',\n# # 'tow_init = \"' + pret_carla.tow_init + '\"',\n# # ]\n# groups['pretrained_emb2D'] = ['do_emb2D = True',\n# 'emb2D_init = \"' + pret_carla.emb2D_init + '\"',\n# # 'emb_dim = %d' % pret_carla.emb_dim,\n# ]\n# groups['pretrained_preocc'] = [\n# 'do_preocc = True',\n# 'preocc_init = \"' + pret_carla.preocc_init + '\"',\n# ]\n# groups['pretrained_vis'] = ['do_vis = True',\n# 'vis_init = \"' + pret_carla.vis_init + '\"',\n# # 'occ_cheap = ' + str(pret_carla.occ_cheap),\n# ]\n# groups['total_init'] = ['total_init = \"' + pret_carla.total_init + '\"']\n# groups['pretrained_optim'] = ['optim_init = \"' + pret_carla.optim_init + '\"']\n\n# groups['frozen_conf'] = ['do_freeze_conf = True', 'do_conf = True']\n# groups['frozen_motionreg'] = ['do_freeze_motionreg = True', 'do_motionreg = True']\n# groups['frozen_feat2D'] = ['do_freeze_feat2D = True', 'do_feat2D = True']\n# groups['frozen_feat3D'] = ['do_freeze_feat3D = True', 'do_feat3D = True']\n# groups['frozen_up3D'] = ['do_freeze_up3D = True', 'do_up3D = True']\n# groups['frozen_vq3d'] = ['do_freeze_vq3d = True', 'do_vq3d = True']\n# groups['frozen_view'] = ['do_freeze_view = True', 'do_view = True']\n# groups['frozen_center'] = ['do_freeze_center = True', 'do_center = True']\n# groups['frozen_seg'] = ['do_freeze_seg = True', 'do_seg = True']\n# groups['frozen_vis'] = ['do_freeze_vis = True', 'do_vis = True']\n# groups['frozen_flow'] = ['do_freeze_flow = True', 'do_flow = True']\n# groups['frozen_match'] = ['do_freeze_match = True', 'do_match = True']\n# groups['frozen_emb2D'] = ['do_freeze_emb2D = True', 'do_emb2D = True']\n# groups['frozen_pri2D'] = ['do_freeze_pri2D = True', 'do_pri2D = True']\n# groups['frozen_occ'] = ['do_freeze_occ = True', 'do_occ = True']\n# groups['frozen_vq2d'] = ['do_freeze_vq2d = True', 'do_vq2d = True']\n# groups['frozen_vq3d'] = ['do_freeze_vq3d = True', 'do_vq3d = True']\n# groups['frozen_sigen3d'] = ['do_freeze_sigen3d = True', 'do_sigen3d = True']\n# groups['frozen_gen3d'] = ['do_freeze_gen3d = True', 'do_gen3d = True']\n# # groups['frozen_ego'] = ['do_freeze_ego = True', 'do_ego = True']\n# # groups['frozen_inp'] = ['do_freeze_inp = True', 'do_inp = True']\n" }, { "alpha_fraction": 0.5763656497001648, "alphanum_fraction": 0.5975473523139954, "avg_line_length": 29.89655113220215, "blob_id": "3546a9bde224720148420708d8e0e4090c2e727a", "content_id": "feeea2f95c213471120d4a45a66e3cf01bd17e06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 897, "license_type": "no_license", "max_line_length": 129, "num_lines": 29, "path": "/archs/pixelshuffle3d.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "\n'''\nreference: http://www.multisilicon.com/blog/a25332339.html\n'''\nimport torch.nn as nn\n\nclass PixelShuffle3d(nn.Module):\n '''\n This class is a 3d version of pixelshuffle.\n '''\n def __init__(self, scale):\n '''\n :param scale: upsample scale\n '''\n super().__init__()\n self.scale = scale\n\n def forward(self, input):\n batch_size, channels, in_depth, in_height, in_width = input.size()\n nOut = channels // self.scale ** 3\n\n out_depth = in_depth * self.scale\n out_height = in_height * self.scale\n out_width = in_width * self.scale\n\n input_view = input.contiguous().view(batch_size, nOut, self.scale, self.scale, self.scale, in_depth, in_height, in_width)\n\n output = input_view.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()\n\n return output.view(batch_size, nOut, out_depth, out_height, out_width)\n" }, { "alpha_fraction": 0.49092531204223633, "alphanum_fraction": 0.5105623602867126, "avg_line_length": 43.217105865478516, "blob_id": "997d93fc8d45ed69008e093c8cca91a08cd53d6b", "content_id": "69861fabddd95ce749e377c1606ad6134c31f318", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6722, "license_type": "no_license", "max_line_length": 130, "num_lines": 152, "path": "/nets/emb3dnet.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport sys\nsys.path.append(\"..\")\n\nimport hyperparams as hyp\nimport utils.improc\nimport utils.misc\nimport utils.vox\nimport utils.basic\n\nclass Emb3dNet(nn.Module):\n def __init__(self):\n super(Emb3dNet, self).__init__()\n\n print('Emb3dNet...')\n self.batch_k = 2\n self.num_samples = hyp.emb3d_num_samples\n assert(self.num_samples > 0)\n self.sampler = utils.misc.DistanceWeightedSampling(batch_k=self.batch_k, normalize=False)\n self.criterion = utils.misc.MarginLoss() #margin=args.margin,nu=args.nu)\n self.beta = 1.2\n\n self.dict_len = 20000\n self.neg_pool = utils.misc.SimplePool(self.dict_len, version='pt')\n self.ce = torch.nn.CrossEntropyLoss()\n\n def sample_embs(self, emb0, emb1, valid, B, Z, Y, X, mod='', do_vis=False, summ_writer=None):\n if hyp.emb3d_mindist == 0.0:\n # pure random\n perm = torch.randperm(B*Z*Y*X)\n emb0 = emb0.reshape(B*Z*Y*X, -1)\n emb1 = emb1.reshape(B*Z*Y*X, -1)\n valid = valid.reshape(B*Z*Y*X, -1)\n emb0 = emb0[perm[:self.num_samples*B]]\n emb1 = emb1[perm[:self.num_samples*B]]\n valid = valid[perm[:self.num_samples*B]]\n return emb0, emb1, valid\n else:\n emb0_all = []\n emb1_all = []\n valid_all = []\n for b in list(range(B)):\n sample_indices, sample_locs, sample_valids = utils.misc.get_safe_samples(\n valid[b], (Z, Y, X), self.num_samples, mode='3d', tol=hyp.emb3d_mindist)\n emb0_s_ = emb0[b, sample_indices]\n emb1_s_ = emb1[b, sample_indices]\n # these are N x D\n emb0_all.append(emb0_s_)\n emb1_all.append(emb1_s_)\n valid_all.append(sample_valids)\n\n if do_vis and (summ_writer is not None):\n sample_occ = utils.vox.voxelize_xyz(torch.unsqueeze(sample_locs, dim=0), Z, Y, X, already_mem=True)\n summ_writer.summ_occ('emb3d/samples_%s/sample_occ' % mod, sample_occ, reduce_axes=[2,3])\n summ_writer.summ_occ('emb3d/samples_%s/valid' % mod, torch.reshape(valid, [B, 1, Z, Y, X]), reduce_axes=[2,3])\n\n emb0_all = torch.cat(emb0_all, axis=0)\n emb1_all = torch.cat(emb1_all, axis=0)\n valid_all = torch.cat(valid_all, axis=0)\n return emb0_all, emb1_all, valid_all\n \n def compute_ce_loss(self, B, C, Z, Y, X, emb_e_vec_all, emb_g_vec_all, valid_vec_all, mod='', do_vis=False, summ_writer=None):\n emb_e_vec, emb_g_vec, valid_vec = self.sample_embs(emb_e_vec_all,\n emb_g_vec_all,\n valid_vec_all,\n B, Z, Y, X,\n mod=mod,\n do_vis=do_vis,\n summ_writer=summ_writer)\n _, emb_n_vec, _ = self.sample_embs(emb_e_vec_all,\n emb_g_vec_all,\n valid_vec_all,\n B, Z, Y, X,\n mod=mod,\n do_vis=do_vis,\n summ_writer=summ_writer)\n emb_e_vec = emb_e_vec.view(B*self.num_samples, C)\n emb_g_vec = emb_g_vec.view(B*self.num_samples, C)\n emb_n_vec = emb_n_vec.view(B*self.num_samples, C)\n \n self.neg_pool.update(emb_n_vec.cpu())\n # print('neg_pool len:', len(self.neg_pool))\n emb_n = self.neg_pool.fetch().cuda()\n\n # print('emb_n', emb_n.shape)\n N2, C2 = list(emb_n.shape)\n assert (C2 == C)\n \n # l_negs = torch.mm(q.view(N, C), negs.view(C, N2)) # this is N x N2\n\n emb_q = emb_e_vec.clone()\n emb_k = emb_g_vec.clone()\n \n # print('emb_q', emb_q.shape)\n # print('emb_k', emb_k.shape)\n N = emb_q.shape[0]\n l_pos = torch.bmm(emb_q.view(N,1,-1), emb_k.view(N,-1,1))\n\n # print('l_pos', l_pos.shape)\n l_neg = torch.mm(emb_q, emb_n.T)\n # print('l_neg', l_neg.shape)\n \n l_pos = l_pos.view(N, 1)\n # print('l_pos', l_pos.shape)\n logits = torch.cat([l_pos, l_neg], dim=1)\n\n labels = torch.zeros(N, dtype=torch.long).cuda()\n\n temp = 0.07\n emb_loss = self.ce(logits/temp, labels)\n # print('emb_loss', emb_loss.detach().cpu().numpy())\n return emb_loss\n \n def forward(self, emb_e, emb_g, vis_e, vis_g, summ_writer=None):\n total_loss = torch.tensor(0.0).cuda()\n\n if torch.isnan(emb_e).any() or torch.isnan(emb_g).any():\n assert(False)\n\n B, C, D, H, W = list(emb_e.shape)\n # put channels on the end\n emb_e_vec = emb_e.permute(0,2,3,4,1).reshape(B, D*H*W, C)\n emb_g_vec = emb_g.permute(0,2,3,4,1).reshape(B, D*H*W, C)\n vis_e_vec = vis_e.permute(0,2,3,4,1).reshape(B, D*H*W, 1)\n vis_g_vec = vis_g.permute(0,2,3,4,1).reshape(B, D*H*W, 1)\n\n # ensure they are both nonzero, else we probably masked or warped something\n valid_vec_e = 1.0 - (emb_e_vec==0).all(dim=2, keepdim=True).float()\n valid_vec_g = 1.0 - (emb_g_vec==0).all(dim=2, keepdim=True).float()\n valid_vec = valid_vec_e * valid_vec_g\n vis_e_vec *= valid_vec\n vis_g_vec *= valid_vec\n # valid_g = 1.0 - (emb_g==0).all(dim=1, keepdim=True).float()\n \n assert(self.num_samples < (B*D*H*W))\n # we will take num_samples from each one\n\n ce_loss = self.compute_ce_loss(B, C, D, H, W, emb_e_vec, emb_g_vec.detach(), vis_g_vec, 'g', False, summ_writer)\n total_loss = utils.misc.add_loss('emb3d/emb_ce_loss', total_loss, ce_loss, hyp.emb3d_ce_coeff, summ_writer)\n\n # where g is valid, we use it as reference and pull up e\n l2_loss = utils.basic.reduce_masked_mean(utils.basic.sql2_on_axis(emb_e-emb_g.detach(), 1, keepdim=True), vis_g)\n total_loss = utils.misc.add_loss('emb3d/emb3d_l2_loss', total_loss, l2_loss, hyp.emb3d_l2_coeff, summ_writer)\n\n l2_loss_im = torch.mean(utils.basic.sql2_on_axis(emb_e-emb_g, 1, keepdim=True), dim=3)\n if summ_writer is not None:\n summ_writer.summ_oned('emb3d/emb3d_l2_loss', l2_loss_im)\n summ_writer.summ_feats('emb3d/embs_3d', [emb_e, emb_g], pca=True)\n return total_loss\n\n" }, { "alpha_fraction": 0.505509614944458, "alphanum_fraction": 0.547658383846283, "avg_line_length": 23.362415313720703, "blob_id": "c967a01d6cef802a70d7c3f49b45afa4c7a7f5e1", "content_id": "01cd9aab8b6b44dde084ab83421511654a20d5cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3630, "license_type": "no_license", "max_line_length": 80, "num_lines": 149, "path": "/exp_carla_det.py", "repo_name": "aharley/neural_3d_mapping", "src_encoding": "UTF-8", "text": "from exp_base import *\n\n############## choose an experiment ##############\n\ncurrent = 'det_builder'\ncurrent = 'det_trainer'\n\nmod = '\"det00\"' # go\nmod = '\"det01\"' # rescore with inbound\nmod = '\"det02\"' # show scores\nmod = '\"det03\"' # show bev too\nmod = '\"det04\"' # narrower bounds, to see \nmod = '\"det05\"' # print scorelists\nmod = '\"det06\"' # rescore actually\nmod = '\"det07\"' # print score no matter what\nmod = '\"det08\"' # float2str\nmod = '\"det09\"' # run feat3d\nmod = '\"det10\"' # really run feat3d\nmod = '\"det11\"' # get axboxlist\nmod = '\"det12\"' # solid centorid\nmod = '\"det13\"' # update lrtlist util\nmod = '\"det14\"' # run detnet\nmod = '\"det15\"' # \nmod = '\"det16\"' # train a whiel\nmod = '\"det17\"' # bugfix\nmod = '\"det18\"' # return early if score < B/2\nmod = '\"det19\"' # new utils\nmod = '\"det20\"' # B2\nmod = '\"det21\"' # B4\nmod = '\"det22\"' # clean up\nmod = '\"det23\"' # rand centroid\nmod = '\"det24\"' # padding 0\nmod = '\"det25\"' # avoid warping to R0\nmod = '\"det26\"' # scorelist *= inbound\nmod = '\"det27\"' # use scorelist in the vis\nmod = '\"det28\"' # only draw nonzero boxes\nmod = '\"det29\"' # cleaned up\nmod = '\"det30\"' # do not draw 0,1 scores\nmod = '\"det31\"' # cleaned up\nmod = '\"det32\"' # evaluate against axlrtlist\nmod = '\"det33\"' # only show a fixed number of digits\nmod = '\"det34\"' # fix that \nmod = '\"det35\"' # maxlen=3\nmod = '\"det36\"' # log500\n\n############## define experiments ##############\n\nexps['det_builder'] = [\n 'carla_det', # mode\n 'carla_multiview_10_data', # dataset\n 'seqlen1',\n '8-4-8_bounds',\n # '16-8-16_bounds',\n '3_iters',\n # '5k_iters',\n # 'lr3', \n 'train_feat3d',\n 'train_det',\n 'B1',\n 'no_shuf',\n 'no_backprop',\n # 'log50',\n 'log1',\n]\nexps['det_trainer'] = [\n 'carla_det', # mode\n # 'carla_multiview_10_data', # dataset\n 'carla_multiview_train_data', # dataset\n 'seqlen1',\n # 'carla_multiview_train_val_data', # dataset\n '16-8-16_bounds',\n # 'carla_16-8-16_bounds_train', \n # 'carla_16-8-16_bounds_val', \n '200k_iters',\n 'lr3',\n 'B4',\n 'train_feat3d',\n 'train_det',\n 'log500', \n]\n\n############## group configs ##############\n\ngroups['carla_det'] = ['do_carla_det = True']\n\n\n\n############## datasets ##############\n\n# DHW for mem stuff\nSIZE = 32\nZ = int(SIZE*4)\nY = int(SIZE*2)\nX = int(SIZE*4)\n\nK = 8 # how many proposals to consider\n\n# H and W for proj stuff\nPH = int(H/2.0)\nPW = int(W/2.0)\n\n\n# S = 1\n# groups['carla_multiview_10_data'] = [\n# 'dataset_name = \"carla\"',\n# 'H = %d' % H,\n# 'W = %d' % W,\n# 'trainset = \"mags7i3ten\"',\n# 'trainset_format = \"multiview\"', \n# 'trainset_seqlen = %d' % S, \n# 'dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"',\n# 'dataset_filetype = \"npz\"'\n# ]\n# groups['carla_multiview_train_val_data'] = [\n# 'dataset_name = \"carla\"',\n# 'H = %d' % H,\n# 'W = %d' % W,\n# 'trainset = \"mags7i3t\"',\n# 'trainset_format = \"multiview\"', \n# 'trainset_seqlen = %d' % S, \n# 'valset = \"mags7i3v\"',\n# 'valset_format = \"multiview\"', \n# 'valset_seqlen = %d' % S, \n# 'dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"',\n# 'dataset_filetype = \"npz\"'\n# ]\n\n############## verify and execute ##############\n\ndef _verify_(s):\n varname, eq, val = s.split(' ')\n assert varname in globals()\n assert eq == '='\n assert type(s) is type('')\n\nprint(current)\nassert current in exps\nfor group in exps[current]:\n print(\" \" + group)\n assert group in groups\n for s in groups[group]:\n print(\" \" + s)\n _verify_(s)\n exec(s) \n\ns = \"mod = \" + mod\n_verify_(s)\n\nexec(s)\n" } ]
22
ValeDelga/CDIN_O2021
https://github.com/ValeDelga/CDIN_O2021
7780bb86987c1a0ae5ac7103d142411aa491f53a
1f1045d412d9701425a4dbac2e5f4ff8bd09045c
19227dcb1771a1317ae0187f175de21e3baf8881
refs/heads/main
2023-08-11T14:50:07.866172
2021-10-04T14:16:26
2021-10-04T14:16:26
399,133,286
0
0
MIT
2021-08-23T14:22:58
2021-08-23T04:09:56
2021-08-23T04:09:53
null
[ { "alpha_fraction": 0.520432710647583, "alphanum_fraction": 0.524338960647583, "avg_line_length": 27.491228103637695, "blob_id": "4c09a5750cfe88cac17ae42e90e22b0bd127f227", "content_id": "2aeee972a82e47cf75417030d0d09c76d69a1c80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3335, "license_type": "permissive", "max_line_length": 152, "num_lines": 114, "path": "/Modulo2/Code/CDIN.py", "repo_name": "ValeDelga/CDIN_O2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 6 07:56:54 2021\n\n@author: gaddiel\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport string\n\nclass CDIN:\n \n def dqr(data):\n # Lista de variables de la base de datos\n columns = pd.DataFrame(list(data.columns.values), columns=['Nombres'], index=list(data.columns.values))\n \n # Lista de tipos de datos\n data_types = pd.DataFrame(data.dtypes, columns=['Tipo_Dato'])\n \n #Lista de valores perdidos (NaN)\n missing_values = pd.DataFrame(data.isnull().sum(), columns=['Datos_Faltantes'])\n \n #Lista de valores presentes\n present_values = pd.DataFrame(data.count(), columns=['Valores_Presentes'])\n \n #Lista de valores unicos para cada variable\n unique_values = pd.DataFrame(columns=['Num_Valores_Unicos'])\n for col in list(data.columns.values):\n unique_values.loc[col] = [data[col].nunique()]\n \n # Lista de valores mínimos para cada variable\n min_values = pd.DataFrame(columns=['Min'])\n for col in list(data.columns.values):\n try:\n min_values.loc[col]=[data[col].min()]\n except:\n pass\n \n # Lista de valores máximos para cada variable\n max_values = pd.DataFrame(columns=['Max'])\n for col in list(data.columns.values):\n try:\n max_values.loc[col]=[data[col].max()]\n except:\n pass\n \n \n # Columna 'Categórica' que obtenga una valor booleando True cuando mi columna es una variable\n # categóorica y False cuando es numérica\n categorica = pd.DataFrame(columns=['Categorica'])\n for col in list(data.columns.values):\n if data[col].dtype=='object':\n categorica.loc[col] = True\n else:\n categorica.loc[col] = False\n \n \n \n return columns.join(data_types).join(missing_values).join(present_values).join(unique_values).join(min_values).join(max_values).join(categorica)\n \n def remove_punctuation(x):\n try:\n x=''.join(ch for ch in x if ch not in string.punctuation)\n except:\n pass\n return x\n \n def remove_digits(x):\n try:\n x=''.join(ch for ch in x if ch not in string.digits)\n except:\n pass\n return x\n \n def remove_whitespace(x):\n try:\n x=''.join(x.split())\n except:\n pass\n return x\n \n def replace_text(x, to_replace, replacement):\n try:\n x=x.replace(to_replace, replacement)\n except:\n pass\n return x\n \n # Convertir a mayúsculas\n def uppercase_text(x):\n try:\n x=x.upper()\n except:\n pass\n return x\n \n # Convertir a minúsculas\n def lowercase_text(x):\n try:\n x=x.lower()\n except:\n pass\n return x\n \n # Quitar espacios en blanco izquierda y derecha\n def remove_whitespace_lr(x):\n try:\n x=x.lstrip()\n x=x.rstrip()\n except:\n pass\n return x\n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n " }, { "alpha_fraction": 0.6732075214385986, "alphanum_fraction": 0.698867917060852, "avg_line_length": 32.97435760498047, "blob_id": "9afba4a3766666dec5ca5cbc2e1d93ba204077b0", "content_id": "0565b12f201e068181cce9638754c1ac659df5d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1355, "license_type": "permissive", "max_line_length": 147, "num_lines": 39, "path": "/README.md", "repo_name": "ValeDelga/CDIN_O2021", "src_encoding": "UTF-8", "text": "# Ciencia de Datos e Inteligencia de Negocios - Otoño 2021\nEn este repositorio podras encontrar el material del curso de Ciencia de Datos e Inteligencia de Negocios (CDIN) para el periodo de Otoño del 2021.\n\nEste curso está dividido en cuatro módulos. \n\n`Introducción.` **Repaso de Librerías Numpy, Pandas.**\n\n 1. Lenguaje de Programación del Curso.\n 2. Repaso librería Numpy.\n 3. Repaso librería Pandas.\n - Tarea 1.\n 4.- ¿Qué es la Ciencia de Datos?\n 5.- Definiciones.\n \n`Módulo 1.` **Minería de Datos: Datos y su clasificación.**\n\n 1. Datos y su Clasificación.\n 2. Análisis Exploratorio de Datos (EDA).\n 3. Reporte de Calidad de Datos (DQR).\n 4. Limpieza de datos.\n 5. Medidas de Similitud datos.\n - Tarea 2.\n\n`Módulo 2.` **Preprocesamiento de Datos y Aprendizaje no Supervizado.**\n\n 1. Integración de datos.\n 2. ¿Qué es el Aprendizaje Automático?\n 3. Aprendizaje no Supervizado para Ciencia de Datos\n 4. Búsqueda de Patrones (algoritmos de clustering)\n 5. Reducción de Datos (Análisis de Componentes Principales)\n - Tarea 3.\n \n`Módulo 3.` **Aprendizaje Supervizado en Ciencia de Datos.**\n\n 1. Análisis de Discriminantes Lineales.\n 2. Regresión Logística.\n 3. Máquina de Vector Soporte (SVM)\n 4. Introducción a las Redes Neuronales\n - Tarea 4.\n" }, { "alpha_fraction": 0.6368194818496704, "alphanum_fraction": 0.672636091709137, "avg_line_length": 28.46808433532715, "blob_id": "a69b5e99588bedca64cc33898ddef3e115733d81", "content_id": "4cd6d67d01d982dd77c334cd75d14ba085b3919d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "permissive", "max_line_length": 84, "num_lines": 47, "path": "/Modulo3/Data/digits_ANN", "repo_name": "ValeDelga/CDIN_O2021", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 6 09:27:56 2020\n\n@author: deloga\n\"\"\"\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import datasets\nfrom sklearn.neural_network import MLPClassifier\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndigits = datasets.load_digits()\n\nplt.gray()\nplt.matshow(digits.images[5])\nplt.show()\n\nfig = plt.figure(figsize = (6,6))\nfig.subplots_adjust(left=0, right =1, bottom=0, top=1, hspace= 0.05, wspace=0.05)\n\nfor i in range(64):\n ax= fig.add_subplot(8, 8, i+1, xticks=[], yticks=[])\n ax.imshow(digits.images[i], cmap = plt.cm.binary, interpolation ='nearest')\n # la etiqueta\n ax.text(0,7, str(digits.target[i]))\n \nX, y = digits.data, digits.target\n\nX_tr, X_t, y_tr, y_t = train_test_split(X, y, test_size=0.2, random_state=0)\n\nscaling = MinMaxScaler(feature_range=(-1,1)).fit(X_tr)\nX_tr = scaling.transform(X_tr)\nX_t = scaling.transform(X_t)\n\nnn = MLPClassifier(hidden_layer_sizes = (512,), activation = 'relu', solver= 'adam',\n shuffle = True, tol = 1e-4, random_state =1)\n\ncv = cross_val_score(nn, X_tr, y_tr, cv=10)\ntest_score = nn.fit(X_tr, y_tr).score(X_t, y_t)\n\nprint('CV accuracy score: %0.3f' % np.mean(cv))\nprint('Test accuracy score: %0.3f' % (test_score))\n\n\n\n\n\n\n\n\n\n\n\n" } ]
3
MikeSoft007/idlUSSD
https://github.com/MikeSoft007/idlUSSD
1fda566dc0c857f2d874195b8d34efe2cb3d2936
60b18c36f6ddadbc376e8f2f601e4290672031be
f9bba81474241ac31ae2bffc2f24beeb2e919e43
refs/heads/master
2021-07-10T09:26:27.471574
2020-03-10T09:02:45
2020-03-10T09:02:45
246,251,773
1
1
MIT
2020-03-10T08:55:15
2020-05-11T10:34:37
2022-01-06T22:43:17
Python
[ { "alpha_fraction": 0.6689295172691345, "alphanum_fraction": 0.6704961061477661, "avg_line_length": 22.072288513183594, "blob_id": "bf08f684868e3c23459b344a53d960cbb03db133", "content_id": "f700d5697d622d86217bf9023751cd36a04be139", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1915, "license_type": "permissive", "max_line_length": 81, "num_lines": 83, "path": "/app/__init__.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import logging\nimport logging.config\nimport os\n\nfrom celery.utils.log import get_task_logger\nfrom dotenv import load_dotenv\nfrom flask import Flask\nfrom flask_login import LoginManager\n\nfrom config import config, Config\nfrom .AfricasTalkingGateway import gateway\nfrom .database import db, redis\n\ndotenv_path = os.path.join(os.path.join(os.path.dirname(__file__), \"..\"), \".env\")\nload_dotenv(dotenv_path)\n\n__version__ = \"0.2.0\"\n__author__ = \"[email protected]\"\n__description__ = \"Nerds Microfinance application\"\n__email__ = \"[email protected]\"\n__copyright__ = \"MIT LICENCE\"\n\nlogin_manager = LoginManager()\n\ncelery_logger = get_task_logger(__name__)\n\n\ndef create_celery():\n from celery import Celery\n\n celery = Celery(\n __name__,\n backend=Config.CELERY_RESULT_BACKEND,\n broker=Config.CELERY_BROKER_URL\n )\n return celery\n\n\ncelery = create_celery()\n\n\ndef create_app(config_name):\n app = Flask(__name__)\n # configure application\n app.config.from_object(config[config_name])\n config[config_name].init_app(app)\n\n # setup login manager\n login_manager.init_app(app)\n\n # setup database\n redis.init_app(app)\n db.init_app(app)\n\n # initialize africastalking gateway\n gateway.init_app(app=app)\n\n # setup celery\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n\n # register blueprints\n from app.ussd import ussd as ussd_bp\n\n app.register_blueprint(ussd_bp)\n\n # setup logging\n from app.util import setup_logging\n from config import basedir\n\n if app.debug:\n logging_level = logging.DEBUG\n else:\n logging_level = logging.INFO\n path = os.path.join(basedir, \"app_logger.yaml\")\n setup_logging(default_level=logging_level, logger_file_path=path)\n return app\n" }, { "alpha_fraction": 0.7216494679450989, "alphanum_fraction": 0.7216494679450989, "avg_line_length": 18.399999618530273, "blob_id": "04f9f43178011e8ce1080fae712f289fb30e5bb8", "content_id": "d0644c6e2a76ceabc14c2b0742fe553fcadffc18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "permissive", "max_line_length": 34, "num_lines": 5, "path": "/app/ussd/__init__.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from flask import Blueprint\n\nussd = Blueprint('ussd', __name__)\n\nfrom . import views, decorators\n" }, { "alpha_fraction": 0.6076869368553162, "alphanum_fraction": 0.6159329414367676, "avg_line_length": 39.88571548461914, "blob_id": "4befea2f5d4a293cbfd93ba848830be6b1a80a0c", "content_id": "eac960255377a159cfb3434d3465617f06b64cc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7155, "license_type": "permissive", "max_line_length": 138, "num_lines": 175, "path": "/app/ussd/views.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from flask import g, make_response, request, url_for\n\nfrom . import ussd\nfrom .airtime import Airtime\nfrom .deposit import Deposit\nfrom .home import LowerLevelMenu\nfrom .register import RegistrationMenu\nfrom .utils import respond\nfrom .withdraw import WithDrawal\nfrom ..models import AnonymousUser\n\n\[email protected]('/', methods=['POST', 'GET'])\ndef index():\n response = make_response(\"END connection ok\")\n response.headers['Content-Type'] = \"text/plain\"\n return response\n\n\[email protected]('/ussd/callback', methods=['POST'])\ndef ussd_callback():\n \"\"\"Handles post call back from AT\"\"\"\n session_id = g.session_id\n user = g.current_user\n session = g.session\n user_response = g.user_response\n if isinstance(user, AnonymousUser):\n # register user\n menu = RegistrationMenu(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user)\n return menu.execute()\n level = session.get('level')\n if level < 2:\n menu = LowerLevelMenu(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user)\n return menu.execute()\n\n if level >= 50:\n menu = Deposit(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user, level=level)\n return menu.execute()\n\n if level >= 40:\n menu = WithDrawal(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user, level=level)\n return menu.execute()\n\n if level >= 10:\n menu = Airtime(session_id=session_id, session=session, phone_number=g.phone_number, user_response=user_response,\n user=user, level=level)\n return menu.execute()\n\n response = make_response(\"END nothing here\", 200)\n response.headers['Content-Type'] = \"text/plain\"\n return response\n\n\[email protected]('/voice/menu')\ndef voice_menu():\n \"\"\"\n When the user enters the digit - in this case 0, 1 or 2, this route\n switches between the various dtmf digits to\n make an outgoing call to the right recipient, who will be\n bridged to speak to the person currently listening to music on hold.\n We specify this music with the ringtone flag as follows:\n ringbackTone=\"url_to/static/media/SautiFinaleMoney.mp3\"\n \"\"\"\n\n # 1. Receive POST from AT\n isActive = request.get('isActive')\n callerNumber = request.get('callerNumber')\n dtmfDigits = request.get('dtmfDigits')\n sessionId = request.get('sessionId')\n # Check if isActive=1 to act on the call or isActive=='0' to store the\n # result\n\n if (isActive == '1'):\n # 2a. Switch through the DTMFDigits\n if (dtmfDigits == \"0\"):\n # Compose response - talk to sales-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Sales.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(\n url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(response)\n\n elif (dtmfDigits == \"1\"):\n # 2c. Compose response - talk to support-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Support.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(\n url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(response)\n elif (dtmfDigits == \"2\"):\n # 2d. Redirect to the main IVR-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Redirect>{}</Redirect>'.format(url_for('voice_callback'))\n response += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(response)\n else:\n # 2e. By default talk to support\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Support.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(\n url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(response)\n else:\n # 3. Store the data from the POST\n durationInSeconds = request.get('durationInSeconds')\n direction = request.get('direction')\n amount = request.get('amount')\n callerNumber = request.get('callerNumber')\n destinationNumber = request.get('destinationNumber')\n sessionId = request.get('sessionId')\n callStartTime = request.get('callStartTime')\n isActive = request.get('isActive')\n currencyCode = request.get('currencyCode')\n status = request.get('status')\n\n\[email protected]('/voice/callback', methods=['POST'])\ndef voice_callback():\n \"\"\"\n voice_callback from AT's gateway is handled here\n\n \"\"\"\n sessionId = request.get('sessionId')\n isActive = request.get('isActive')\n\n if isActive == \"1\":\n callerNumber = request.get('callerNumber')\n # GET values from the AT's POST request\n session_id = request.values.get(\"sessionId\", None)\n isActive = request.values.get('isActive')\n serviceCode = request.values.get(\"serviceCode\", None)\n text = request.values.get(\"text\", \"default\")\n text_array = text.split(\"*\")\n user_response = text_array[len(text_array) - 1]\n\n # Compose the response\n menu_text = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n menu_text += '<Response>'\n menu_text += '<GetDigits timeout=\"30\" finishOnKey=\"#\" callbackUrl=\"https://49af2317.ngrok.io/api/v1.1/voice/callback\">'\n menu_text += '<Say>\"Thank you for calling. Press 0 to talk to sales, 1 to talk to support or 2 to hear this message again.\"</Say>'\n menu_text += '</GetDigits>'\n menu_text += '<Say>\"Thank you for calling. Good bye!\"</Say>'\n menu_text += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(menu_text)\n\n else:\n # Read in call details (duration, cost). This flag is set once the call is completed.\n # Note that the gateway does not expect a response in thie case\n\n duration = request.get('durationInSeconds')\n currencyCode = request.get('currencyCode')\n amount = request.get('amount')\n\n # You can then store this information in the database for your records\n" }, { "alpha_fraction": 0.6230167746543884, "alphanum_fraction": 0.6338144540786743, "avg_line_length": 47.79838562011719, "blob_id": "0a407b52ecf4e18f334230990038b1bad18ef17b", "content_id": "7c4c9fbfb932029060d1852451b3bc45bbd2d0c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18152, "license_type": "permissive", "max_line_length": 481, "num_lines": 372, "path": "/README.md", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "[![DUB](https://img.shields.io/dub/l/vibe-d.svg)]()\n[![PyPI](https://img.shields.io/pypi/v/nine.svg)]()\n[![Build Status](https://dev.azure.com/dannyongesa/ussd%20python%20demo/_apis/build/status/Piusdan.USSD-Python-Demo?branchName=master)](https://dev.azure.com/dannyongesa/ussd%20python%20demo/_build/latest?definitionId=2&branchName=master)\n\n# Setting Up a USSD Service for MicroFinance Institutions\n#### A step-by-step guide\n\n- Setting up the logic for USSD is easy with the [Africa's Talking API](docs.africastalking.com/ussd). This is a guide to how to use the code provided on this [repository](https://github.com/Piusdan/USSD-Python-Demo) to create a USSD that allows users to get registered and then access a menu of the following services:\n\n| USSD APP Features |\n| --------------------------------------------:| \n| Request to get a call from support | \n| Deposit Money to user's account | \n| Withdraw money from users account | \n| Send money from users account to another | \n| Repay loan | \n| Buy Airtime | \n\n----\n\n## INSTALLATION AND GUIDE\n\n1. clone/download the project into the directory of your choice\n\n1. Create a .env file on your root directory \n\n $ cp .env_example .env\n\nBe sure to substitute the example variables with your credentials\n\n#### Docker\n\n- To install using docker, run\n\n $ docker-compose up -b 8080:8000\n\n This will start your application on port 8080\n\n#### Using a virtual environment\n\n1. Create a virtual environment\n\n $ python3 -m venv venv\n $ . venv/bin/activate\n\n1. Install the project's dependancies\n\n $ pip install requirements.txt \n\n\n1. Configure your flask path\n\n $ export FLASK_APP=manage.py\n\n1. Initialise your database\n\n $ flask initdb\n\n1. Launch application\n\n $ flask run \n\n1. Head to https://localhost:5000\n\n- You need to set up on the sandbox and [create](https://sandbox.africastalking.com/ussd/createchannel) a USSD channel that you will use to test by dialing into it via our [simulator](https://simulator.africastalking.com:1517/).\n\n- Assuming that you are doing your development on a localhost, you have to expose your application living in the webroot of your localhost to the internet via a tunneling application like [Ngrok](https://ngrok.com/). Otherwise, if your server has a public IP, you are good to go! Your URL callback for this demo will become:\n http://<your ip address>/MfUSSD/microfinanceUSSD.php\n\n- This application has been developed on an Ubuntu 16.04LTS and lives in the web root at /var/www/html/MfUSSD. Courtesy of Ngrok, the publicly accessible url is: https://49af2317.ngrok.io (instead of http://localhost) which is referenced in the code as well. \n(Create your own which will be different.)\n\n- The webhook or callback to this application therefore becomes: \nhttps://49af2317.ngrok.io/api/v1.1/ussd/callback. \nTo allow the application to talk to the Africa's Talking USSD gateway, this callback URL is placed in the dashboard, [under ussd callbacks here](https://account.africastalking.com/ussd/callback).\n\n- Finally, this application works with a connection to an sqlite database. This is the default database shipped with python, however its recomended switching to a proper database when deploying the application. Also create a session_levels table and a users table. These details are configured in the models.py and this is required in the main application script app/apiv2/views.py\n\n\n| Field | Type | Null | Key | Default | Extra |\n| ------------- |:----------------------------:| -----:|----:| -----------------:| ---------------------------:|\n| id | int(6) | YES | | NULL | |\n| name | varchar(30) | YES | | NULL | |\n| phonenumber | varchar(20) | YES | | NULL | |\n| city | varchar(30) | YES | | NULL | |\n| validation | varchar(30) | YES | | NULL | |\n| reg_date | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |\n\n- The application uses redis for session management. User sessions are stored as key value pairs in redis.\n\n\n## Features on the Services List\nThis USSD application has the following user journey.\n\n- The user dials the ussd code - something like `*384*303#`\n\n- The application checks if the user is registered or not. If the user is registered, the services menu is served which allows the user to: receive SMS, receive a call with an IVR menu.\n\n- In case the user is not registered, the application prompts the user for their name and city (with validations), before successfully serving the services menu.\n\n## Code walkthrough\nThis documentation is for the USSD application that lives in https://49af2317.ngrok.io/api/v1.1/ussd/callback.\n- The applications entrypoint is at `app/ussd/views.py`\n```python\n #1. This code only runs after a post request from AT\n @ussd.route('/ussd/callback', methods=['POST'])\n def ussd_callback():\n \"\"\"\n Handles post call back from AT\n\n :return:\n \"\"\"\n```\nImport all the necessary scripts to run this application\n\n```python\n # 2. Import all neccesary modules\n from flask import g, make_response\n \n from app.models import AnonymousUser\n from . import ussd\n from .airtime import Airtime\n from .deposit import Deposit\n from .home import LowerLevelMenu\n from .register import RegistrationMenu\n from .withdraw import WithDrawal\n```\n\nReceive the HTTP POST from AT. `app/ussd/decorators.py`\n\nWe will use a decorator that hooks on to the application request, to query and initialize session metadata stored in redis.\n\n```python\n # 3. get data from ATs post payload\n session_id = request.values.get(\"sessionId\", None)\n phone_number = request.values.get(\"phoneNumber\", None)\n text = request.values.get(\"text\", \"default\")\n```\n\nThe AT USSD gateway keeps chaining the user response. We want to grab the latest input from a string like 1*1*2\n```python\n text_array = text.split(\"*\")\n user_response = text_array[len(text_array) - 1]\n```\n\nInteractions with the user can be managed using the received sessionId and a level management process that your application implements as follows.\n\n- The USSD session has a set time limit(20-180 secs based on provider) under which the sessionId does not change. Using this sessionId, it is easy to navigate your user across the USSD menus by graduating their level(menu step) so that you dont serve them the same menu or lose track of where the user is. \n- Query redis for the user's session level using the sessionID as the key. If this exists, the user is returning and they therefore have a stored level. Grab that level and serve that user the right menu. Otherwise, serve the user the home menu.\n- The session metadata is stored in flask's `g` global variable to allow for access within the current request context.\n```python\n\t# 4. Query session metadata from redis or initialize a new session for this user if the session does not exist\n # get session\n session = redis.get(session_id)\n if session is None:\n session = {\"level\": 0, \"session_id\": session_id}\n redis.set(session_id, json.dumps(session))\n else:\n session = json.loads(session.decode())\n # add user, response and session to the request variable g\n g.user_response = text_array[len(text_array) - 1]\n g.session = session\n g.current_user = user\n g.phone_number = phone_number\n g.session_id = session_id\n return func(*args, **kwargs)\n```\n\nBefore serving the menu, check if the incoming phone number request belongs to a registered user(sort of a login). If they are registered, they can access the menu, otherwise, they should first register.\n\n`app/ussd/views.py`\n```python \n\t# 5. Check if the user is in the db\n session_id = g.session_id\n user = g.current_user\n session = g.session\n user_response = g.user_response\n if isinstance(user, AnonymousUser):\n # register user\n menu = RegistrationMenu(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user)\n return menu.execute()\n```\n\nIf the user is available and all their mandatory fields are complete, then the application switches between their responses to figure out which menu to serve. The first menu is usually a result of receiving a blank text -- the user just dialed in.\n```python\n # 7. Serve the Services Menu \n if level < 2:\n menu = LowerLevelMenu(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user)\n return menu.execute()\n\n if level >= 50:\n menu = Deposit(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user, level=level)\n return menu.execute()\n\n if level >= 40:\n menu = WithDrawal(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user, level=level)\n return menu.execute()\n\n if level >= 10:\n menu = Airtime(session_id=session_id, session=session, phone_number=g.phone_number, user_response=user_response,\n user=user, level=level)\n return menu.execute()\n\t\n```\nIf the user is not registered, we use the users level - purely to take the user through the registration process. We also enclose the logic in a condition that prevents the user from sending empty responses.\n```python\n if isinstance(user, AnonymousUser):\n # register user\n menu = RegistrationMenu(session_id=session_id, session=session, phone_number=g.phone_number,\n user_response=user_response, user=user)\n return menu.execute()\n \n```\n\n## Complexities of Voice.\n- The voice service included in this script requires a few juggling acts and probably requires a short review of its own.\nWhen the user requests a to get a call, the following happens.\na) The script at https://49af2317.ngrok.io/api/v1.1/ussd/callback requests the call() method through the Africa's Talking Voice Gateway, passing the number to be called and the caller/dialer Id. The call is made and it comes into the users phone. When they answer isActive becomes 1.\n\n```python\n def please_call(self):\n # call the user and bridge to a sales person\n menu_text = \"END Please wait while we place your call.\\n\"\n\n # make a call\n caller = current_app.config[\"AT_NUMBER\"]\n to = self.user.phone_number\n\n # create a new instance of our awesome gateway\n gateway = AfricasTalkingGateway(\n current_app.config[\"AT_USERNAME\"], current_app.config[\"AT_APIKEY\"])\n try:\n gateway.call(caller, to)\n except AfricasTalkingGateway as e:\n print \"Encountered an error when calling: {}\".format(str(e))\n\n # print the response on to the page so that our gateway can read it\n return respond(menu_text)\tcase \"2\":\n```\t\t\t \nb) As a result, Africa's Talking gateway check the callback for the voice number in this case +254703554404.\nc) The callback is a route on our views.py file whose URL is: https://49af2317.ngrok.io/api/v1.1/voice/callback\nd) The instructions are to respond with a text to speech message for the user to enter dtmf digits.\n\n```python\n @ussd.route('/voice/callback', methods=['POST'])\n def voice_callback():\n \"\"\"\n voice_callback from AT's gateway is handled here\n\n \"\"\"\n sessionId = request.get('sessionId')\n isActive = request.get('isActive')\n\n if isActive == \"1\":\n callerNumber = request.get('callerNumber')\n # GET values from the AT's POST request\n session_id = request.values.get(\"sessionId\", None)\n isActive = request.values.get('isActive')\n serviceCode = request.values.get(\"serviceCode\", None)\n text = request.values.get(\"text\", \"default\")\n text_array = text.split(\"*\")\n user_response = text_array[len(text_array) - 1]\n\n # Compose the response\n menu_text = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n menu_text += '<Response>'\n menu_text += '<GetDigits timeout=\"30\" finishOnKey=\"#\" callbackUrl=\"https://49af2317.ngrok.io/api/v1.1/voice/callback\">'\n menu_text += '<Say>\"Thank you for calling. Press 0 to talk to sales, 1 to talk to support or 2 to hear this message again.\"</Say>'\n menu_text += '</GetDigits>'\n menu_text += '<Say>\"Thank you for calling. Good bye!\"</Say>'\n menu_text += '</Response>'\n\n # Print the response onto the page so that our gateway can read it\n return respond(menu_text)\n\n else:\n # Read in call details (duration, cost). This flag is set once the call is completed.\n # Note that the gateway does not expect a response in thie case\n\n duration = request.get('durationInSeconds')\n currencyCode = request.get('currencyCode')\n amount = request.get('amount')\n\n # You can then store this information in the database for your records\t\t\t\t\t\n```\ne) When the user enters the digit - in this case 0, 1 or 2, this digit is submitted to another route also in our views.py file which lives at https://49af2317.ngrok.io/api/v1.1/voice/menu and which switches between the various dtmf digits to make an outgoing call to the right recipient, who will be bridged to speak to the person currently listening to music on hold. We specify this music with the ringtone flag as follows: ringbackTone=\"url_to/static/media/SautiFinaleMoney.mp3\"\n\n```python\n @ussd.route('/voice/menu')\n def voice_menu():\n \"\"\"\n When the user enters the digit - in this case 0, 1 or 2, this route \n switches between the various dtmf digits to \n make an outgoing call to the right recipient, who will be \n bridged to speak to the person currently listening to music on hold. \n We specify this music with the ringtone flag as follows: \n ringbackTone=\"url_to/static/media/SautiFinaleMoney.mp3\"\n \"\"\"\n \n # 1. Receive POST from AT\n isActive = request.get('isActive')\n callerNumber = request.get('callerNumber')\n dtmfDigits = request.get('dtmfDigits')\n sessionId = request.get('sessionId')\n # Check if isActive=1 to act on the call or isActive=='0' to store the\n # result\n \n if (isActive == '1'):\n # 2a. Switch through the DTMFDigits\n if (dtmfDigits == \"0\"):\n # Compose response - talk to sales-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Sales.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n \n # Print the response onto the page so that our gateway can read it\n return respond(response)\n \n elif (dtmfDigits == \"1\"):\n # 2c. Compose response - talk to support-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Support.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n \n # Print the response onto the page so that our gateway can read it\n return respond(response)\n elif (dtmfDigits == \"2\"):\n # 2d. Redirect to the main IVR-\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Redirect>{}</Redirect>'.format(url_for('voice_callback'))\n response += '</Response>'\n \n # Print the response onto the page so that our gateway can read it\n return respond(response)\n else:\n # 2e. By default talk to support\n response = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n response += '<Response>'\n response += '<Say>Please hold while we connect you to Support.</Say>'\n response += '<Dial phoneNumbers=\"[email protected]\" ringbackTone=\"{}\"/>'.format(url_for('media', path='SautiFinaleMoney.mp3'))\n response += '</Response>'\n \n # Print the response onto the page so that our gateway can read it\n return respond(response)\n else:\n # 3. Store the data from the POST\n durationInSeconds = request.get('durationInSeconds')\n direction = request.get('direction')\n amount = request.get('amount')\n callerNumber = request.get('callerNumber')\n destinationNumber = request.get('destinationNumber')\n sessionId = request.get('sessionId')\n callStartTime = request.get('callStartTime')\n isActive = request.get('isActive')\n currencyCode = request.get('currencyCode')\n status = request.get('status')\n\n # 3a. Store the data, write your SQL statements here-\n```\n\nWhen the agent/person picks up, the conversation can go on.\n\n- That is basically our application! Happy coding!" }, { "alpha_fraction": 0.6909871101379395, "alphanum_fraction": 0.7038626670837402, "avg_line_length": 20.18181800842285, "blob_id": "c131da40342bdaef2016b7b7c37e4d6132ae67d0", "content_id": "256f21436d5c1e35df10890412d7cf74ec3b908a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "permissive", "max_line_length": 51, "num_lines": 11, "path": "/app/ussd/utils.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from flask import make_response\n\n\ndef iso_format(amount):\n return \"KES{}\".format(amount)\n\n\ndef respond(response):\n response = make_response(response, 200)\n response.headers['Content-Type'] = \"text/plain\"\n return response\n" }, { "alpha_fraction": 0.5568581223487854, "alphanum_fraction": 0.5736615657806396, "avg_line_length": 42.37288284301758, "blob_id": "2426012562118a4e6efd1fef7901297dc2ff16c7", "content_id": "a3c472831e0832c2f9aef584d640d08ceaa2de72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2559, "license_type": "permissive", "max_line_length": 107, "num_lines": 59, "path": "/app/ussd/airtime.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from .base_menu import Menu\nfrom .tasks import buyAirtime\n\n\nclass Airtime(Menu):\n def get_phone_number(self): # 10\n if self.user_response == '1':\n self.session[\"phone_number\"] = self.phone_number\n menu_text = \"Buy Airtime\\nPlease Enter Amount(Ksh)\"\n self.session['level'] = 12\n return self.ussd_proceed(menu_text)\n if self.user_response == '2':\n menu_text = \"Buy Airtime\\nPlease enter phone number as (+2547XXXXXXXX)\"\n self.session['level'] = 11\n return self.ussd_proceed(menu_text)\n return self.home()\n\n def another_number(self): # 11\n if not self.user_response.startswith(\"+\"):\n menu_text = \"Buy Airtime\\nPlease enter a valid phone number as (+2547XXXXXXXX)\"\n return self.ussd_proceed(menu_text)\n self.session['phone_number'] = self.phone_number\n menu_text = \"Buy Airtime\\nPlease Enter Amount(Ksh)\"\n self.session['level'] = 12\n return self.ussd_proceed(menu_text)\n\n def get_amount(self, amount=None): # level 12\n if int(self.user_response) < 5 and amount is None:\n menu_text = \"Buy Airtime\\nYou can only buy airtime above Ksh 5.00. Please enter amount\"\n return self.ussd_proceed(menu_text)\n if amount is None:\n self.session['amount'] = int(self.user_response)\n self.session['level'] = 13\n menu_text = \"Purchase Ksh{:.2f} worth of airtime for {}\\n\".format(self.session.get('amount'),\n self.session.get(\"phone_number\"))\n menu_text += \"1.Confirm\\n2.Cancel\"\n return self.ussd_proceed(menu_text)\n\n def confirm(self): # 13\n if self.user_response == \"1\":\n menu_text = \"Please wait as we load your account.\"\n buyAirtime.apply_async(\n kwargs={'phone_number': self.session['phone_number'], 'amount': self.session['amount'],\n 'account_phoneNumber': self.user.phone_number})\n return self.ussd_end(menu_text)\n if self.user_response == \"2\":\n menu_text = \"Thank you for doing business with us\"\n return self.ussd_end(menu_text)\n return self.get_amount(amount=True)\n\n def execute(self):\n level = self.session.get('level')\n menu = {\n 10: self.get_phone_number,\n 11: self.another_number,\n 12: self.get_amount,\n 13: self.confirm\n }\n return menu.get(level, self.home)()\n" }, { "alpha_fraction": 0.6222537159919739, "alphanum_fraction": 0.6243798732757568, "avg_line_length": 29.673913955688477, "blob_id": "0f27b683068fc813006fcc770460889d9ff8a4b9", "content_id": "60a4ec64e5811fcf8f6445148097def7c069dc8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1411, "license_type": "permissive", "max_line_length": 114, "num_lines": 46, "path": "/app/ussd/decorators.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import json\nfrom functools import wraps\nimport uuid\n\nfrom flask import g, request\n\nfrom . import ussd\nfrom .. import redis\nfrom ..models import User, AnonymousUser\n\n\ndef validate_ussd_user(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n \"\"\"Get user trying to access to USSD session and the session id and adds them to the g request variable\"\"\"\n # get user response\n text = request.values.get(\"text\", \"default\")\n text_array = text.split(\"*\")\n # get phone number\n phone_number = request.values.get(\"phoneNumber\")\n # get session id\n session_id = request.values.get(\"sessionId\") or str(uuid.uuid4())\n # get user\n user = User.by_phoneNumber(phone_number) or AnonymousUser()\n # get session\n session = redis.get(session_id)\n if session is None:\n session = {\"level\": 0, \"session_id\": session_id}\n redis.set(session_id, json.dumps(session))\n else:\n session = json.loads(session.decode())\n # add user, response and session to the request variable g\n g.user_response = text_array[len(text_array) - 1]\n g.session = session\n g.current_user = user\n g.phone_number = phone_number\n g.session_id = session_id\n return func(*args, **kwargs)\n\n return wrapper\n\n\[email protected]_app_request\n@validate_ussd_user\ndef before_request():\n pass\n" }, { "alpha_fraction": 0.5493975877761841, "alphanum_fraction": 0.5638554096221924, "avg_line_length": 31.763158798217773, "blob_id": "405c5c27c53e21c5b49711a61b84d3cbb14411b7", "content_id": "3c2274b28c8640c858970daa19b6bdb511ae586b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "permissive", "max_line_length": 103, "num_lines": 38, "path": "/app/ussd/home.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from .base_menu import Menu\nfrom .tasks import check_balance\n\n\nclass LowerLevelMenu(Menu):\n \"\"\"serves the home menu\"\"\"\n def deposit(self): # 1\n menu_text = \"Enter amount you wish to deposit?\\n\"\n self.session['level'] = 50\n return self.ussd_proceed(menu_text)\n\n def withdraw(self): # 2\n menu_text = \"Enter amount you wish to withdraw?\\n\"\n self.session['level'] = 40\n return self.ussd_proceed(menu_text)\n\n def buy_airtime(self): # level 10\n menu_text = \"Buy Airtime\\n\" \\\n \"1. My Number\\n\" \\\n \"2. Another Number\\n\" \\\n \"0. Back\"\n self.session['level'] = 10\n return self.ussd_proceed(menu_text)\n\n def check_balance(self): # 4\n menu_text = \"Please wait as we load your account\\nYou will receive an SMS notification shortly\"\n # send balance async\n check_balance.apply_async(kwargs={'user_id': self.user.id})\n return self.ussd_end(menu_text)\n\n def execute(self):\n menus = {\n '1': self.deposit,\n '2': self.withdraw,\n '3': self.buy_airtime,\n '4': self.check_balance\n }\n return menus.get(self.user_response, self.home)()\n" }, { "alpha_fraction": 0.5687999725341797, "alphanum_fraction": 0.5824000239372253, "avg_line_length": 34.74285888671875, "blob_id": "d669bf919b8916503b58b10fa1ff9db443409e28", "content_id": "9ef7ba182c0193cb26477282a5985ad035dc6863", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1250, "license_type": "permissive", "max_line_length": 104, "num_lines": 35, "path": "/app/ussd/withdraw.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from .base_menu import Menu\nfrom .tasks import make_B2Crequest\n\n\nclass WithDrawal(Menu):\n def get_amount(self): # 40\n try:\n amount = int(self.user_response)\n except ValueError as exc:\n return self.home()\n self.session['amount'] = int(self.user_response)\n self.session['level'] = 51\n menu_text = \"Withdraw Ksh{:.2f} from your Wallet\\n\".format(self.session.get('amount'))\n menu_text += \"1.Confirm\\n2.Cancel\"\n return self.ussd_proceed(menu_text)\n\n def confirm(self): # 41\n amount = self.session.get('amount')\n if self.user_response == \"1\":\n menu_text = \"We are sending your withrawal deposit of KES{} shortly\".format(amount)\n make_B2Crequest.apply_async(\n kwargs={'phone_number': self.user.phone_number, 'amount': amount, 'reason': 'Withdraw'})\n return self.ussd_end(menu_text)\n\n if self.user_response == \"2\":\n menu_text = \"Thank you for doing business with us\"\n return self.ussd_end(menu_text)\n return self.home()\n\n def execute(self):\n menu = {\n 40: self.get_amount,\n 41: self.confirm\n }\n return menu.get(self.level, self.home)()" }, { "alpha_fraction": 0.5654664635658264, "alphanum_fraction": 0.579378068447113, "avg_line_length": 32.94444274902344, "blob_id": "8fec6c55c934827051ffb7e35ef3a0fca0242a1b", "content_id": "fd69f812f4878e4db8359427699770c020002f8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 106, "num_lines": 36, "path": "/app/ussd/deposit.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from .base_menu import Menu\nfrom .tasks import makeC2Brequest\n\n\nclass Deposit(Menu):\n def get_amount(self): # 50\n try:\n amount = int(self.user_response)\n except ValueError as exc:\n return self.home()\n self.session['amount'] = int(self.user_response)\n self.session['level'] = 51\n menu_text = \"Deposit Ksh{:.2f} to your Wallet\\n\".format(self.session.get('amount'))\n menu_text += \"1.Confirm\\n2.Cancel\"\n return self.ussd_proceed(menu_text)\n\n def confirm(self): # 51\n amount = self.session.get('amount')\n if self.user_response == \"1\":\n menu_text = \"We are sending you an Mpesa Checkout for deposit of KES{} shortly\".format(amount)\n makeC2Brequest.apply_async(\n kwargs={'phone_number': self.user.phone_number, 'amount': amount})\n return self.ussd_end(menu_text)\n\n if self.user_response == \"2\":\n menu_text = \"Thank you for doing business with us\"\n return self.ussd_end(menu_text)\n\n return self.home()\n\n def execute(self):\n menu = {\n 50: self.get_amount,\n 51: self.confirm\n }\n return menu.get(self.level)()\n" }, { "alpha_fraction": 0.6091617941856384, "alphanum_fraction": 0.6130604147911072, "avg_line_length": 34.379310607910156, "blob_id": "ad0741ee2367f1d8deb3726f94c59f728dec9e95", "content_id": "3cdcc16bd8c36f6537f0638798456e84ae47d218", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 108, "num_lines": 29, "path": "/app/ussd/register.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from .base_menu import Menu\nfrom ..models import User\n\n\nclass RegistrationMenu(Menu):\n \"\"\"Serves registration callbacks\"\"\"\n\n def get_number(self):\n # insert user's phone number\n self.session[\"level\"] = 21\n menu_text = \"Please choose a username\"\n return self.ussd_proceed(menu_text)\n\n def get_username(self):\n username = self.user_response\n if username or not User.by_username(username): # check if user entered an option or username exists\n self.user = User.create(username=username, phone_number=self.phone_number)\n self.session[\"level\"] = 0\n # go to home\n return self.home()\n else: # Request again for name - level has not changed...\n menu_text = \"Username is already in use. Please enter your username \\n\"\n return self.ussd_proceed(menu_text)\n\n def execute(self):\n if self.session[\"level\"] == 0:\n return self.get_number()\n else:\n return self.get_username()\n" }, { "alpha_fraction": 0.6571782231330872, "alphanum_fraction": 0.6621286869049072, "avg_line_length": 26.545454025268555, "blob_id": "2b6b97ab46ba5be49bb0245d94bb885d04e5493f", "content_id": "0f62c0bb15d58db324bbcb4bf4a551bd748184e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2424, "license_type": "permissive", "max_line_length": 121, "num_lines": 88, "path": "/config.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "# usr/bin/python\n\"\"\"\nConfiguration for the USSD application\n\"\"\"\nimport os\n\nbasedir = os.path.abspath(os.path.dirname(__file__)) # base directory\n\n\nclass Config:\n \"\"\"General configuration variables\"\"\"\n\n # flask specific application configurations\n DEBUG = False\n TESTING = False\n\n # security credentials\n SECRET_KEY = b\"I\\xf9\\x9cF\\x1e\\x04\\xe6\\xfaF\\x8f\\xe6)-\\xa432\" # use a secure key\n CSRF_ENABLED = True\n\n # persistance layer configs - configure database, redis and celery backend\n CELERY_BROKER_URL = os.getenv('REDIS_URL', \"redis://localhost:6379\")\n CELERY_RESULT_BACKEND = os.getenv('REDIS_URL', \"redis://localhost:6379\")\n REDIS_URL = os.getenv('REDIS_URL', \"redis://localhost:6379\")\n SQLALCHEMY_DATABASE_URI = os.getenv(\"SQLALCHEMY_DATABASE_URI\") or 'sqlite:///' + os.path.join(basedir, 'data.sqlite')\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_COMMIT_ON_TEARDOWN = True\n SSL_DISABLE = True\n CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']\n\n # africastalking credentials\n AT_ENVIRONMENT = os.getenv('AT_ENVIRONMENT')\n AT_USERNAME = os.getenv('AT_USERNAME')\n AT_APIKEY = os.getenv('AT_APIKEY')\n APP_NAME = 'nerds-microfinance-ussd-application'\n\n # application credentials\n ADMIN_PHONENUMBER = os.getenv('ADMIN_PHONENUMBER')\n\n @classmethod\n def init_app(cls, app):\n pass\n\n\nclass DevelopmentConfig(Config):\n \"\"\"\n Configuration variables when in development mode\n \"\"\"\n \"\"\"Development Mode configuration\"\"\"\n DEBUG = True\n CSRF_ENABLED = False\n\n @classmethod\n def init_app(cls, app):\n Config.init_app(app)\n\n\nclass ProductionConfig(Config):\n \"\"\"Production Mode configuration\"\"\"\n CSRF_ENABLED = True\n\n @classmethod\n def init_app(cls, app):\n Config.init_app(app)\n # handle proxy server errors\n from werkzeug.contrib.fixers import ProxyFix\n app.wsgi_app = ProxyFix(app.wsgi_app)\n\n SSL_DISABLE = bool(os.environ.get('SSL_DISABLE'))\n\n\nclass TestingConfig(Config):\n \"\"\"\n Testing configuration variables\n \"\"\"\n TESTING = True\n # use a temporary database for testing\n SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \\\n 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'testing': TestingConfig,\n 'production': ProductionConfig,\n 'default': DevelopmentConfig\n\n}\n" }, { "alpha_fraction": 0.5740457773208618, "alphanum_fraction": 0.5816794037818909, "avg_line_length": 21.20339012145996, "blob_id": "5300a7a8ab3c42664164b2ece4214a81000c8ea6", "content_id": "e9fe75ffb835e1ffc012fd1f27478712095509e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1310, "license_type": "permissive", "max_line_length": 70, "num_lines": 59, "path": "/app/models.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "# from app.ussd.utils import kenya_time\n\nfrom .database import db, AuditColumns\nfrom .util import kenya_time\n\n\nclass User(AuditColumns, db.Model):\n __tablename__ = 'users'\n id = db.Column(\n db.Integer,\n primary_key=True\n )\n username = db.Column(\n db.String(64),\n index=True\n )\n phone_number = db.Column(\n db.String(64),\n unique=True,\n index=True,\n nullable=False\n )\n account = db.Column(\n db.Float,\n default=10.00\n )\n reg_date = db.Column(\n db.DateTime,\n default=kenya_time\n )\n validation = db.Column(\n db.String,\n default=\"\"\n )\n city = db.Column(db.String(32), default=\"\")\n\n def __repr__(self):\n return \"User {}\".format(self.name)\n\n @staticmethod\n def by_phoneNumber(phone_number):\n return User.query.filter_by(phone_number=phone_number).first()\n\n @staticmethod\n def by_username(username):\n return User.query.filter_by(username=username).first()\n\n def deposit(self, amount):\n self.account += amount\n self.save()\n\n def withdraw(self, amount):\n if self.amount > self.account:\n raise Exception(\"Cannot overwithdraw\")\n self.account -= amount\n self.save()\n\n\nclass AnonymousUser(): pass\n" }, { "alpha_fraction": 0.6946216821670532, "alphanum_fraction": 0.7000911831855774, "avg_line_length": 32.24242401123047, "blob_id": "1e431b69fd3a291d891d421870f32094bceffc1c", "content_id": "568f5eb26ada12c98285a4df93150c3f8c0bf15a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "permissive", "max_line_length": 102, "num_lines": 33, "path": "/app/AfricasTalkingGateway.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import os\n\nfrom africastalking.AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException\n\n\nclass NerdsMicrofinanceGatewayGatewayException(AfricasTalkingGatewayException):\n pass\n\n\nclass NerdsMicrofinanceGateway(AfricasTalkingGateway):\n def __init__(self):\n pass # override default constructor\n\n @classmethod\n def init_app(cls, app):\n # this initialises an AfricasTalking Gateway instanse similar to calling\n # africastalking.gateway(username, apikey, environment)\n # this enables us to initialise one gateway to use throughout the app\n\n cls.username = app.config['AT_USERNAME']\n cls.apiKey = app.config['AT_APIKEY']\n cls.environment = app.config['AT_ENVIRONMENT']\n cls.HTTP_RESPONSE_OK = 200\n cls.HTTP_RESPONSE_CREATED = 201\n\n # Turn this on if you run into problems. It will print the raw HTTP response from our server\n if os.environ.get('APP_CONFIG') == 'development':\n cls.Debug = True\n else:\n cls.Debug = False\n\n\ngateway = NerdsMicrofinanceGateway()\n" }, { "alpha_fraction": 0.5825977325439453, "alphanum_fraction": 0.5895333886146545, "avg_line_length": 35.04545593261719, "blob_id": "1f340c4b8b785ba79bd2860d6bbe56c14ecb8b0f", "content_id": "48b630752f7f0f7aefb32840949bb48391052223", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1586, "license_type": "permissive", "max_line_length": 106, "num_lines": 44, "path": "/app/ussd/base_menu.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import json\n\nfrom flask import make_response, current_app\n\nfrom ..database import redis\n\n\nclass Menu(object):\n def __init__(self, session_id, session, user, user_response, phone_number=None, level=None):\n self.session = session\n self.session_id = session_id\n self.user = user\n self.user_response = user_response\n self.phone_number = phone_number\n self.level = level\n\n def execute(self):\n raise NotImplementedError\n\n def ussd_proceed(self, menu_text):\n redis.set(self.session_id, json.dumps(self.session))\n menu_text = \"CON {}\".format(menu_text)\n response = make_response(menu_text, 200)\n response.headers['Content-Type'] = \"text/plain\"\n return response\n\n def ussd_end(self, menu_text):\n redis.delete(self.session_id)\n menu_text = \"END {}\".format(menu_text)\n response = make_response(menu_text, 200)\n response.headers['Content-Type'] = \"text/plain\"\n return response\n\n def home(self):\n \"\"\"serves the home menu\"\"\"\n menu_text = \"Hello {}, welcome to {},\\n Choose a service\\n\".format(self.user.username,\n current_app.config['APP_NAME'])\n menu_text += \" 1. Deposit Money\\n\"\n menu_text += \" 2. Withdraw Money\\n\"\n menu_text += \" 3. Buy Airtime\\n\"\n menu_text += \" 4. Check Wallet Balance\\n\"\n self.session['level'] = 1\n # print the response on to the page so that our gateway can read it\n return self.ussd_proceed(menu_text)\n" }, { "alpha_fraction": 0.5433303713798523, "alphanum_fraction": 0.5470275282859802, "avg_line_length": 42.346153259277344, "blob_id": "1bfd1b94d0a6de63c22c41349892819ec46cb09e", "content_id": "7380b0b284d95d0c32f66823d08e7d931eb8af2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6762, "license_type": "permissive", "max_line_length": 113, "num_lines": 156, "path": "/app/ussd/tasks.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import uuid\n\nfrom flask import current_app\n\nfrom .utils import iso_format\nfrom .. import celery\nfrom .. import celery_logger\nfrom ..AfricasTalkingGateway import NerdsMicrofinanceGatewayGatewayException as AfricasTalkingGatewayException\nfrom ..AfricasTalkingGateway import gateway as africastalkinggateway\nfrom ..models import User\nfrom ..util import kenya_time\n\n\[email protected](ignore_result=True)\ndef check_balance(user_id):\n user = User.query.get(user_id)\n balance = iso_format(user.account)\n timestamp = kenya_time()\n transaction_cost = 0.00\n\n message = \"{status}. Your Wallet balance was {balance} on {date} at {time} \" \\\n \"Transaction cost {transaction_cost:0.2f}\\n\".format(balance=balance,\n status='Confirmed',\n transaction_cost=transaction_cost,\n date=timestamp.date().strftime('%d/%m/%y'),\n time=timestamp.time().strftime('%H:%M %p'))\n try:\n resp = africastalkinggateway.sendMessage(to_=user.phone_number, message_=message)\n celery_logger.warn(\"Balance message sent to {}\".format(user.phone_number))\n except AfricasTalkingGatewayException as exc:\n celery_logger.error(\"Could not send account balance message to {} \"\n \"error {}\".format(user.phone_number, exc))\n\n\[email protected](bind=True, ignore_result=True)\ndef buyAirtime(self, phone_number, amount, account_phoneNumber):\n \"\"\"\n :param phone_number: phone number to purchase airtime for\n :param amount: airtime worth\n :param account_phoneNumber: phone number linked to account making transaction\n :return:\n \"\"\"\n user = User.by_phoneNumber(account_phoneNumber)\n celery_logger.warn(\"{}\".format(amount))\n if not isinstance(amount, int):\n celery_logger.error(\"Invalid format for amount\")\n value = iso_format(amount)\n timestamp = kenya_time() # generate timestamp\n if phone_number.startswith('0'): # transform phone number to ISO format\n phone_number = \"+254\" + phone_number[1:]\n\n if user.account < amount: # check if user has enough cash\n message = \"Failed. There is not enough money in your account to buy airtime worth {amount}. \" \\\n \"Your Cash Value Wallet balance is {balance}\\n\".format(amount=value,\n balance=iso_format(user.account)\n )\n africastalkinggateway.sendMessage(to_=user.phone_number, message_=message)\n celery_logger.error(message)\n return False\n recepients = [{\"phoneNumber\": phone_number, \"amount\": value}]\n try:\n response = africastalkinggateway.sendAirtime(recipients_=recepients)[0] # get response from AT\n if response['status'] == 'Success':\n user.account -= amount\n else:\n celery_logger.error(\"Airtime wasn't sent to {}\".format(phone_number))\n except AfricasTalkingGatewayException as exc:\n celery_logger.error(\"Encountered an error while sending airtime: {}\".format(exc))\n\n\[email protected](bind=True, ignore_result=True)\ndef make_B2Crequest(self, phone_number, amount, reason):\n \"\"\"\n :param phone_number:\n :param amount:\n :param reason:\n :return:\n \"\"\"\n user = User.by_phoneNumber(phone_number)\n value = iso_format(amount)\n recipients = [\n {\"phoneNumber\": phone_number,\n \"currencyCode\": user.address.code.currency_code,\n \"amount\": amount,\n \"reason\": reason,\n \"metadata\": {\n \"phone_number\": user.phone_number,\n \"reason\": reason\n }\n }\n ]\n if user.account < amount:\n message = \"Failed. There is not enough money in your account to buy withdraw {amount}. \" \\\n \"Your Cash Value Wallet balance is {balance}\\n\".format(amount=value,\n balance=iso_format(user.account)\n )\n africastalkinggateway.sendMessage(to_=user.phone_number, message_=message)\n celery_logger.error(message)\n try:\n response = africastalkinggateway.mobilePaymentB2CRequest(productName_=current_app.config[\"PRODUCT_NAME\"],\n recipients_=recipients)[0]\n # withdrawal request\n transaction_fees = 0.00\n africastalkinggateway.sendMessage(to_=user.phone_number,\n message_=\"Confirmed. \"\n \"You have withdrwan {amount} from your Wallet to your\"\n \"Mpesa account.\"\n \"Your new wallet balance is {balance}.\"\n \"Transaction fee is {fees}\"\n \"\".format(amount=value,\n fees=iso_format(transaction_fees),\n balance=iso_format(user.balance)\n )\n )\n\n\n except AfricasTalkingGatewayException as exc:\n celery_logger.error(\"B2C request experienced an errorr {}\".format(exc))\n raise self.retry(exc=exc, countdown=5)\n\n\[email protected](bind=True, ignore_result=True)\ndef makeC2Brequest(self, phone_number, amount):\n metadata = {\n \"transaction_id\": str(uuid.uuid1()),\n \"reason\": 'Deposit'\n }\n # get user\n user = User.by_phoneNumber(phone_number)\n # get currency code\n currency_code = 'KES'\n timestamp = kenya_time()\n transaction_id = metadata.get('transaction_id')\n\n try:\n payments = africastalkinggateway.initiateMobilePaymentCheckout(\n productName_=current_app.config['PRODUCT_NAME'],\n currencyCode_=currency_code,\n amount_=amount,\n metadata_=metadata,\n providerChannel_=\"9142\",\n phoneNumber_=phone_number\n )\n user.account += amount\n user.save()\n celery_logger.warn(\n \"New transaction id: {} logged\".format(\n transaction_id\n )\n )\n except AfricasTalkingGatewayException as exc:\n celery_logger.error(\n \"Could not complete transaction {exc}\".format(\n exc=exc\n )\n )\n" }, { "alpha_fraction": 0.6502395868301392, "alphanum_fraction": 0.6522929668426514, "avg_line_length": 24.189655303955078, "blob_id": "a1c1ebe23b5a3ef636e799b9f95ed20b2e0566bb", "content_id": "25a5027a60ace4c356777b71f94bf7dac761d608", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 78, "num_lines": 58, "path": "/manage.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "# -*-coding:utf-8-*-\n\"\"\"Main application script\"\"\"\n\nimport os\n\nimport click\nfrom flask_migrate import Migrate\n\nfrom app import create_app, db\nfrom app.models import User\n\napp = create_app(os.getenv('APP_CONFIG') or 'default')\nmigrate = Migrate(app, db)\n\n\n# set up code coverage\nCOV = None\nif os.environ.get('APP_COVERAGE'):\n import coverage\n\n COV = coverage.coverage(branch=True, include='app/*')\n COV.start()\n\n\[email protected]_context_processor\ndef make_shell_context():\n return dict(app=app, db=db, User=User)\n\n\[email protected]()\ndef initdb():\n \"\"\"Initialize the database.\"\"\"\n click.echo('Init the db')\n from flask_migrate import upgrade\n # migrate database to latest revision\n upgrade()\n\n\[email protected]()\ndef test(coverage=False):\n \"\"\"Run the unit tests.\"\"\"\n if coverage and not os.environ.get('FLASK_COVERAGE'):\n import sys\n os.environ['FLASK_COVERAGE'] = '1'\n os.execvp(sys.executable, [sys.executable] + sys.argv)\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n if COV:\n COV.stop()\n COV.save()\n print(\"Coverage Summary:\")\n COV.report()\n basedir = os.path.abspath(os.path.dirname(__file__))\n covdir = os.path.join(basedir, 'temp/coverage')\n COV.html_report(directory=covdir)\n print('HTML version: file://{covdir}index.html'.format(covdir=covdir))\n COV.erase()\n" }, { "alpha_fraction": 0.6196318864822388, "alphanum_fraction": 0.6211656332015991, "avg_line_length": 27.34782600402832, "blob_id": "e1c96814fcfb21cc572030db4f99881e5d37f795", "content_id": "b00e0096e0ee9d87c38c1ae50e85e2a065fd06b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "permissive", "max_line_length": 98, "num_lines": 23, "path": "/app/util.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "import datetime\nimport logging\nimport logging.config\nimport os\n\nimport yaml\n\n\ndef kenya_time():\n return datetime.datetime.utcnow() + datetime.timedelta(hours=3)\n\n\ndef setup_logging(file_name=\"app_logger.yaml\", default_level=logging.INFO, logger_file_path=None):\n \"\"\"\n Logging configuration.\n \"\"\"\n if logger_file_path is None:\n path = os.path.abspath(os.path.join(os.path.dirname(__file__),\n \"../\", file_name))\n if os.path.exists(logger_file_path):\n with open(logger_file_path, 'rt') as f:\n config = yaml.safe_load(f.read())\n logging.config.dictConfig(config)\n" }, { "alpha_fraction": 0.4928457736968994, "alphanum_fraction": 0.6931637525558472, "avg_line_length": 16, "blob_id": "0d76cf8d3eabc638d17d5b3f105805005ce9abaf", "content_id": "0a15063be1073081dc71de3476cdf597fbc9625e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 629, "license_type": "permissive", "max_line_length": 26, "num_lines": 37, "path": "/requirements.txt", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "africastalking==1.2.0\nAfricastalkingGateway==2.0\nalembic==1.4.1\namqp==2.5.2\nbilliard==3.6.3.0\ncelery==4.4.1\ncertifi==2019.11.28\nchardet==3.0.4\nclick==7.1.1\ncontextlib2==0.5.5\nFlask==1.1.1\nFlask-Login==0.5.0\nFlask-Migrate==2.5.2\nflask-redis==0.4.0\nFlask-SQLAlchemy==2.4.1\nFlask-SSLify==0.1.5\ngunicorn==20.0.4\nidna==2.9\nitsdangerous==1.1.0\nJinja2==2.11.1\nkombu==4.6.8\nMako==1.1.2\nMarkupSafe==1.1.1\n# pkg-resources==0.0.0\npython-dateutil==2.8.1\npython-dotenv==0.12.0\npython-editor==1.0.4\npytz==2019.3\nPyYAML==5.3\nredis==3.4.1\nrequests==2.23.0\nschema==0.7.1\nsix==1.14.0\nSQLAlchemy==1.3.13\nurllib3==1.25.8\nvine==1.3.0\nWerkzeug==1.0.0\n" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6431451439857483, "avg_line_length": 25.810810089111328, "blob_id": "07910040b5a39db5af7b560c303607cd0af98b9b", "content_id": "1032b07cef612e46bd631bdb88743fe520d5f57b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 992, "license_type": "permissive", "max_line_length": 86, "num_lines": 37, "path": "/app/database.py", "repo_name": "MikeSoft007/idlUSSD", "src_encoding": "UTF-8", "text": "from flask_redis import FlaskRedis\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom .util import kenya_time\n\nredis = FlaskRedis()\ndb = SQLAlchemy()\n\n\nclass CRUDMixin(object):\n def __repr__(self):\n return \"<{}>\".format(self.__class__.__name__)\n\n @classmethod\n def create(cls, **kwargs):\n instance = cls(**kwargs)\n return instance.save()\n\n def save(self):\n \"\"\"Saves object to database\"\"\"\n db.session.add(self)\n db.session.commit()\n return self\n\n def delete(self):\n \"\"\"deletes object from db\"\"\"\n db.session.delete(self)\n db.session.commit()\n return self\n\n\nclass AuditColumns(CRUDMixin):\n created_by = db.Column(db.String(128), nullable=True)\n created_date = db.Column(db.DateTime, default=kenya_time)\n last_edited_date = db.Column(db.DateTime, onupdate=kenya_time, default=kenya_time)\n last_edited_by = db.Column(db.String(128), nullable=True)\n active = db.Column(db.Boolean, default=False)\n" } ]
20
ihenisa1972/Python_Repo_CircleCI_Archive
https://github.com/ihenisa1972/Python_Repo_CircleCI_Archive
42939717b375f28cad38854b754c340e57cfc66a
be6662865493c5acf7bc394073bb50d86488cdea
d1ed4188b57d48d4655eb353dd9ea7f7900952f4
refs/heads/master
2020-04-18T21:16:18.120594
2019-01-28T00:39:40
2019-01-28T00:39:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6386554837226868, "alphanum_fraction": 0.6554622054100037, "avg_line_length": 16.850000381469727, "blob_id": "87abf0a4fa99a8628776db77a425793e80e751b9", "content_id": "bc1271ff276de3da0dc39de618c6a807535318c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 39, "num_lines": 20, "path": "/Python_Repo_CircleCI/test_calculator.py", "repo_name": "ihenisa1972/Python_Repo_CircleCI_Archive", "src_encoding": "UTF-8", "text": "\"\"\"\nUnit tests for the calculator library\n\"\"\"\n\n\ndef add(first_term, second_term):\n return first_term + second_term\n\n\ndef subtract(first_term, second_term):\n return first_term - second_term\n\n\nclass TestCalculator:\n\n def test_addition(self):\n assert 4 == self.add(2, 2)\n\n def test_subtraction(self):\n assert 2 == self.subtract(4, 2)\n" } ]
1
SarthakJShetty/pyResearchInsights
https://github.com/SarthakJShetty/pyResearchInsights
9c6c6220db1173badc13f6f9a0b9201581d5a2b8
28becf606061640c34ff1864a7e14c6cf9fd54ab
2441a6c18e822de809293d33ae7da9915a5be159
refs/heads/master
2023-04-10T10:19:51.081525
2021-12-19T02:42:12
2021-12-19T02:42:12
294,472,065
26
8
MIT
2020-09-10T17:04:46
2022-08-29T00:47:07
2022-08-28T08:56:24
Python
[ { "alpha_fraction": 0.8759689927101135, "alphanum_fraction": 0.8759689927101135, "avg_line_length": 63.66666793823242, "blob_id": "3d546deb0b4f7d3a3499fb842013ec80ae0a72fe", "content_id": "d829005a85d9b239718cb78b13b417abb3977688", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "permissive", "max_line_length": 93, "num_lines": 6, "path": "/pyResearchInsights/__init__.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "from pyResearchInsights.Scraper import scraper_main\nfrom pyResearchInsights.Cleaner import cleaner_main\nfrom pyResearchInsights.Analyzer import analyzer_main\nfrom pyResearchInsights.NLP_Engine import nlp_engine_main\nfrom pyResearchInsights.common_functions import pre_processing, arguments_parser, end_process\nfrom pyResearchInsights.system_functions import tarballer, rm_original_folder" }, { "alpha_fraction": 0.7298387289047241, "alphanum_fraction": 0.7328628897666931, "avg_line_length": 44.39215850830078, "blob_id": "e0e52a6d2e3c87a788ab7f774310aa63bdc93907", "content_id": "ffe903d307f26fcb5da27a33f87999aee75a2e99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6944, "license_type": "permissive", "max_line_length": 144, "num_lines": 153, "path": "/pyResearchInsights/common_functions.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''Hello! This script contains functions that are resued by other pieces of code and scripts belonging to this\nproject as well.\n\nCheckout the README.md for more details regarding the project itself.\n\nSarthak J Shetty\n12/09/2018'''\n\n'''datetime is used while building the database logs'''\nfrom datetime import datetime\n'''Importing OS functions to build the folders for the LOG run here as well'''\nimport os\n'''Importing argparse to parse the keywords, then supplied to the Scraper.py code'''\nimport argparse\n\ndef status_logger(status_logger_name, status_key):\n\t'''Status logger to print and log details throught the running the program.\n\tDeclaring current_hour, current_minute & current_second.'''\n\tcurrent_hour = str(datetime.now().time().hour)\n\tcurrent_minute = str(datetime.now().time().minute)\n\tcurrent_second = str(datetime.now().time().second)\n\n\t'''Logging the complete_status_key and printing the complete_status_key'''\n\tcomplete_status_key = \"[INFO]\"+current_hour+\":\"+current_minute+\":\"+current_second+\" \"+status_key\n\tprint(complete_status_key)\n\tstatus_log = open(status_logger_name+'.txt', 'a')\n\tstatus_log.write(complete_status_key+\"\\n\")\n\tstatus_log.close()\n\ndef status_logger_creator(abstracts_log_name):\n\t'''This is a standalone status_logger and session_folder filename generator, if someone is using the Bias components as standalone functions'''\n\tsession_folder_name = abstracts_log_name.split('/')[-1]\n\tos.makedirs(session_folder_name)\n\tstatus_logger_name = session_folder_name+\"/\"+\"Status_Logger\"\n\treturn status_logger_name, session_folder_name\n\ndef pre_processing(keywords):\n\t'''This function contains all the pre-processing statements related to the running of the program, including:\n\t1. Abstracts LOG Name\n\t2. Status Logger Name'''\n\n\tif((type(keywords) == str)):\n\t\t'''If the user uses the function independently of the argument_parser() we need this to convert the keywords to a list of words'''\n\t\tkeywords = argument_formatter(keywords)\n\n\t'''Declaring the time and date variables here. Year, month, day, hours, minute & seconds.'''\n\trun_start_year = str(datetime.now().date().year)\n\trun_start_month = str(datetime.now().date().month)\n\trun_start_day = str(datetime.now().date().day)\n\trun_start_date = str(datetime.now().date())\n\trun_start_hour = str(datetime.now().time().hour)\n\trun_start_minute = str(datetime.now().time().minute)\n\trun_start_second = str(datetime.now().time().second)\n\n\t'''Keywords have to be written into the filename of the LOG that we are running'''\n\tfolder_attachement = \"\"\n\tif(len(keywords)==1):\n\t\tfolder_attachement = keywords[0]\n\telse:\n\t\tfor keyword_index in range(0, len(keywords)):\n\t\t\tif((keyword_index+1)==len(keywords)):\n\t\t\t\tfolder_attachement = folder_attachement+keywords[keyword_index]\n\t\t\telse:\n\t\t\t\tfolder_attachement = folder_attachement+keywords[keyword_index]+\"_\"\n\n\t'''Declaring the LOG folder and the abstract, abstract_id & status_logger files.'''\n\tlogs_folder_name = \"LOGS\"+\"/\"+\"LOG\"+\"_\"+run_start_date+'_'+run_start_hour+'_'+run_start_minute+\"_\"+folder_attachement\n\tabstracts_log_name = logs_folder_name+\"/\"+'Abstract_Database'+'_'+run_start_date+'_'+run_start_hour+'_'+run_start_minute\n\tstatus_logger_name = logs_folder_name+\"/\"+'Status_Logger'+'_'+run_start_date+'_'+run_start_hour+'_'+run_start_minute\n\n\t'''If the filename does not exist create the file in the LOG directory'''\n\tif not os.path.exists(logs_folder_name):\n\t\tos.makedirs(logs_folder_name)\n\t\n\t'''Creating the status_log and writing the session duration & date'''\n\tstatus_log = open(status_logger_name+'.txt', 'a')\n\tstatus_log.write(\"Session:\"+\" \"+run_start_day+\"/\"+run_start_month+\"/\"+run_start_year+\"\\n\")\n\tstatus_log.write(\"Time:\"+\" \"+run_start_hour+\":\"+run_start_minute+\":\"+run_start_second+\"\\n\")\n\tstatus_log.close()\n\n\tlogs_folder_name_status_key = \"Built LOG folder for session\"\n\tstatus_logger(status_logger_name, logs_folder_name_status_key)\n\n\treturn abstracts_log_name, status_logger_name\n\ndef keyword_url_generator(keywords_to_search):\n\t'''Reducing the long output of the pre_processing statement by offloading some of the scraper specific functions to another function'''\n\tif((type(keywords_to_search) == str)):\n\t\t'''If the user uses the function independently of the argument_parser() we need this to convert the keywords to a list of words'''\n\t\tkeywords = argument_formatter(keywords_to_search)\n\n\tquery_string = \"\"\n\tif (len(keywords)==1):\n\t\tquery_string = keywords[0]\n\telse:\n\t\tfor keyword_index in range(0, len(keywords)):\n\t\t\tif((keyword_index+1)==len(keywords)):\n\t\t\t\tquery_string = query_string+keywords[keyword_index]\n\t\t\telse:\n\t\t\t\tquery_string = query_string+keywords[keyword_index]+\"+\"\n\n\tstart_url = \"https://link.springer.com/search/page/\"\n\tabstract_url = 'https://link.springer.com'\n\n\t'''We take the keywords here and generate the URLs here'''\n\treturn start_url, abstract_url, query_string\n\ndef abstract_id_log_name_generator(abstracts_log_name):\n\t'''We use this function to generate the abstract_id_log_name from the abstracts_log_name'''\n\treturn abstracts_log_name.split('Abstract')[0] + 'Abstract_ID' + abstracts_log_name.split('Abstract')[1]+'_'\n\ndef argument_formatter(argument_string):\n\t'''We make this into a function so that we can use it across the pyResearchInsights stack'''\n\treturn argument_string.split()\n\ndef arguments_parser():\n\t'''This function is used to read the initial keyword that will be queried in Springer (for now).\n\tWe will be scrapping Science, Nature etc later, as long as generic URLs are supported.\n\tParses two arguments now:\n\ta) --keywords: This argument is the term that will be searched for in Springer.\n\tb) --trends: This argument provides the term whose research trend will be generated.\n\tc) --paper: This argument is triggered if the PDFs have to be downloaded as well.'''\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--keywords\", help=\"Keyword to search on Springer\", default=\"Tiger\")\n\tparser.add_argument(\"--trends\", help=\"Keywords to generate the trends histogram for\", default=\"Conservation\")\n\tparser.add_argument(\"--paper\", help=\"If papers have to be downloaded as well\", default=\"No\")\n\n\targuments = parser.parse_args()\n\tif arguments.keywords:\n\t\tkeywords = arguments.keywords\n\t'''The keyword if a string will be split and then be passed to the scraper functions'''\n\n\tkeywords = argument_formatter(keywords)\n\n\tif arguments.trends:\n\t\ttrends = arguments.trends\n\t'''The entire list of the abstract words will be lowered and hence trends term has to be\n\tlowered to obtain a match with those terms.'''\n\n\t'''if arguments.paper:\n\t\tpaper = arguments.paper'''\n\t'''If this argument is turned to Yes, then the papers will be downloaded as well'''\n\n\ttrends = trends.lower()\n\ttrends = argument_formatter(trends)\n\n\treturn keywords, trends\n\ndef end_process(status_logger_name):\n\t'''Self-explanatory, this function declares successful completion of the code.'''\n\tend_process_status_key=\"Process has successfully ended\"\n\tstatus_logger(status_logger_name, end_process_status_key)" }, { "alpha_fraction": 0.7402964234352112, "alphanum_fraction": 0.7482357025146484, "avg_line_length": 58.046875, "blob_id": "ed4508547d110a1e88b09e96b6d8cd5d5c160121", "content_id": "6fe0ab2da54f34eef888cc5a0033d93b127587d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11336, "license_type": "permissive", "max_line_length": 243, "num_lines": 192, "path": "/pyResearchInsights/Visualizer.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''Hello! This code code is part of the pyResearchInsights project.\nWe will be displaying the results from the NLP_Engine.py code here, using primarily using pyLDAvis library.\n\nCheck out the repository README.md for a high-level overview of the project and the objective.\n\nSarthak J. Shetty\n24/11/2018'''\n\nfrom pyResearchInsights.common_functions import argument_formatter, status_logger\n'''import matplotlib as plt'''\nimport matplotlib.pyplot as plt\n'''Library necessary to develop the html visualizations'''\nimport pyLDAvis\n'''Generating dictionary from the textual_data that is lemmatized'''\nfrom collections import Counter\n'''Importing pandas to create the dataframes to plot the histograms'''\nimport pandas as pd\n'''Importing the colormap functions using matplotlib'''\nfrom matplotlib import cm\n\ndef visualizer_generator(lda_model, corpus, id2word, logs_folder_name, status_logger_name):\n\t'''This code generates the .html file with generates the visualization of the data prepared.'''\n\tvisualizer_generator_start_status_key = \"Preparing the topic modeling visualization\"\n\tstatus_logger(status_logger_name, visualizer_generator_start_status_key)\n\n\t'''Here, we generate the actual topic modelling visualization from thghe model created by pyLDAvis'''\n\ttextual_data_visualization = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)\n\tpyLDAvis.save_html(textual_data_visualization, logs_folder_name+\"/\"+\"Data_Visualization_Topic_Modelling.html\")\n\n\t'''Here, we generate the order of topics according to the LDA visualization'''\n\ttopic_order = [textual_data_visualization[0].iloc[topic].name for topic in range(lda_model.num_topics)]\n\n\treturn topic_order\n\n\tvisualizer_generator_end_status_key = \"Prepared the topic modeling visualization\"+\" \"+logs_folder_name+\"/\"+\"Data_Visualization_Topic_Modelling.html\"\n\tstatus_logger(status_logger_name, visualizer_generator_end_status_key)\t\t\n\ndef topic_builder(lda_model, topic_order, num_topics, num_keywords, textual_data_lemmatized, logs_folder_name, status_logger_name):\n\t'''We generate histograms here to present the frequency and weights of the keywords of each topic and save them to the disc for further analysis'''\n\ttopic_builder_start_status_key = \"Preparing the frequency and weights vs keywords charts\"\n\tstatus_logger(status_logger_name, topic_builder_start_status_key)\n\n\t'''Setting the colormaps here to generate the num_topics charts that proceed'''\n\tcolorchart = cm.get_cmap('plasma', num_topics)\n\n\ttopics = lda_model.show_topics(num_topics = -1, num_words = num_keywords, formatted=False)\n\tdata_flat = [w for w_list in textual_data_lemmatized for w in w_list]\n\tcounter = Counter(data_flat)\n\n\t'''Generating a pandas dataframe that contains the word, topic_id, importance and word_count'''\n\tout = []\n\tfor i, topic in topics:\n\t for word, weight in topic:\n\t out.append([word, i , weight, counter[word]])\n\n\t'''We will use bits of this dataframe across this function'''\n\tdf = pd.DataFrame(out, columns=['word', 'topic_id', 'importance', 'word_count'])\n\n\tfor topic in topic_order:\n\t\t'''Progressively generating the figures comprising the weights and frequencies for each keyword in each topic'''\n\t\t_, ax = plt.subplots(1, 1, figsize=[20, 15])\n\t\tx_axis = [x_axis_element for x_axis_element in range(0, num_keywords)]\n\n\t\t'''Creating the x_axis labels here, which is the topic keywords'''\n\t\tx_axis_labels = [element for element in df.loc[df.topic_id==topic, 'word']]\n\t\ty_axis = [round(element, 2) for element in df.loc[df.topic_id==topic, 'word_count']]\n\n\t\t'''Here, we make sure that the y_axis labels are equally spaced, and that there are 10 of them'''\n\t\tword_count_list = [word_count for word_count in df.loc[df.topic_id==topic, 'word_count']]\n\t\tword_count_increment = (max(word_count_list)/10)\n\t\ty_axis_labels = [round(0 + increment*(word_count_increment)) for increment in range(0, 10)]\n\n\t\t'''Here, we make sure that the y_axis_twin labels are equally spaced, and that there are 10 of them''' \n\t\tword_importance_list = [word_count for word_count in df.loc[df.topic_id==topic, 'importance']]\n\t\tword_importance_increment = (max(word_importance_list)/10)\n\t\ty_axis_twin_labels = [0 + increment*(word_importance_increment) for increment in range(0, 10)]\n\n\t\tplt.xticks(x_axis, x_axis_labels, rotation=40, horizontalalignment='right', fontsize = 25)\n\t\tax.bar(x_axis, y_axis, width=0.5, alpha=0.3, color=colorchart.colors[topic], label=\"Word Count\")\n\t\tax.set_yticks(y_axis_labels)\n\t\tax.tick_params(axis = 'y', labelsize = 25)\n\t\tax.set_ylabel('Word Count', color=colorchart.colors[topic], fontsize = 25)\n\t\tax.legend(loc='upper left', fontsize = 20)\n\n\t\t'''Generating the second set of barplots here'''\t\t\n\t\tax_twin = ax.twinx()\n\t\tax_twin.bar(x_axis, df.loc[df.topic_id==topic, 'importance'], width=0.2, color=colorchart.colors[topic], label = \"Weight\")\n\t\tax_twin.set_ylabel('Weight', color=colorchart.colors[topic], fontsize = 25)\n\t\tax_twin.set_yticks(y_axis_twin_labels)\n\t\tax_twin.tick_params(axis='y', labelsize = 25)\n\t\tax_twin.legend(loc='upper right', fontsize = 20)\n\t\tplt.title('Topic Number: '+str(topic_order.index(topic) + 1), color=colorchart.colors[topic], fontsize=25)\n\n\t\t'''Saving each of the charts generated to the disc'''\t\t\n\t\tplt.savefig(logs_folder_name + '/FrequencyWeightChart_TopicNumber_' + str(topic_order.index(topic) + 1) + '.png')\n\n\ttopic_builder_end_status_key = \"Prepared the frequency and weights vs keywords charts\"\n\tstatus_logger(status_logger_name, topic_builder_end_status_key)\n\ndef trends_histogram(abstracts_log_name, logs_folder_name, trend_keywords, status_logger_name):\n\t'''This function is responsible for generating the histograms to visualizations the trends in research topics.'''\n\ttrends_histogram_start_status_key = \"Generating the trends histogram\"\n\tstatus_logger(status_logger_name, trends_histogram_start_status_key)\n\n\t'''What's happening here?\n\ta) trends_histogram receives the dictionary filename for the dictionary prepared by the Scraper code.\n\tb) Information is organized in a conventional key and value form; key=year, value=frequency.\n\tc) We extract the key from the dictionary and generate a new list comprising of the years in which the trend keywords occurs.\n\td) We calculate the max and min years in this new list and convert them to int and extract the complete set of years that lie between these extremes.\n\te) We cycle through the keys in the dictionary and extract frequency of occurrence for each year in the list of years.\n\tf) If the term does not appear in that year, then it's assigned zero (that's how dictionaries work).\n\tg) The two lists (list of years and list of frequencies) are submitted to the plot function for plotting.'''\n\n\t'''This list will hold the abstract years which contain occurrences of the word that we are investigating'''\n\tlist_of_years=[]\n\tlist_of_frequencies = []\n\n\t'''Accessing the dictionary data dumped by the Scraper code'''\n\tabstract_word_dictionary_file = open(abstracts_log_name + '_DICTIONARY.csv', 'r')\n\n\t'''Here we collect the dictionary data dumped by the Scraper code'''\n\tfor line in abstract_word_dictionary_file:\n\t\tlist_of_years.append(int(line.split(',')[0]))\n\t\tlist_of_frequencies.append(int(line.split(',')[1][:-1]))\n\n\t'''Tabulating the start and the ending years of appearence of the specific trend_keywords'''\n\tstarting_year = min(list_of_years)\n\tending_year = max(list_of_years)\n\n\t'''Recreating the actual dictionary here'''\n\tabstract_word_dictionary = {list_of_years[year]:list_of_frequencies[year] for year in range(0, len(list_of_years))}\n\n\t'''Generating a continuous list of years to be plotted from the abstracts collected'''\n\tlist_of_years_to_be_plotted = [year for year in range((starting_year), (ending_year)+1)]\n\t\n\tfrequencies_to_be_plotted = []\n\n\t'''Here we generate the corresponding frequencies for each of the years recorded'''\n\tfor year in range(starting_year, ending_year+1):\n\t\ttry:\n\t\t\tfrequencies_to_be_plotted.append(abstract_word_dictionary[year])\n\t\texcept KeyError:\n\t\t\tfrequencies_to_be_plotted.append(0)\n\n\t'''Here, we will generate a list of frequencies to be plotted along the Y axis, using the Y ticks function'''\n\ty_ticks_frequency = []\n\n\t'''Extracting the largest frequency value in the list to generate the Y ticks list'''\n\tmax_frequency_value = max(frequencies_to_be_plotted)\n\tfor frequency_element in range(0, max_frequency_value+1):\n\t\ty_ticks_frequency.append(frequency_element)\n\n\t'''Varying the size of the figure to accommodate the entire trends graph generated'''\n\tplt.figure(figsize=[15,10])\n\t'''Plotting the years along the X axis and the frequency along the Y axis'''\n\tplt.plot(list_of_years_to_be_plotted, frequencies_to_be_plotted)\n\t'''Plotting the frequencies again to make the frequency pivots visible'''\n\tplt.plot(list_of_years_to_be_plotted, frequencies_to_be_plotted, 'ro')\n\t'''Here, we are labeling each of the frequencies plotted to ensure better readability, instead of second-guessing Y axis values'''\n\tfor element in range(0, len(list_of_years_to_be_plotted)):\n\t\t'''Avoiding the unnecessary clutter in the visualization by removing text boxes for frequency=0'''\n\t\tif(frequencies_to_be_plotted[element]!=0):\n\t\t\tplt.text(list_of_years_to_be_plotted[element], frequencies_to_be_plotted[element], \"Frequency: \"+str(frequencies_to_be_plotted[element]), bbox=dict(facecolor='orange', alpha=0.3), horizontalalignment='right', verticalalignment='top',size=8)\n\n\t'''Adds a label to the element being represented across the Y-axis (frequency of occurrence)'''\n\tplt.ylabel(\"Frequency of occurrence:\"+\" \"+trend_keywords[0])\n\t'''Adds a label to the element being represented across the X-axis (years)'''\n\tplt.xlabel(\"Year of occurrence:\"+\" \"+trend_keywords[0])\n\t'''Adds an overall title to the trends chart'''\n\tplt.title(\"Trends Chart:\"+\" \"+trend_keywords[0])\n\t'''xticks() ensures that each and every year is plotted along the x axis and changing the rotation to ensure better readability'''\n\tplt.xticks(list_of_years_to_be_plotted, rotation=45)\n\t'''yticks() ensures that each and every frequency is plotted to ensure better readability in the resulting figure'''\n\tplt.yticks(y_ticks_frequency)\n\t'''Saves the graph generated to the disc for further analysis'''\n\tplt.savefig(logs_folder_name+\"/\"+\"Data_Visualization_Trends_Graph\"+\"_\"+trend_keywords[0]+\".png\")\n\n\ttrends_histogram_end_status_key = \"Generated the trends graph\"+\" \"+logs_folder_name+\"/\"+\"Data_Visualization_Trends_Graph\"+\"_\"+trend_keywords[0]+\".png\"\n\tstatus_logger(status_logger_name, trends_histogram_end_status_key)\n\ndef\tvisualizer_main(lda_model, corpus, id2word, textual_data_lemmatized, num_topics, num_keywords, logs_folder_name, status_logger_name):\n\tvisualizer_main_start_status_key = \"Entering the visualizer_main() code\"\n\tstatus_logger(status_logger_name, visualizer_main_start_status_key)\n\n\t'''This the main visualizer code. Reorging this portion of the code to ensure modularity later on as well.'''\n\ttopic_order = visualizer_generator(lda_model, corpus, id2word, logs_folder_name, status_logger_name)\n\n\t'''We generate histograms here to present the frequency and weights of the keywords of each topic'''\n\ttopic_builder(lda_model, topic_order, num_topics, num_keywords, textual_data_lemmatized, logs_folder_name, status_logger_name)\n\n\tvisualizer_main_end_status_key = \"Exiting the visualizer_main() code\"\n\tstatus_logger(status_logger_name, visualizer_main_end_status_key)" }, { "alpha_fraction": 0.7377378344535828, "alphanum_fraction": 0.7495200037956238, "avg_line_length": 50.385650634765625, "blob_id": "5b115806afd7022640718f607a385a870d10da7c", "content_id": "228caa66c325a68311e4f8b0d0db7c375e4112fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11460, "license_type": "permissive", "max_line_length": 657, "num_lines": 223, "path": "/README.md", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "# ***pyResearchInsights:*** An open-source Python package for scientific text analysis\n\n## Contents \n[1.0 Introduction](#introduction)\n\n[2.0 Installation](#installation)\n\n[3.0 How it works](#how)\n\n[4.0 Results](#results)\n\n[Citation](#cite)\n\n## <a title='Introduction' id='introduction'>1.0 Introduction</a>:\n\n- Academic publishing has risen 2-fold in the past ten years, making it nearly impossible to sift through a large number of papers and identify broad areas of research within disciplines.\n\n- In order to *understand* such vast volumes of research, there is a need for **automated content analysis (ACA)** tools.\n\n- However, existing ACA tools such are **expensive and lack in-depth analysis of publications**.\n\n- To address these issues, we developed ```pyResearchInsights``` an end-to-end, open-source, automated content analysis tool that:\n\t- **Scrapes** abstracts from scientific repositories,\n\t- **Cleans** the abstracts collected,\n\t- **Analyses** temporal frequency of keywords,\n\t- **Visualizes** themes of discussions using natural language processing.\n\n### <a title='About' id='about-the-project'>1.1 About</a>:\n\nThis project is a collaboration between <a title=\"Sarthak\" href=\"https://SarthakJShetty.github.io\" target=\"_blank\"> Sarthak J. Shetty</a>, from the <a title=\"Aerospace Engineering\" href=\"http://ces.iisc.ac.in\" >Center for Ecological Sciences</a>, <a title=\"IISc\" href=\"https://iisc.ac.in\" target=\"_blank\"> Indian Institute of Science</a> and <a title=\"Vijay\" href=\"https://evolecol.weebly.com/\" target=\"_blank\"> Vijay Ramesh</a>, from the <a title=\"E3B\" href=\"http://e3b.columbia.edu/\" target=\"_blank\">Department of Ecology, Evolution & Environmental Biology</a>, <a href=\"https://www.columbia.edu/\" title=\"Columbia University\" target=\"_blank\">Columbia University</a>.\n\n## <a title='Installation' id='installation'>2.0 Installation</a>:\n\nTo install the package using ```pip```, use the command:\n\n```bash\npip install pyResearchInsights\n```\n\n**Note:** `pyResearchInsights` requires `python 3.7` to run. If you're unsure about the local dependencies on your system, please use package on [Google Colab](https://colab.research.google.com/) or create a `python 3.7` [Conda](https://docs.conda.io/en/latest/) environment and install `pyResearchInsights` inside that environment.\n\nSince ```pyResearchInsights``` is available on ```pip```, it can be run on [Google Colab](https://colab.research.google.com/drive/1gZjOKr5pfwVMuxCSaGYw20ldFpV4gVws?usp=sharing) as well where users can leverage Google's powerful CPU and GPU hardware.\n\n[![Run on Google Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1gZjOKr5pfwVMuxCSaGYw20ldFpV4gVws?usp=sharing)\n\n[![Cite This!](https://zenodo.org/badge/294472065.svg)](https://onlinelibrary.wiley.com/doi/10.1002/ece3.8098)\n\n## <a title='How it works' id='how'>3.0 How it works</a>:\n\n<img src=\"https://raw.githubusercontent.com/SarthakJShetty/Bias/master/assets/Bias.png\" alt=\"Bias Pipeline\">\n\n<i>***Figure 3.1*** Diagrammatic representation of the pipeline.</i>\n\n```pyResearchInsights``` is modular in nature. Each part of the package can be run independently or part of a larger pipeline.\n\n### <a title='Example Pipeline' id='how-example'>Example Pipeline</a>:\n\nThis is an example pipeline, where we scrape abstracts from Springer pertaining to the conservation efforts in the Western Ghats.\n\n```python\nfrom pyResearchInsights.common_functions import pre_processing\nfrom pyResearchInsights.Scraper import scraper_main\nfrom pyResearchInsights.Cleaner import cleaner_main\nfrom pyResearchInsights.Analyzer import analyzer_main\nfrom pyResearchInsights.NLP_Engine import nlp_engine_main\n\n'''Abstracts containing these keywords will be queried from Springer'''\nkeywords_to_search = \"Western Ghats Conservation\"\n\n'''Calling the pre_processing functions here so that abstracts_log_name and status_logger_name is available across the code.'''\nabstracts_log_name, status_logger_name = pre_processing(keywords_to_search)\n\n'''Runs the scraper here to scrape the details from the scientific repository'''\nscraper_main(keywords_to_search, abstracts_log_name, status_logger_name)\n\n'''Cleaning the corpus here before any of the other modules use it for analysis'''\ncleaner_main(abstracts_log_name, status_logger_name)\n\n'''Calling the Analyzer Function here'''\nanalyzer_main(abstracts_log_name, status_logger_name)\n\n'''Calling the visualizer code below this portion'''\nnlp_engine_main(abstracts_log_name, status_logger_name)\n```\n\nEach module of the pacakage can be run independtely, as described in the following sections:\n\n### <a title='Scraper' id='how-scraper'>3.1 Scraper</a>:\n\n```python\n'''Importing pre_processing() which generates LOG files during the code run'''\nfrom pyResearchInsights.common_functions import pre_processing\n\n'''Importing the scraper_main() which initiates the scraping process'''\nfrom pyResearchInsights.Scraper import scraper_main\n\n'''Abstracts containing these keywords will be scraped from Springer'''\nkeywords_to_search = \"Valdivian Forests Conservation\"\n\n'''The refernce to the LOG folder and the status_logger are returned by pre_processing() here'''\nabstracts_log_name, status_logger_name = pre_processing(keywords_to_search)\n\n'''Calling the scraper_main() to start the scraping processing'''\nscraper_main(keywords_to_search, abstracts_log_name, status_logger_name)\n```\n\nHere,\n\n- ```keywords``` - Abstracts queried from Springer will contain these keywords.\n- ```abstracts_log_name``` - The ```.txt``` file containing the abstracts downloaded.\n- ```status_logger_name``` - File that contains logs the sequence of functions executed for later debugging.\n\n- This script downloads abstracts from [Springer](https://link.springer.com) containing the ```keywords``` \"Valdivian Forests Conservation\".\n\n### <a title='Cleaner' id='how-cleaner'>3.2 Cleaner</a>:\n\n```python\n'''Importing the cleaner_main() to clean the txt file of abstracts'''\nfrom pyResearchInsights.Cleaner import cleaner_main\n\n'''The location of the file to be cleaned is mentioned here'''\nabstracts_log_name = \"/location/to/txt/file/to/be/cleaned\"\n\n'''status_logger() logs the seequence of functions executed during the code run'''\nstatus_logger_name = \"Status_Logger_Name\"\n\n'''Calling the cleaner_main() here to clean the text file provided'''\ncleaner_main(abstracts_log_name, status_logger_name)\n```\nHere,\n\n- ```abstracts_log_name``` - The ```.txt``` file containing the abstracts to be cleaned before generating research themes.\n- ```status_logger_name``` - File that contains logs the sequence of functions executed for later debugging.\n\n- This script cleans the ```file_name.txt``` and generates a ```file_name_CLEANED.txt``` file. Abstracts available online are often riddled with poor formatting and special characters.\n\n<img src=\"https://raw.githubusercontent.com/SarthakJShetty/Bias/master/assets/Cleaner_1.png\">\n<i> <b>Figure 3.2.1a</b> The text collected by the Scraper consists of special characters (second last line in figure above, '30\\xc2\\xa0cm'), which has to be cleaned before performing topic-modelling</i>\n\n\n<img src=\"https://raw.githubusercontent.com/SarthakJShetty/Bias/master/assets/Cleaner_2.png\">\n<i><b>Figure 3.2.1b</b> The Cleaner gets rid of the special characters seen throughout the corpus as in Figure 3.2.1a, and thereby ensures legible topic-modelling results</i>\n\n### <a title='Analyzer' id='how-analyzer'>3.3 Analyzer</a>:\n\n```python\n'''Importing the analyzer_main() to analyze the frequency of keywords encountered in the text file'''\nfrom pyResearchInsights.Analyzer import analyzer_main\n\n'''The location of the file to be analyzed is mentioned here'''\nabstracts_log_name = \"/location/to/txt/file/to/be/analyzed\"\n\n'''status_logger() logs the seequence of functions executed during the code run'''\nstatus_logger_name = \"Status_Logger_Name\"\n\n'''Calling the cleaner_main() here to analyze the text file provided'''\nanalyzer_main(abstracts_log_name, status_logger_name)\n```\nHere,\n\n- ```abstracts_log_name``` - The ```.txt``` file containing the abstracts to be analyzed for temporal frequency of various keywords.\n- ```status_logger_name``` - File that contains logs the sequence of functions executed for later debugging.\n\n- This script analyzes the frequency of different keywords occuring in texts contained in ```file_name.txt```, and generates a ```file_name_FREQUENCY_CSV.csv``` file.\n\n### <a title='NLP Engine' id='how-nlp'>3.4 NLP_Engine</a>:\n\n```python\n'''Importing the nlp_engine_main() to generate the interactive topic modelling charts'''\nfrom pyResearchInsights.NLP_Engine import nlp_engine_main\n\n'''The location of the abstracts which will be used to train the language models'''\nabstracts_log_name = \"/location/to/txt/file/to/be/analyzed\"\n\n'''status_logger() logs the seequence of functions executed during the code run'''\nstatus_logger_name = \"Status_Logger_Name\"\n\n'''Calling the nlp_engine_main() here to train the language models on the texts provided'''\nnlp_engine_main(abstracts_log_name, status_logger_name)\n```\n\n**Note**: The ```Visualizer``` is integrated within the ```NLP_Engine``` function.\n\nHere,\n\n- ```abstracts_log_name``` - The ```.txt``` file containing the abstracts from which research themes are to be generated.\n- ```status_logger_name``` - File that contains logs the sequence of functions executed for later debugging.\n\n- This script generates the <a title = 'Result - 1' href = '#topic-modelling-results'>topic modelling</a> and the <a title = 'Result - 2' href = '#frequency-charts'>frequency/weight</a> charts for the abstracts in the ```abstracts_log_name``` file.\n\n## <a title='Results' id='results'>4.0 Results</a>:\n\n### <a title = 'Topic Modelling Results' id = 'results-topic'>4.1 Topic Modelling Results</a>:\n\n<img src='https://raw.githubusercontent.com/SarthakJShetty/Bias/master/assets/Topics.png' alt='Topic Modelling Chart'>\n\n<i>***Figure 4.1*** Distribution of topics presented as pyLDAvis charts</i>\n\n- Circles indicate topics generated from the ```.txt``` file supplied to the ```NLP_Engine.py```. The number of topics here can be varied usine the ```--num_topics``` flag of the ```NLP_Engine```.\n- Each topic is made of a number of keywords, seen on the right.\n- More details regarding the visualizations and the udnerlying mechanics can be checked out [here](https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf).\n\n### <a title = 'Weights/Frequency Chart' id = 'results-frequency-weight'>4.2 Weights and Frequency Results</a>:\n\n<img src = 'https://raw.githubusercontent.com/SarthakJShetty/Bias/master/assets/WeightsAndFrequency.png' alt= \"Weights and Frequncy\">\n\n<i>***Figure 4.2*** Here, we plot the variation in the weights and frequency of topic keywords</i>.\n\n- The weight of a keyword is calculated by its: i) frequency of occurance in the corpus and, ii) its frequency of co-occurance with other keywords in the same topic.\n\n## <a title='Citation' id='cite'>Citation</a>:\nIf you use `pyReasearchInsights` for your research, please cite us! Here is the BibTex entry for our 2021 Ecology & Evolution [paper](https://onlinelibrary.wiley.com/doi/10.1002/ece3.8098).\n\n\t\t@article{shetty2021pyresearchinsights,\n\t\ttitle={pyResearchInsights—An open-source Python package for scientific text analysis},\n\t\tauthor={Shetty, Sarthak J and Ramesh, Vijay},\n\t\tjournal={Ecology and Evolution},\n\t\tvolume={11},\n\t\tnumber={20},\n\t\tpages={13920--13929},\n\t\tyear={2021},\n\t\tpublisher={Wiley Online Library}\n\t\t}" }, { "alpha_fraction": 0.7582626938819885, "alphanum_fraction": 0.7601215243339539, "avg_line_length": 53.87064743041992, "blob_id": "3cd9928b1a8b886c52adbb66ee0581d7a4a4b4fb", "content_id": "a552cea092ff64ef446f31ec15f8565d7b6ceec4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22057, "license_type": "permissive", "max_line_length": 213, "num_lines": 402, "path": "/pyResearchInsights/Scraper.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''The aim of this script is to scrape abstracts, author names and date of publication from Springer\nSarthak J. Shetty\n04/08/2018'''\n\n'''Adding the libraries to be used here.'''\n\n'''Importing urllib.request to use urlopen'''\nfrom urllib.request import build_opener, HTTPCookieProcessor\n''''Importing urllib.error to handle errors in HTTP pinging.'''\nimport urllib.error\n'''BeautifulSoup is used for souping.'''\nfrom bs4 import BeautifulSoup as bs\n'''Counter generates a dictionary from the abstract data, providing frequencies of occurences'''\nfrom collections import Counter\n'''Importing the CSV library here to dump the dictionary for further analysis and error checking if required. Will edit it out later.'''\nimport csv\n'''Importing numpy to generate a random integer for the delay_function (see below)'''\nimport numpy as np\n'''This library is imported to check if we can feasibly introduce delays into the processor loop to reduce instances of the remote server, shutting the connection while scrapping extraordinarily large datasets.'''\nimport time\n'''Fragmenting code into different scripts. Some functions are to be used across the different sub-parts as well. Hence, shifted some of the functions to the new script.'''\nfrom pyResearchInsights.common_functions import pre_processing, argument_formatter, keyword_url_generator, abstract_id_log_name_generator, status_logger\n\ndef url_reader(url, status_logger_name):\n\t'''This keyword is supplied to the URL and is hence used for souping.\n\tEncountered an error where some links would not open due to HTTP.error\n\tThis is added here to try and ping the page. If it returns false the loop ignores it and\n\tmoves on to the next PII number'''\n\ttry:\n\t\t'''Using the urllib function, urlopen to extract the html_code of the given page'''\n\t\topen_connection = build_opener(HTTPCookieProcessor())\n\t\thtml_code = open_connection.open(url)\n\t\t'''Closing the abstract window after each abstract has been extracted'''\n\t\treturn html_code\t\t\t\n\texcept (UnboundLocalError, urllib.error.HTTPError):\n\t\tpass\n\ndef results_determiner(url, status_logger_name):\n\t'''This function determines the number of results that a particular keywords returns\n\tonce it looks up the keyword on link.springer.com\n\tThe function returns all the possible links containing results and then provides the total number of results\n\treturned by a particular keyword, or combination of keywords.'''\n\tfirst_page_to_scrape = url_reader(url, status_logger_name)\n\n\tfirst_page_to_scrape_soup = page_souper(first_page_to_scrape, status_logger_name)\n\tnumber_of_results = first_page_to_scrape_soup.find('h1', {'id':'number-of-search-results-and-search-terms'}).find('strong').text\n\n\tresults_determiner_status_key = \"Total number of results obtained: \"+number_of_results\n\tstatus_logger(status_logger_name, results_determiner_status_key)\n\ndef url_generator(start_url, query_string, status_logger_name):\n\t'''This function is written to scrape all possible webpages of a given topic\n\tThe search for the URLs truncates when determiner variable doesn't return a positive value'''\n\turl_generator_start_status_key = start_url+\" \"+\"start_url has been received\"\n\tstatus_logger(status_logger_name, url_generator_start_status_key)\n\n\t'''Initiallizing a list here in order to contain the URLs. Even if a URL does not return valid results,\n\tit is popped later on from the list.'''\n\turls_to_scrape=[]\n\tcounter = 0\n\ttotal_url = start_url+str(counter)+\"?facet-content-type=\\\"Article\\\"&query=\"+query_string+\"&facet-language=\\\"En\\\"\"\n\tinitial_url_status_key = total_url+\" \"+\"has been obtained\"\n\tstatus_logger(status_logger_name, initial_url_status_key)\n\turls_to_scrape.append(total_url)\n\ttest_soup = bs(url_reader(total_url, status_logger_name), 'html.parser')\n\t'''Here, we grab the page element that contains the number of pages to be scrapped'''\n\tdeterminer = test_soup.findAll('span', {'class':'number-of-pages'})[0].text\n\t'''We generate the urls_to_scrape from the stripped down determiner element'''\n\turls_to_scrape = [(start_url+str(counter)+\"?facet-content-type=\\\"Article\\\"&query=\"+query_string+\"&facet-language=\\\"En\\\"\") for counter in range(1, (int(determiner.replace(',', '')) + 1))]\n\t\n\turl_generator_stop_status_key = determiner.replace(',', '') + \" page URLs have been obtained\"\n\tstatus_logger(status_logger_name, url_generator_stop_status_key)\n\n\treturn urls_to_scrape\n\ndef page_souper(page, status_logger_name):\n\t'''Function soups the webpage elements and provided the tags for search.\n\tNote: Appropriate encoding has to be picked up beenfore souping'''\n\tpage_souper_start_status_key = \"Souping page\"\n\tstatus_logger(status_logger_name, page_souper_start_status_key)\n\n\tpage_soup = bs(page, 'html.parser')\n\n\tpage_souper_stop_status_key = \"Souped page\"\n\tstatus_logger(status_logger_name, page_souper_stop_status_key)\n\n\treturn page_soup\n\ndef abstract_word_extractor(abstract, abstract_title, abstract_year, permanent_word_sorter_list, trend_keywords, status_logger_name):\n\t'''This function creates the list that stores the text in the form of individual words\n\tagainst their year of appearence.'''\n\tabstract_word_sorter_start_status_key = \"Adding:\"+\" \"+abstract_title+\" \"+\"to the archival list\"\n\tstatus_logger(status_logger_name, abstract_word_sorter_start_status_key)\n\t\n\t'''This line of code converts the entire abstract into lower case'''\n\tabstract = abstract.lower()\n\t'''Converting the abstract into a list of words'''\n\tabstract_word_list = abstract.split()\n\t'''This line of code sorts the elements in the word list alphabetically. Working with dataframes is harden, hence\n\twe are curbing this issue by modifying the list rather.'''\n\tabstract_word_list.sort()\n\t'''If the word currently being looped in the abstract list matches the trend word being investigated for, the year it appears\n\tis appended to the permanent word sorter list'''\n\tfor element in abstract_word_list:\n\t\tif(element==trend_keywords[0]):\n\t\t\tpermanent_word_sorter_list.append(abstract_year[:4])\n\n\tabstract_word_sorter_end_status_key = \"Added:\"+\" \"+abstract_title+\" \"+\"to the archival list\"\n\tstatus_logger(status_logger_name, abstract_word_sorter_end_status_key)\n\ndef abstract_year_list_post_processor(permanent_word_sorter_list, status_logger_name):\n\t'''Because of this function we have a dictionary containing the frequency of occurrence of terms in specific years'''\n\tabstract_year_list_post_processor_start_status_key = \"Post processing of permanent word sorter list has commenced\"\n\tstatus_logger(status_logger_name, abstract_year_list_post_processor_start_status_key)\n\n\tabstract_year_dictionary = Counter(permanent_word_sorter_list)\n\n\tabstract_year_list_post_processor_end_status_key = \"Post processing of permanent word sorter list has completed\"\n\tstatus_logger(status_logger_name, abstract_year_list_post_processor_end_status_key)\n\n\treturn abstract_year_dictionary\n\ndef abstract_year_dictionary_dumper(abstract_word_dictionary, abstracts_log_name, status_logger_name):\n\t'''This function saves the abstract word dumper to the disc for further inspection.\n\tThe file is saved as a CSV bucket and then dumped.'''\n\tpermanent_word_sorter_list_start_status_key = \"Dumping the entire dictionary to the disc\"\n\tstatus_logger(status_logger_name, permanent_word_sorter_list_start_status_key)\n\n\twith open(abstracts_log_name+\"_\"+\"DICTIONARY.csv\", 'w') as dictionary_to_csv:\n\t\twriter = csv.writer(dictionary_to_csv)\n\t\tfor key, value in abstract_word_dictionary.items():\n\t\t\tyear = key\n\t\t\twriter.writerow([year, value])\n\t\n\tpermanent_word_sorter_list_end_status_key = \"Dumped the entire dictionary to the disc\"\n\tstatus_logger(status_logger_name, permanent_word_sorter_list_end_status_key)\n\ndef abstract_page_scraper(abstract_url, abstract_input_tag_id, abstracts_log_name, permanent_word_sorter_list, site_url_index, status_logger_name):\n\t'''This function is written to scrape the actual abstract of the specific paper,\n\t that is being referenced within the list of abstracts'''\n\tabstract_page_scraper_status_key=\"Abstract ID:\"+\" \"+abstract_input_tag_id\n\tstatus_logger(status_logger_name, abstract_page_scraper_status_key)\n\t\n\tabstract_page_url = abstract_url+abstract_input_tag_id\n\tabstract_page = url_reader(abstract_page_url, status_logger_name)\n\tabstract_soup = page_souper(abstract_page, status_logger_name)\n\ttitle = title_scraper(abstract_soup, status_logger_name)\n\tabstract_date = abstract_date_scraper(title, abstract_soup, status_logger_name)\n\n\t'''Due to repeated attribute errors with respect to scraping the authors name, these failsafes had to be put in place.'''\n\ttry:\n\t\tauthor = author_scraper(abstract_soup, status_logger_name)\n\texcept AttributeError:\n\t\tauthor = \"Author not available\"\n\n\t'''Due to repeated attribute errors with respect to scraping the abstract, these failsafes had to be put in place.'''\n\ttry:\n\t\tabstract = abstract_scraper(abstract_soup)\n\t\t# abstract_word_extractor(abstract, title, abstract_date, permanent_word_sorter_list, trend_keywords, status_logger_name)\n\texcept AttributeError:\n\t\tabstract = \"Abstract not available\"\n\n\tabstract_database_writer(abstract_page_url, title, author, abstract, abstracts_log_name, abstract_date, status_logger_name)\n\tanalytical_abstract_database_writer(title, author, abstract, abstracts_log_name, status_logger_name)\n\ndef abstract_crawler(abstract_url, abstract_id_log_name, abstracts_log_name, permanent_word_sorter_list, site_url_index, status_logger_name):\n\tabstract_crawler_start_status_key = \"Entered the Abstract Crawler\"\n\tstatus_logger(status_logger_name, abstract_crawler_start_status_key)\n\t\n\tabstract_crawler_temp_index = site_url_index\n\t'''This function crawls the page and access each and every abstract'''\n\tabstract_input_tag_ids = abstract_id_database_reader(abstract_id_log_name, abstract_crawler_temp_index, status_logger_name)\n\tfor abstract_input_tag_id in abstract_input_tag_ids:\n\t\ttry:\n\t\t\tabstract_crawler_accept_status_key=\"Abstract Number:\"+\" \"+str((abstract_input_tag_ids.index(abstract_input_tag_id)+1)+abstract_crawler_temp_index*20)\n\t\t\tstatus_logger(status_logger_name, abstract_crawler_accept_status_key)\n\t\t\tabstract_page_scraper(abstract_url, abstract_input_tag_id, abstracts_log_name, permanent_word_sorter_list, site_url_index, status_logger_name)\n\t\texcept TypeError:\n\t\t\tabstract_crawler_reject_status_key=\"Abstract Number:\"+\" \"+str(abstract_input_tag_ids.index(abstract_input_tag_id)+1)+\" \"+\"could not be processed\"\n\t\t\tstatus_logger(status_logger_name, abstract_crawler_reject_status_key)\n\t\t\tpass\n\n\tabstract_crawler_end_status_key = \"Exiting the Abstract Crawler\"\n\tstatus_logger(status_logger_name, abstract_crawler_end_status_key)\n\ndef analytical_abstract_database_writer(title, author, abstract, abstracts_log_name, status_logger_name):\n\t'''This function will generate a secondary abstract file that will contain only the abstract.\n\tThe abstract file generated will be passed onto the Visualizer and Analyzer function, as opposed to the complete \n\tabstract log file containing lot of garbage words in addition to the abstract text.'''\n\tanalytical_abstract_database_writer_start_status_key = \"Writing\"+\" \"+title+\" \"+\"by\"+\" \"+author+\" \"+\"to analytical abstracts file\"\n\tstatus_logger(status_logger_name, analytical_abstract_database_writer_start_status_key)\n\n\tanalytical_abstracts_txt_log = open(abstracts_log_name+'_'+'ANALYTICAL'+'.txt', 'a')\n\tanalytical_abstracts_txt_log.write(abstract)\n\tanalytical_abstracts_txt_log.write('\\n'+'\\n')\n\tanalytical_abstracts_txt_log.close()\n\n\tanalytical_abstract_database_writer_stop_status_key = \"Written\"+\" \"+title+\" \"+\"to disc\"\n\tstatus_logger(status_logger_name, analytical_abstract_database_writer_stop_status_key)\n\ndef abstract_database_writer(abstract_page_url, title, author, abstract, abstracts_log_name, abstract_date, status_logger_name):\n\t'''This function makes text files to contain the abstracts for future reference.\n\tIt holds: 1) Title, 2) Author(s), 3) Abstract'''\n\tabstract_database_writer_start_status_key = \"Writing\"+\" \"+title+\" \"+\"by\"+\" \"+author+\" \"+\"to disc\"\n\tstatus_logger(status_logger_name, abstract_database_writer_start_status_key)\n\t\n\tabstracts_csv_log = open(abstracts_log_name+'.csv', 'a')\n\tabstracts_txt_log = open(abstracts_log_name+'.txt', 'a')\n\tabstracts_txt_log.write(\"Title:\"+\" \"+title)\n\tabstracts_txt_log.write('\\n')\n\tabstracts_txt_log.write(\"Author:\"+\" \"+author)\n\tabstracts_txt_log.write('\\n')\n\tabstracts_txt_log.write(\"Date:\"+\" \"+abstract_date)\n\tabstracts_txt_log.write('\\n')\n\tabstracts_txt_log.write(\"URL:\"+\" \"+abstract_page_url)\n\tabstracts_txt_log.write('\\n')\n\tabstracts_txt_log.write(\"Abstract:\"+\" \"+abstract)\n\tabstracts_csv_log.write(abstract)\n\tabstracts_csv_log.write('\\n')\n\tabstracts_txt_log.write('\\n'+'\\n')\n\tabstracts_txt_log.close()\n\tabstracts_csv_log.close()\n\n\tabstract_database_writer_stop_status_key = \"Written\"+\" \"+title+\" \"+\"to disc\"\n\tstatus_logger(status_logger_name, abstract_database_writer_stop_status_key)\n\ndef abstract_id_database_reader(abstract_id_log_name, site_url_index, status_logger_name):\n\t'''This function has been explicitly written to access\n\tthe abstracts database that the given prgram generates.'''\n\tabstract_id_reader_temp_index = site_url_index\n\tabstract_id_database_reader_start_status_key = \"Extracting Abstract IDs from disc\"\n\tstatus_logger(status_logger_name, abstract_id_database_reader_start_status_key)\n\n\tlines_in_abstract_id_database=[line.rstrip('\\n') for line in open(abstract_id_log_name+str(abstract_id_reader_temp_index+1)+'.txt')]\n\n\tabstract_id_database_reader_stop_status_key = \"Extracted Abstract IDs from disc\"\n\tstatus_logger(status_logger_name, abstract_id_database_reader_stop_status_key)\n\n\treturn lines_in_abstract_id_database\n\ndef abstract_id_database_writer(abstract_id_log_name, abstract_input_tag_id, site_url_index):\n\t'''This function writes the abtract ids to a .txt file for easy access and documentation.'''\n\tabstract_id_writer_temp_index = site_url_index\n\tabstract_id_log = open((abstract_id_log_name+str(abstract_id_writer_temp_index+1)+'.txt'), 'a')\n\tabstract_id_log.write(abstract_input_tag_id)\n\tabstract_id_log.write('\\n')\n\tabstract_id_log.close()\n\ndef abstract_date_scraper(title, abstract_soup, status_logger_name):\n\t'''This function scrapes the date associated with each of the abstracts.\n\tThis function will play a crucial role in the functionality that we are trying to build into our project.'''\n\tdate_scraper_entry_status_key = \"Scraping date of the abstract titled:\"+\" \"+title\n\tstatus_logger(status_logger_name, date_scraper_entry_status_key)\n\n\ttry:\n\t\tabstract_date = abstract_soup.find('time').get('datetime')\n\t\tdate_scraper_exit_status_key = title+\" \"+\"was published on\"+\" \"+abstract_date\n\texcept AttributeError:\n\t\tabstract_date = \"Date for abstract titled:\"+\" \"+title+\" \"+\"was not available\"\n\t\tdate_scraper_exit_status_key = abstract_date\n\t\tpass\n\n\tstatus_logger(status_logger_name, date_scraper_exit_status_key)\n\n\treturn abstract_date\n\ndef abstract_scraper(abstract_soup):\n\t'''This function scrapes the abstract from the soup and returns to the page scraper'''\n\tabstract = str(abstract_soup.find('div', {'id':'Abs1-content'}).text.encode('utf-8'))[1:]\n\n\treturn abstract\n\ndef author_scraper(abstract_soup, status_logger_name):\n\t'''This function scrapes the author of the text, for easy navigation and search'''\n\tauthor_scraper_start_status_key = \"Scraping the author name\"\n\tstatus_logger(status_logger_name, author_scraper_start_status_key)\n\n\t'''This class element's text attribute contains all the authors names. It is converted to a findAll() list and then concatinated into a string for storage.'''\n\tauthor = ''.join(str(author) for author in [authorElement.text for authorElement in abstract_soup.findAll('li', {'class':'c-author-list__item'})])\n\n\tauthor_scraper_end_status_key = \"Scraped the author's name:\" + \" \"+str(author)\n\tstatus_logger(status_logger_name, author_scraper_end_status_key)\n\n\treturn author\n\ndef title_scraper(abstract_soup, status_logger_name):\n\t'''This function scrapes the title of the text from the abstract'''\n\ttitle_scraper_start_status_key = \"Scraping the title of the abstract\"\n\tstatus_logger(status_logger_name, title_scraper_start_status_key)\n\t\n\t'''Purpose of this block is to retrieve the title of the text even if an AttributeError arises'''\n\ttry:\n\t\ttitle = str(abstract_soup.find('h1', {'class':'c-article-title'}).text.encode('utf-8'))[1:]\n\t\t'''In case an incorrectly classified asset is to be scrapped (Journal/Chapter as opposed to Article), go through this block in an attempt to retrieve the title.'''\n\texcept AttributeError:\n\t\ttry:\n\t\t\ttitle = str(abstract_soup.find('h1',{'class':'ChapterTitle'}).text.encode('utf-8'))[1:]\n\t\texcept AttributeError:\n\t\t\ttry:\n\t\t\t\ttitle = (abstract_soup.find('span', {'class':'JournalTitle'}).text)\n\t\t\texcept AttributeError:\n\t\t\t\ttitle = \"Title not available\"\n\n\ttitle_scraper_end_status_key = \"Scraped the title of the abstract\"\n\tstatus_logger(status_logger_name, title_scraper_end_status_key)\n\t\n\treturn title\n\ndef abstract_id_scraper(abstract_id_log_name, page_soup, site_url_index, status_logger_name):\n\t'''This function helps in obtaining the PII number of the abstract.\n\tThis number is then coupled with the dynamic URL and provides'''\n\tabstract_id_scraper_start_status_key=\"Scraping IDs\"\n\tstatus_logger(status_logger_name, abstract_id_scraper_start_status_key)\n\t\n\t''''This statement collects all the input tags that have the abstract ids in them'''\n\tabstract_input_tags = page_soup.findAll('a', {'class':'title'})\n\tfor abstract_input_tag in abstract_input_tags:\n\t\tabstract_input_tag_id=abstract_input_tag.get('href')\n\t\tabstract_id_database_writer(abstract_id_log_name, abstract_input_tag_id, site_url_index)\n\n\tabstract_id_scraper_stop_status_key=\"Scraped IDs\"\n\tstatus_logger(status_logger_name, abstract_id_scraper_stop_status_key)\n\ndef word_sorter_list_generator(status_logger_name):\n\tword_sorter_list_generator_start_status_key = \"Generating the permanent archival list\"\n\tstatus_logger(status_logger_name, word_sorter_list_generator_start_status_key)\n\t\n\t'''This function generates the list that hold the Words and corresponding Years of the\n\tabstract data words before the actual recursion of scrapping data from the website begins.'''\n\tword_sorter_list = []\n\n\tword_sorter_list_generator_exit_status_key = \"Generated the permanent archival list\"\n\tstatus_logger(status_logger_name, word_sorter_list_generator_exit_status_key)\n\t\n\treturn word_sorter_list\n\ndef delay_function(status_logger_name):\n\t'''Since the Springer servers are contstantly shutting down the remote connection, we introduce\n\tthis function in the processor function in order to reduce the number of pings it delivers to the remote.'''\n\n\tdelay_variable = np.random.randint(0, 20)\n\n\tdelay_function_start_status_key = \"Delaying remote server ping:\"+\" \"+str(delay_variable)+\" \"+\"seconds\"\n\tstatus_logger(status_logger_name, delay_function_start_status_key)\n\n\t'''Sleep parameter causes the code to be be delayed by 1 second'''\n\ttime.sleep(delay_variable)\n\n\tdelay_function_end_status_key = \"Delayed remote server ping:\"+\" \"+str(delay_variable)+\" \"+\"seconds\"\n\tstatus_logger(status_logger_name, delay_function_end_status_key)\n\ndef processor(abstract_url, urls_to_scrape, abstract_id_log_name, abstracts_log_name, status_logger_name, keywords_to_search):\n\t''''Multiple page-cycling function to scrape multiple result pages returned from Springer.\n\tprint(len(urls_to_scrape))'''\n\t\n\t'''This list will hold all the words mentioned in all the abstracts. It will be later passed on to the\n\tvisualizer code to generate the trends histogram.'''\n\tpermanent_word_sorter_list = word_sorter_list_generator(status_logger_name)\n\n\tfor site_url_index in range(0, len(urls_to_scrape)):\n\t\tif(site_url_index==0):\n\t\t\tresults_determiner(urls_to_scrape[site_url_index], status_logger_name)\n\t\t'''Collects the web-page from the url for souping'''\n\t\tpage_to_soup = url_reader(urls_to_scrape[site_url_index], status_logger_name)\n\t\t'''Souping the page for collection of data and tags'''\n\t\tpage_soup = page_souper(page_to_soup, status_logger_name)\n\t\t'''Scrapping the page to extract all the abstract IDs'''\n\t\tabstract_id_scraper(abstract_id_log_name, page_soup, site_url_index, status_logger_name)\n\t\t'''Actually obtaining the abstracts after combining ID with the abstract_url'''\n\t\tabstract_crawler(abstract_url, abstract_id_log_name, abstracts_log_name, permanent_word_sorter_list, site_url_index, status_logger_name)\n\t\t'''Delaying after each page being scrapped, rather than after each abstract'''\n\t\tdelay_function(status_logger_name)\n\n\t'''This line of code processes and generates a dictionary from the abstract data'''\n\n\tabstract_year_dictionary = abstract_year_list_post_processor(permanent_word_sorter_list, status_logger_name)\n\n\treturn abstract_year_dictionary\n\ndef scraper_main(keywords_to_search, abstracts_log_name, status_logger_name):\n\t''''This function contains all the functions and contains this entire script here, so that it can be imported later to the main function'''\n\n\t'''Here, we utilize the keywords provided by the user to generate the URLs for scrapping'''\n\tstart_url, abstract_url, query_string = keyword_url_generator(keywords_to_search)\n\n\t'''Since we receive only the abstracts_log_name, we have to extract the abstract_id_log_name'''\n\tabstract_id_log_name = abstract_id_log_name_generator(abstracts_log_name)\n\n\tif(type(keywords_to_search) == str):\n\t\t'''If the user ran the code using just the function from the library, then the keywords and trends words need to be in this format'''\n\t\tkeywords_to_search = argument_formatter(keywords_to_search)\n\telse:\n\t\tkeywords_to_search = keywords_to_search\n\n\t'''Provides the links for the URLs to be scraped by the scraper'''\n\turls_to_scrape = url_generator(start_url, query_string, status_logger_name)\n\t'''Calling the processor() function here'''\n\tabstract_year_dictionary = processor(abstract_url, urls_to_scrape, abstract_id_log_name, abstracts_log_name, status_logger_name, keywords_to_search)\n\t'''This function dumps the entire dictionary onto the disc for further analysis and inference.'''\n\tabstract_year_dictionary_dumper(abstract_year_dictionary, abstracts_log_name, status_logger_name)\n\n\treturn 0" }, { "alpha_fraction": 0.7372742295265198, "alphanum_fraction": 0.7482210993766785, "avg_line_length": 47.105262756347656, "blob_id": "59dac9a7ced70fc77292d1ba93d069b56e65e728", "content_id": "a636e53dcf6c69b5442f1558e417749aab8ae441", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1827, "license_type": "permissive", "max_line_length": 150, "num_lines": 38, "path": "/pyResearchInsights/system_functions.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''Hello! This portion of the code that acts as the processing code corroborating with the main scripts [re: Scraper, Analyzer+NLP_Engine, Visualizer]\n\n- Sarthak J. Shetty\n06/02/2019\n\nThis script has been renamed as the system_functions.py to carry out OS level interactions, such as:\n1. tarballing the LOGS generated to reduce space.\n2. Deleting the LOGs once the tarball has been created.\n3. (Eventually) enable shell script to send the tarballed file over mail to the user.\n4. (Eventually) enable shell script to upload the LOGS generated to GitHub.\n\n- Sarthak J. Shetty\n15/04/2019'''\n\n'''Importing OS to call the tar function to generate the .tar file.'''\nimport os\n'''From common_functions.py calling the status_logger() function to LOG the tarballing process and others as they are added here.'''\nfrom pyResearchInsights.common_functions import status_logger\n\ndef rm_original_folder(logs_folder_name, status_logger_name):\n\t'''This function deletes the logs folder generated once the .tar.gz file has been created.'''\n\trm_original_folder_start_status_key = \"Deleting files belonging to:\"+\" \"+logs_folder_name\n\tstatus_logger(status_logger_name, rm_original_folder_start_status_key)\n\n\tcommand_to_rm_function = \"rm -r\"+\" \"+logs_folder_name\n\n\tos.system(command_to_rm_function)\n\ndef tarballer(logs_folder_name, status_logger_name):\n\t'''This function prepares the tar ball of the LOG file.'''\n\ttarballer_start_status_key = \"Tarballing\"+\" \"+logs_folder_name+\" \"+\"into\"+\" \"+logs_folder_name+\".tar.gz\"\n\tstatus_logger(status_logger_name, tarballer_start_status_key)\n\n\tcommand_to_tar_function = \"tar czf\"+\" \"+logs_folder_name+\".tar.gz\"+\" \"+logs_folder_name\n\tos.system(command_to_tar_function)\n\n\ttarballer_start_end_key = \"Tarballed\"+\" \"+logs_folder_name+\" \"+\"into\"+\" \"+logs_folder_name+\".tar.gz\"\n\tstatus_logger(status_logger_name, tarballer_start_end_key)" }, { "alpha_fraction": 0.7362984418869019, "alphanum_fraction": 0.7402297258377075, "avg_line_length": 49.6796875, "blob_id": "4f49c84c95c29a9fafc00a492c60b4f5e8abdff1", "content_id": "28a00aeb0c7474d73477cbdcb7a1f6fc2aecfe94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12973, "license_type": "permissive", "max_line_length": 359, "num_lines": 256, "path": "/pyResearchInsights/NLP_Engine.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''Hello! This module of code is a part of the larger pyResearchInsights project.\nThis file was earlier named as Temp_Gensim_Code; code is now bifurcated into Gensim code (this) and a seperate\nvisualization code that will be added to the repository as well.\n\nCheckout the Bias README.md for an overview of the project.\n\nSarthak J. Shetty\n24/11/2018'''\n\n'''Natural Language toolkit. Here we download the commonly used English stopwords'''\nimport nltk; nltk.download('stopwords')\n'''Standard set of functions for reading and appending files'''\nimport re\n'''Pandas and numpy is a dependency used by other portions of the code.'''\nimport numpy as np\nimport pandas as pd\n'''Think this stands for pretty print. Prints out stuff to the terminal in a prettier way'''\nfrom pprint import pprint\n'''Importing OS to get current working directory (cwd) to tackle abstracts_log_name edge cases'''\nimport os\n'''Contains the language model that has to be developed.'''\nimport gensim\nimport gensim.corpora as corpora\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nfrom pyResearchInsights.common_functions import status_logger\nfrom pyResearchInsights.Visualizer import visualizer_main\n'''Industrial level toolkit for NLP'''\nimport spacy\n\nimport pyLDAvis\nimport pyLDAvis.gensim_models\n\n'''Make pretty visualizations'''\nimport matplotlib as plt\n\n'''Library to log any errors. Came across this in the tutorial.'''\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\nfrom nltk.corpus import stopwords\nstop_words = stopwords.words('english')\nstop_words.extend(['from', 'subject', 're', 'edu', 'use', 'com', 'https', 'url', 'link', 'abstract', 'author', 'chapter', 'springer', 'title', \"the\", \"of\", \"and\", \"in\", \"to\", \"a\", \"is\", \"for\", \"from\", \"with\", \"that\", \"by\", \"are\", \"on\", \"was\", \"as\", \n\t\"were\", \"url:\", \"abstract:\", \"abstract\", \"author:\", \"title:\", \"at\", \"be\", \"an\", \"have\", \"this\", \"which\", \"study\", \"been\", \"not\", \"has\", \"its\", \"also\", \"these\", \"this\", \"can\", \"a\", 'it', 'their', \"e.g.\", \"those\", \"had\", \"but\", \"while\", \"will\", \"when\", \"only\", \"author\", \"title\", \"there\", \"our\", \"did\", \"as\", \"if\", \"they\", \"such\", \"than\", \"no\", \"-\", \"could\"])\n\ndef data_reader(abstracts_log_name, status_logger_name):\n\t'''This wherer the file is being parsed from to the model'''\n\tdata_reader_start_status_key = abstracts_log_name+\".txt is being ported to dataframe\"\n\tstatus_logger(status_logger_name, data_reader_start_status_key)\n\n\ttry:\n\t\t'''If the NLP_Engine script is run independently, not as part of the pipeline as a whole, there would be no filename_CLEAND.txt.\n\t\tThis ensures that that file can be processed independently.'''\n\t\tabstracts_txt_file_name = (abstracts_log_name.split(\".txt\")[0]) + \"_\" + 'CLEANED.txt'\n\t\ttextual_dataframe = pd.read_csv(abstracts_txt_file_name, delimiter=\"\\t\")\n\texcept FileNotFoundError:\n\t\ttextual_dataframe = pd.read_csv(abstracts_log_name, delimiter=\"\\t\")\n\n\tdata_reader_end_status_key = abstracts_log_name + \".txt has been ported to dataframe\"\t\n\tstatus_logger(status_logger_name, data_reader_end_status_key)\n\n\treturn textual_dataframe\n\ndef textual_data_trimmer(textual_dataframe, status_logger_name):\n\t'''Converts each of the abstracts in the file into a list element, of size = (number of abstracts)'''\n\ttextual_data_trimmer_start_status_key = \"Trimming data and preparing list of words\"\n\tstatus_logger(status_logger_name, textual_data_trimmer_start_status_key)\n\n\ttextual_data = textual_dataframe.values.tolist()\n\n\ttextual_data_trimmer_end_status_key = \"Trimmed data and prepared list of words\"\n\tstatus_logger(status_logger_name, textual_data_trimmer_end_status_key)\n\n\treturn textual_data\n\ndef sent_to_words(textual_data, status_logger_name):\n\t'''Removing unecessary characters and removing punctuations from the corpus. Resultant words are then tokenized.'''\n\tsent_to_words_start_status_key = \"Tokenizing words\"\n\tstatus_logger(status_logger_name, sent_to_words_start_status_key)\n\n\tfor sentence in textual_data:\n\t\tyield(gensim.utils.simple_preprocess(str(sentence), deacc=True))\n\ttextual_data = list(sent_to_words(textual_data, status_logger_name))\n\t\n\tsent_to_words_end_status_key = \"Tokenized words\"\n\tstatus_logger(status_logger_name, sent_to_words_end_status_key)\t\n\n\treturn textual_data\n\ndef bigram_generator(textual_data, status_logger_name):\n\t'''Generating bigram model from the words that are in the corpus.'''\n\t'''Bigrams: Words that occur together with a high frequency,'''\n\tbigram_generator_start_status_key = \"Generating word bigrams\"\n\tstatus_logger(status_logger_name, bigram_generator_start_status_key)\n\t\n\tbigram = gensim.models.Phrases(textual_data, min_count=5, threshold=100)\n\tbigram_mod = gensim.models.phrases.Phraser(bigram)\n\n\tbigram_generator_end_status_key = \"Generated word bigrams\"\n\tstatus_logger(status_logger_name, bigram_generator_end_status_key)\t\n\n\treturn bigram_mod\n\ndef remove_stopwords(textual_data, status_logger_name):\n\t'''This function removes the standard set of stopwords from the corpus of abstract words.\n\tWe've added a bunch of other words in addition.'''\n\tremove_stopwords_start_status_key = \"Removing stopwords\"\n\tstatus_logger(status_logger_name, remove_stopwords_start_status_key)\n\t\n\treturn [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in textual_data]\n\t\n\tremove_stopwords_end_status_key = \"Removed stopwords\"\n\tstatus_logger(status_logger_name, remove_stopwords_end_status_key)\n\ndef format_topics_sentences(ldamodel, corpus, texts):\n\t'''This function generates a dataframe that presents the dominant topic of each entry in the dataset'''\n\tsent_topics_df = pd.DataFrame()\n\tfor i, row in enumerate(ldamodel[corpus]):\n\t\trow = sorted(row, key=lambda x: (x[1]), reverse=True)\n\t\tfor j, (topic_num, prop_topic) in enumerate(row):\n\t\t\tif j == 0:\n\t\t\t\twp = ldamodel.show_topic(topic_num)\n\t\t\t\ttopic_keywords = \", \".join([word for word, prop in wp])\n\t\t\t\tsent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)\n\t\t\telse:\n\t\t\t\tbreak\n\tsent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']\n\tcontents = pd.Series(texts)\n\tsent_topics_df = pd.concat([sent_topics_df, contents], axis=1)\n\n\treturn (sent_topics_df)\n\ndef make_bigrams(textual_data, status_logger_name):\n\t'''Generates multiple bigrams of word pairs in phrases that commonly occuring with each other over the corpus'''\n\tmake_bigrams_start_status_key = \"Generating bigrams\"\n\tstatus_logger(status_logger_name, make_bigrams_start_status_key)\n\n\tbigram_mod = bigram_generator(textual_data, status_logger_name)\n\treturn [bigram_mod[doc] for doc in textual_data]\n\t\n\tmake_bigrams_end_status_key = \"Generated bigrams\"\n\tstatus_logger(status_logger_name, make_bigrams_end_status_key)\n\ndef lemmatization(status_logger_name, textual_data, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):\n\t'''Reducing a word to the root word. Running -> Run for example'''\n\tlemmatization_start_status_key = \"Beginning lemmatization\"\n\tstatus_logger(status_logger_name, lemmatization_start_status_key)\n\n\ttexts_out = []\n\ttry:\n\t\tnlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])\n\texcept OSError:\n\t\tfrom spacy.cli import download\n\t\tdownload('en_core_web_sm')\n\t\tnlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])\n\tfor sent in textual_data:\n\t\tdoc = nlp(\" \".join(sent))\n\t\ttexts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])\n\n\tlemmatization_end_status_key = \"Ending lemmatization\"\n\tstatus_logger(status_logger_name, lemmatization_end_status_key)\n\n\treturn texts_out\n\ndef nlp_engine_main(abstracts_log_name, status_logger_name, num_topics = None, num_keywords = None, mallet_path = None):\n\tnlp_engine_main_start_status_key = \"Initiating the NLP Engine\"\n\tstatus_logger(status_logger_name, nlp_engine_main_start_status_key)\n\n\t'''We can arrive at logs_folder_name from abstracts_log_name, instead of passing it to the NLP_Engine function each time'''\n\tif('Abstract' in abstracts_log_name):\n\t\tlogs_folder_name = abstracts_log_name.split('Abstract')[0][:-1]\n\telse:\n\t\t'''If the user points to an abstracts_log_name that does not contain 'Abstract' and lies at the current working directory then set the logs_folder_name as cwd'''\n\t\tlogs_folder_name = ''\n\n\tif(logs_folder_name == ''):\n\t\t'''This condition is required, if the file is located at the directory of the pyResearchInsights code.'''\n\t\tlogs_folder_name = logs_folder_name + os.getcwd()\n\n\t'''Declaring the number of topics to be generated by the LDA model'''\n\tif num_topics == None:\n\t\t'''If the user has not provided this argument then set to 10'''\n\t\tnum_topics = 10\n\n\t'''Declaring the number of keywords to be presented by the Visualizer'''\n\tif num_keywords == None:\n\t\t'''If the user has not provided this argument then set to 20'''\n\t\tnum_keywords = 20\n\n\t'''Extracts the data from the .txt file and puts them into a Pandas dataframe buckets'''\n\ttextual_dataframe = data_reader(abstracts_log_name, status_logger_name)\n\t'''Rids the symbols and special characters from the textual_data'''\n\ttextual_data = textual_data_trimmer(textual_dataframe, status_logger_name)\n\t'''Removes stopwords that were earlier downloaded from the textual_data'''\n\ttextual_data_no_stops = remove_stopwords(textual_data, status_logger_name)\n\t'''Prepares bigrams'''\n\ttextual_data_words_bigrams = make_bigrams(textual_data_no_stops, status_logger_name)\n\t'''Lemmatization: Running -> Run'''\n\ttextual_data_lemmatized = lemmatization(status_logger_name, textual_data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])\n\t'''Creating a dictionary for each term as the key, and the value as their frequency in that sentence.'''\n\tid2word = corpora.Dictionary(textual_data_lemmatized)\n\n\ttexts = textual_data_lemmatized\n\t'''Creating a dictionary for the entire corpus and not just individual abstracts and documents.'''\n\tcorpus = [id2word.doc2bow(text) for text in texts]\n\n\t'''Builds the actual LDA model that will be used for the visualization and inference'''\n\tlda_model_generation_start_status_key = \"Generating the LDA model using default parameter set\"\n\tstatus_logger(status_logger_name, lda_model_generation_start_status_key)\n\n\tif(mallet_path):\n\t\tlda_model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics = num_topics, id2word=id2word)\n\n\t\t'''Generating a dataset to show which '''\n\t\tdf_topic_sents_keywords = format_topics_sentences(ldamodel = lda_model, corpus = corpus, texts = textual_data)\n\t\tdf_dominant_topic = df_topic_sents_keywords.reset_index()\n\t\tdf_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text']\n\t\tdf_dominant_topic.to_csv(logs_folder_name + '/Master_Topic_Per_Sentence.csv')\n\n\t\t'''Generating a dataset to present the percentage of papers under each topic, their keywords and number of papers'''\n\t\tsent_topics_sorteddf_mallet = pd.DataFrame()\n\t\tsent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic')\n\t\tfor i, grp in sent_topics_outdf_grpd:\n\t\t\tsent_topics_sorteddf_mallet = pd.concat([sent_topics_sorteddf_mallet, grp.sort_values(['Perc_Contribution'], ascending=[0]).head(1)], axis=0)\n\t\tsent_topics_sorteddf_mallet.reset_index(drop=True, inplace=True)\n\t\ttopic_counts = df_topic_sents_keywords['Dominant_Topic'].value_counts()\n\t\ttopic_contribution = round(topic_counts/topic_counts.sum(), 4)\n\t\tsent_topics_sorteddf_mallet.columns = ['Topic_Num', \"Topic_Perc_Contrib\", \"Keywords\", \"Text\"]\n\t\tsent_topics_sorteddf_mallet.head()\n\t\tsent_topics_sorteddf_mallet['Number_Papers'] = [topic_counts[count] for count in range(num_topics)]\n\t\tsent_topics_sorteddf_mallet['Percentage_Papers'] = [topic_contribution[count] for count in range(0, num_topics)]\n\t\tsent_topics_sorteddf_mallet.to_csv(logs_folder_name+'/Master_Topics_Contribution.csv')\n\n\t\t'''Converting the mallet model to LDA for use by the Visualizer code'''\n\t\tlda_model = gensim.models.wrappers.ldamallet.malletmodel2ldamodel(lda_model)\n\n\telse:\n\t\tlda_model = gensim.models.ldamodel.LdaModel(corpus = corpus, id2word = id2word, num_topics = num_topics, random_state = 100, update_every = 1, chunksize = 100, passes = 10, alpha = 'auto', per_word_topics = True)\n\n\tlda_model_generation_end_status_key = \"Generated the LDA model using default parameter set\"\n\tstatus_logger(status_logger_name, lda_model_generation_end_status_key)\n\n\tperplexity_score = lda_model.log_perplexity(corpus)\n\n\tperplexity_status_key = \"Issued perplexity:\"+\" \"+str(perplexity_score)\n\tstatus_logger(status_logger_name, perplexity_status_key)\n\n\tnlp_engine_main_end_status_key = \"Idling the NLP Engine\"\n\tstatus_logger(status_logger_name, nlp_engine_main_end_status_key)\n\n\t'''Importing the visualizer_main function to view the LDA Model built by the NLP_engine_main() function'''\n\tvisualizer_main(lda_model, corpus, id2word, textual_data_lemmatized, num_topics, num_keywords, logs_folder_name, status_logger_name)\n\n\treturn 0" }, { "alpha_fraction": 0.7190326452255249, "alphanum_fraction": 0.7214325070381165, "avg_line_length": 45.30769348144531, "blob_id": "a7caceb3bb98d323c6af26280c45ea987e56c131", "content_id": "78d85189f63c3e64f1501d43fe71aeb26c9517cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5417, "license_type": "permissive", "max_line_length": 149, "num_lines": 117, "path": "/pyResearchInsights/Cleaner.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''\nHello! This script is part of the larger pyResearchInsights project that you can check out here: https://github.com/SarthakJShetty/pyResearchInsights\nWe are trying to build an end-to-end ACA tool here\n-Sarthak\n(03/10/2019)\n\nPurpose of this script:\nClean the corpus of special character'''\n\n'''Importing the status logger function here to LOG the cleaner module working for debugging'''\nfrom pyResearchInsights.common_functions import status_logger\n\n'''This holds the elements of the abstract after it has been split at the spaces'''\nelements = []\n'''Holds the dirty elements that contain the \\\\ and // in them'''\ndirty_elements = []\n'''Holds the clean members of the abstract elements'''\ncleaned_str_list = []\n'''Holds the screened abstracts, null of any special character occurances'''\ncleaned_texts = []\n\n'''What needs to be implemented here?\n1. A way for each element containing \\\\ to be put into a list.\n2. Subtract said list from elements'''\n\ndef txt_to_list(abstract_directory, status_logger_name):\n '''Converting the text file to a list for easier processing'''\n txt_to_list_start_status_key = \"Converting text to list\"\n status_logger(status_logger_name, txt_to_list_start_status_key)\n\n try:\n '''If the Cleaner script is run independently, not as part of the pipeline as a whole, there would be no filename_ANALYTICAL.txt.\n This ensures that that file can be processed independently.'''\n cleaner_abstract_directory = (abstract_directory.split(\".txt\")[0])+\"_\"+'ANALYTICAL.txt'\n folder = open(cleaner_abstract_directory, 'r')\n except FileNotFoundError:\n cleaner_abstract_directory = (abstract_directory.split(\".txt\")[0])+'.txt'\n folder = open(cleaner_abstract_directory, 'r')\n\n abstracts = []\n\n for line in folder:\n abstracts.append(line)\n\n txt_to_list_end_status_key = \"Converted text to list\"\n status_logger(status_logger_name, txt_to_list_end_status_key)\n\n return abstracts\n\ndef dirty_element_generator(texts, status_logger_name):\n '''Finds all the elements which have the special character in them, makes a list and\n referes through them durng the next phases'''\n dirty_element_generator_start_status_key = \"Generating list with special elements for weeding out later\"\n status_logger(status_logger_name, dirty_element_generator_start_status_key)\n\n for text in texts:\n elements = text.split(\" \")\n for element in elements:\n if('\\\\' in element):\n dirty_elements.append(element)\n \n dirty_element_generator_end_status_key = \"Generated list with special elements for weeding out later\"\n status_logger(status_logger_name, dirty_element_generator_end_status_key)\n\n return dirty_elements\n\ndef dirty_element_weeder(texts, dirty_elements, status_logger_name):\n '''Refers to the list of dirty variables and cleans the abstracts'''\n dirty_element_weeder_start_status_key = \"Removing elements with special characters from the text list\"\n status_logger(status_logger_name, dirty_element_weeder_start_status_key)\n\n cleaned_str_list =[]\n for text in texts:\n elements = text.split(\" \")\n for element in elements:\n if element not in dirty_elements:\n cleaned_str_list.append(element)\n cleaned_texts.append(\" \".join(lol for lol in cleaned_str_list))\n cleaned_str_list = []\n\n dirty_element_weeder_end_status_key = \"Removed elements with special characters from the text list\"\n status_logger(status_logger_name, dirty_element_weeder_end_status_key)\n \n return cleaned_texts\n\ndef cleaned_abstract_dumper(abstract_directory, cleaned_texts, status_logger_name):\n '''Dumping the cleaned abstracts to the disc and will be referring to it henceforth in the code'''\n cleaned_abstract_dumper_start_status_key = \"Dumping the cleaned abstract .txt to the disc\"\n status_logger(status_logger_name, cleaned_abstract_dumper_start_status_key)\n\n pre_new_cleaned_texts_folder = abstract_directory.split(\".txt\")[0]\n new_cleaned_texts_folder = open(pre_new_cleaned_texts_folder + \"_\"+\"CLEANED.txt\", 'w')\n\n for cleaned_text in cleaned_texts:\n new_cleaned_texts_folder.write(cleaned_text)\n new_cleaned_texts_folder.write('\\n')\n\n cleaned_abstract_dumper_end_status_key = \"Dumped the cleaned abstract .txt to the disc\"\n status_logger(status_logger_name, cleaned_abstract_dumper_end_status_key)\n\n return new_cleaned_texts_folder\n \ndef cleaner_main(abstract_directory, status_logger_name):\n '''This module removes all the special characters from the abstract scrapped using the Bias tool.'''\n cleaner_main_start_status_key = \"Entering the Cleaner module\"\n status_logger(status_logger_name, cleaner_main_start_status_key)\n\n abstracts = txt_to_list(abstract_directory, status_logger_name)\n dirty_elements = dirty_element_generator(abstracts, status_logger_name)\n cleaned_texts = dirty_element_weeder(abstracts, dirty_elements, status_logger_name)\n new_cleaned_texts_folder = cleaned_abstract_dumper(abstract_directory, cleaned_texts, status_logger_name)\n '''Main contribution from this block of the code is the new cleaned .txt folder and cleaned abstracts. Just in case.'''\n \n cleaner_main_end_status_key = \"Exiting the Cleaner module\"\n status_logger(status_logger_name, cleaner_main_end_status_key)\n\n return cleaned_texts, new_cleaned_texts_folder" }, { "alpha_fraction": 0.7882787585258484, "alphanum_fraction": 0.7925026416778564, "avg_line_length": 48.8684196472168, "blob_id": "833436339fa0f42f93c3b6cf78edb3a7169b8d78", "content_id": "419320dadde899e6bb031772bb25582c22a59bc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1894, "license_type": "permissive", "max_line_length": 145, "num_lines": 38, "path": "/pyResearchInsights/example.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''Hello! We have decided to modularize the entire code, and run it off of one common script.\nIn the future, the Analyzer.py and the Visualizer.py scripts will be called here as well.\n\nCheck out the build-log.md for a detailed changes implemented.\nCheck out the README.md for more details about the project.\n\nSarthak J. Shetty\n12/09/2018'''\n\n'''Imports scraper_main() from Scraper.py'''\nfrom pyResearchInsights.Scraper import scraper_main\n'''Importing the analyzer code here as well'''\nfrom pyResearchInsights.Analyzer import analyzer_main\n'''Importing the Cleaner functions here that removes special characters from the corpus'''\nfrom pyResearchInsights.Cleaner import cleaner_main\n'''Importing the visualizer and gensim code here'''\nfrom pyResearchInsights.NLP_Engine import nlp_engine_main\n'''Imports some of the functions required by different scripts here.'''\nfrom pyResearchInsights.common_functions import pre_processing\n'''Declaring tarballer here from system_functions() to tarball the LOG directory, & rm_original_folder to delete the directory and save space.'''\nfrom pyResearchInsights.system_functions import tarballer, rm_original_folder\n\nkeywords_to_search = \"Western Ghats Conservation\"\n\n'''Calling the pre_processing functions here so that abstracts_log_name and status_logger_name is available across the code.'''\nabstracts_log_name, status_logger_name = pre_processing(keywords_to_search)\n\n'''Runs the scraper here to scrape the details from the scientific repository'''\nscraper_main(keywords_to_search, abstracts_log_name, status_logger_name)\n\n'''Cleaning the corpus here before any of the other modules use it for analysis'''\ncleaner_main(abstracts_log_name, status_logger_name)\n\n'''Calling the Analyzer Function here'''\nanalyzer_main(abstracts_log_name, status_logger_name)\n\n'''Calling the visualizer code below this portion'''\nnlp_engine_main(abstracts_log_name, status_logger_name)" }, { "alpha_fraction": 0.7319076657295227, "alphanum_fraction": 0.7340771555900574, "avg_line_length": 53.694915771484375, "blob_id": "6a0a4640d702ffda1cf31845001f2381e746fff3", "content_id": "3007c25923680cbca7c1ab2eb87e00590ad53f4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6453, "license_type": "permissive", "max_line_length": 358, "num_lines": 118, "path": "/pyResearchInsights/Analyzer.py", "repo_name": "SarthakJShetty/pyResearchInsights", "src_encoding": "UTF-8", "text": "'''This code is part of the larger pyResearchInsights project, where we aim\nto study the research themes being discussed in scientific publications.\n\nThis portion of the code analyzes the contents of the .txt file developed\nby the Scraper.py and saves it to a .csv for later visualization by the\nsoon to be built Visualizer.py script\n\nSarthak J. Shetty\n01/09/2018'''\n\n'''Importing OS here to split the filename at the extension'''\nimport os\n'''Importing status_logger here to log the details of the process run.'''\nfrom pyResearchInsights.common_functions import status_logger\n'''Importing the collections which contains the Counter function'''\nfrom collections import Counter\n'''Importing pandas here to build the dataframe'''\nimport pandas as pd\n'''Importing numpy here to build the index of the pandas frameword'''\nimport numpy as np\n\ndef analyzer_pre_processing(abstracts_log_name, status_logger_name):\n\t'''Carries out the pre-processing tasks, such as folder creation'''\n\tanalyzer_pre_processing_status_key=\"Carrying out pre-processing functions for analyzer\"\n\tstatus_logger(status_logger_name, analyzer_pre_processing_status_key)\n\n\ttry:\n\t\t'''If the Analyzer script is run independently, not as part of the pipeline as a whole, there would be no filename_CLEAND.txt.\n\t\tThis ensures that that file can be processed independently.'''\n\t\tabstracts_txt_file_name = (abstracts_log_name.split(\".txt\")[0])+\"_\"+'CLEANED.txt'\n\t\topen(abstracts_txt_file_name, 'r')\n\texcept FileNotFoundError:\n\t\tabstracts_txt_file_name = (abstracts_log_name.split(\".txt\")[0])+'.txt'\n\n\t'''This code strips the abstracts_log_name of its extension and adds a .csv to it'''\n\tabstracts_csv_file_name = (abstracts_log_name.split(\".txt\")[0]) + \"_\" + \"FREQUENCY_CSV_DATA\" + \".csv\"\n\n\tanalyzer_pre_processing_status_key = \"Carried out pre-processing functions for analyzer\"\n\tstatus_logger(status_logger_name, analyzer_pre_processing_status_key)\n\n\treturn abstracts_txt_file_name, abstracts_csv_file_name\n\ndef list_cleaner(list_to_be_cleaned, status_logger_name):\n\tlist_cleaner_start_status_key = \"Cleaning the list of words generated\"\n\tstatus_logger(status_logger_name, list_cleaner_start_status_key)\n\n\t'''This function cleans the list containing the words found in the abstract. It eliminates words found in another pre-defined list of words.'''\n\twords_to_be_eliminated = ['from', 'subject', 're', 'edu', 'use', 'com', 'https', 'url', 'link', 'abstract', 'author', 'chapter', 'springer', 'title', \"the\", \"of\", \"and\", \"in\", \"to\", \"a\", \"is\", \"for\", \"from\", \"with\", \"that\", \"by\", \"are\", \"on\", \"was\", \"as\", \n\t\"were\", \"url:\", \"abstract:\", \"abstract\", \"author:\", \"title:\", \"at\", \"be\", \"an\", \"have\", \"this\", \"which\", \"study\", \"been\", \"not\", \"has\", \"its\", \"also\", \"these\", \"this\", \"can\", \"a\", 'it', 'their', \"e.g.\", \"those\", \"had\", \"but\", \"while\", \"will\", \"when\", \"only\", \"author\", \"title\", \"there\", \"our\", \"did\", \"as\", \"if\", \"they\", \"such\", \"than\", \"no\", \"-\", \"could\"]\n\n\tcleaned_list_of_words_in_abstract = [item for item in list_to_be_cleaned if item not in words_to_be_eliminated]\n\n\tlist_cleaner_end_status_key = \"Cleaned the list of words generated\"\n\tstatus_logger(status_logger_name, list_cleaner_end_status_key)\t\n\n\treturn cleaned_list_of_words_in_abstract\n\ndef transfer_function(abstracts_txt_file_name, abstracts_csv_file_name, status_logger_name):\n\t'''This function is involved in the actual transfer of data from the .txt file to the .csv file'''\n\ttransfer_function_status_key = \"Copying data from\"+\" \"+str(abstracts_txt_file_name)+\" \"+\"to\"+\" \"+\"pandas dataframe\"\n\tstatus_logger(status_logger_name, transfer_function_status_key)\n\n\t'''This list will contain all the words extracted from the .txt abstract file'''\n\tlist_of_words_in_abstract=[]\n\n\t'''Each word is appended to the list, from the .txt file'''\n\twith open(abstracts_txt_file_name, 'r') as abstracts_txt_data:\n\t\tfor line in abstracts_txt_data:\n\t\t\tfor word in line.split():\n\t\t\t\tlist_of_words_in_abstract.append(word)\n\n\t'''This function cleans up the data of uneccessary words'''\n\tcleaned_list_of_words_in_abstract = list_cleaner(list_of_words_in_abstract, status_logger_name)\n\n\t'''A Counter is a dictionary, where the value is the frequency of term, which is the key'''\n\tdictionary_of_abstract_list = Counter(cleaned_list_of_words_in_abstract)\n\n\tlength_of_abstract_list = len(dictionary_of_abstract_list)\n\n\t'''Building a dataframe to hold the data from the list, which in turn contains the data from '''\n\tdataframe_of_abstract_words=pd.DataFrame(index=np.arange(0, length_of_abstract_list), columns=['Words', 'Frequency'])\n\n\t'''An element to keep tab of the number of elements being added to the list'''\n\tdictionary_counter = 0\n\n\t'''Copying elements from the dictionary to the pandas file'''\n\tfor dictionary_element in dictionary_of_abstract_list:\n\t\tif(dictionary_counter==length_of_abstract_list):\n\t\t\tpass\n\t\telse:\n\t\t\tdataframe_of_abstract_words.loc[dictionary_counter, 'Words'] = dictionary_element\n\t\t\tdataframe_of_abstract_words.loc[dictionary_counter, 'Frequency'] = dictionary_of_abstract_list[dictionary_element]\n\t\t\tdictionary_counter = dictionary_counter+1\n\n\ttransfer_function_status_key = \"Copied data from\"+\" \"+str(abstracts_txt_file_name)+\" \"+\"to\"+\" \"+\"pandas dataframe\"\n\tstatus_logger(status_logger_name, transfer_function_status_key)\n\n\ttransfer_function_status_key = \"Copying data from pandas dataframe to\"+\" \"+str(abstracts_csv_file_name)\n\tstatus_logger(status_logger_name, transfer_function_status_key)\n\n\t'''Saving dataframe to csv file, without the index column'''\n\tdataframe_of_abstract_words.to_csv(abstracts_csv_file_name, index=False)\n\n\ttransfer_function_status_key = \"Copied data from pandas dataframe to\"+\" \"+str(abstracts_csv_file_name)\n\tstatus_logger(status_logger_name, transfer_function_status_key)\n\ndef analyzer_main(abstracts_log_name, status_logger_name):\n\t'''Declaring the actual analyzer_main function is integrated to Bias.py code'''\n\tanalyzer_main_status_key=\"Entered the Analyzer.py code.\"\n\tstatus_logger(status_logger_name, analyzer_main_status_key)\n\n\t'''Calling the pre-processing and transfer functions here'''\n\tabstracts_txt_file_name, abstracts_csv_file_name = analyzer_pre_processing(abstracts_log_name, status_logger_name)\n\ttransfer_function(abstracts_txt_file_name, abstracts_csv_file_name, status_logger_name)\n\n\t'''Logs the end of the process Analyzer code in the status_logger'''\n\tanalyzer_main_status_key=\"Exiting the Analyzer.py code.\"\n\tstatus_logger(status_logger_name, analyzer_main_status_key)" } ]
10
wwfxuk/changelog-cli
https://github.com/wwfxuk/changelog-cli
1b49dec934143d5e051f5f89e539f74649f31666
ec6c6d3c70b0a8a9add06f51d44cc5252380a176
8dd211a12b8763316cca9941d8e1612e477dc8d2
refs/heads/master
2020-12-10T17:14:38.848511
2020-01-14T18:59:56
2020-01-14T18:59:56
233,656,488
0
0
null
2020-01-13T17:45:49
2020-01-14T12:40:07
2020-01-14T18:59:56
Python
[ { "alpha_fraction": 0.5704772472381592, "alphanum_fraction": 0.586015522480011, "avg_line_length": 19.953489303588867, "blob_id": "8c3c84375fa5c23d5e998a4fde049f40665b20ad", "content_id": "a52526c55e55bd65f690ca0c9f35108eecd181ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 901, "license_type": "no_license", "max_line_length": 117, "num_lines": 43, "path": "/src/changelog/templates.py", "repo_name": "wwfxuk/changelog-cli", "src_encoding": "UTF-8", "text": "BASE = \"\"\"# CHANGELOG\n\nAll notable changes to this project will be documented in this file.\nThis project adheres to [Semantic Versioning](http://semver.org/) and [Keep a Changelog](http://keepachangelog.com/).\n\"\"\"\n\nUNRELEASED = \"\"\"\n## Unreleased\n---\n\n### New\n\n### Changes\n\n### Fixes\n\n### Breaks\n\n\n\"\"\"\n\nINIT = BASE + UNRELEASED\n\nDEFAULT_VERSION = \"0.0.0\"\n\nRELEASE_LINE = \"## {0} - ({1})\\n\"\n\nDATE_REGEX = r'(?P<date>\\d{4}-\\d{2}-\\d{2})'\nLOCAL_REGEX = r'(?P<local>\\+[a-zA-Z0-9][a-zA-Z0-9\\.]*[a-zA-Z0-9])'\nVERSION_REGEX = r'\\d+\\.\\d+\\.\\d+'\nFULL_VERSION_REGEX = r'(?P<version>{version}{local}?)'.format(\n version=VERSION_REGEX,\n local=LOCAL_REGEX,\n)\n\nRELEASE_LINE_REGEXES = [\n regex.format(full_version=FULL_VERSION_REGEX, date=DATE_REGEX)\n for regex in [\n r\"^##\\s{full_version}\\s\\-\\s\\({date}\\)$\",\n r\"^##\\sv?{full_version}\",\n r\"^##\\s\\[{full_version}\\]\\s\\-\\s{date}$\",\n ]\n]\n" } ]
1
lbarchive/b.py
https://github.com/lbarchive/b.py
76357689649b17ad26099382a5d5b2994402da91
18b533dc40e5fdf7ba62209b51584927c2dd9ba0
928146f23c6232c40280199e57447b24b1912f6c
refs/heads/master
2020-11-25T20:52:31.303486
2016-02-26T06:13:41
2016-02-26T06:13:41
228,841,391
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7291393876075745, "alphanum_fraction": 0.7326343655586243, "avg_line_length": 33.164180755615234, "blob_id": "ed78a586995b5410eb1ab122f574846f1e260c35", "content_id": "2b9dc281b4ca82e8a63a5e2724feef2c51047248", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "permissive", "max_line_length": 79, "num_lines": 67, "path": "/tests/test_bpy_handlers_text.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\nimport test_bpy_handlers_base as test_base\nfrom bpy.handlers.text import Handler\n\n\nclass HandlerTestCase(test_base.BaseHandlerTestCase):\n\n def setUp(self):\n\n self.handler = Handler(None)\n\n # =====\n\n def test_generate_title_pre_wrap_oneline(self):\n\n handler = self.handler\n handler.options['pre_wrap'] = True\n super(HandlerTestCase, self).test_generate_title_oneline()\n\n def test_generate_pre_wrap_multiline(self):\n\n handler = self.handler\n handler.options['pre_wrap'] = True\n super(HandlerTestCase, self).test_generate_title_multiline()\n\n def test_generate_pre_wrap_common_markup(self):\n\n handler = self.handler\n handler.options['pre_wrap'] = True\n super(HandlerTestCase, self).test_generate_title_common_markup()\n\n # =====\n\n def test_embed_images(self):\n\n handler = self.handler\n self.assertRaises(RuntimeError, handler.embed_images, ('', ))\n\n def test_embed_images_generate(self):\n\n handler = self.handler\n handler.options['embed_images'] = True\n\n handler.markup = '<img src=\"http://example.com/example.png\"/>'\n html = handler.generate()\n EXPECT = '&lt;img src=\"http://example.com/example.png\"/&gt;'\n self.assertEqual(html, EXPECT)\n" }, { "alpha_fraction": 0.6289893388748169, "alphanum_fraction": 0.6289893388748169, "avg_line_length": 18.789474487304688, "blob_id": "cc16caf2186b4b4f6e40223ca81cee828c78b324", "content_id": "a2dad2f972a552abcc94c18b126ff95a13b70419", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 752, "license_type": "permissive", "max_line_length": 79, "num_lines": 38, "path": "/docs/configuration.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "=============\nConfiguration\n=============\n\n.. _brc.py:\n\n``brc.py``\n==========\n\n``brc.py`` is the configuration that :doc:`b.py` reads from the current working\ndirectory, it may look like:\n\n.. code:: python\n\n service = '<service id>'\n service_options = {\n # see below\n }\n\n # Normally, you only need settings above.\n # For customized handlers and services, you can specify:\n\n handlers = {\n # see below\n }\n\n services = {\n # see below\n }\n\nA normal ``brc.py`` only needs ``service`` and ``service_options``, but you can\nadd customized handlers and services.\n\n.. seealso:: :ref:`Service options <service-options>`\n\n.. seealso:: :ref:`Writing a custom handler <custom-handler>`\n\n.. seealso:: :ref:`Writing a custom service <custom-service>`\n" }, { "alpha_fraction": 0.6762778759002686, "alphanum_fraction": 0.6815203428268433, "avg_line_length": 29.11842155456543, "blob_id": "591d6e76d9f931ffdcb100ecf30d156e38aff794", "content_id": "d7c23e222929e53f69ec788d4e659e88af152d34", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "permissive", "max_line_length": 79, "num_lines": 76, "path": "/bpy/handlers/mkd.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nYou can specify `configuration`__ for Python Markdown in :ref:`brc.py` or\nembed_images_, for example:\n\n__ http://packages.python.org/Markdown/reference.html#markdown\n\n.. code:: python\n\n handlers = {\n 'Markdown': {\n 'options': {\n 'config': {\n 'extensions': ['extension1', 'extension2'],\n 'tab_length': 8,\n },\n 'embed_images': True,\n },\n },\n }\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nimport markdown\n\nfrom bpy.handlers import base\n\n\nclass Handler(base.BaseHandler):\n \"\"\"Handler for Markdown markup language\n\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n <!-- !b\n title: foobar\n -->\n <BLANKLINE>\n \"\"\"\n\n PREFIX_HEAD = '<!-- '\n PREFIX_END = '-->'\n HEADER_FMT = '%s: %s'\n\n def _generate(self, markup=None):\n \"\"\"Generate HTML from Markdown\n\n >>> handler = Handler(None)\n >>> print(handler._generate('a *b*'))\n <p>a <em>b</em></p>\n \"\"\"\n if markup is None:\n markup = self.markup\n\n # markdown library only accepts unicode, utf8 encoded str results in error.\n html = markdown.markdown(markup, **self.options.get('config', {}))\n return html\n" }, { "alpha_fraction": 0.6378747820854187, "alphanum_fraction": 0.6434674263000488, "avg_line_length": 28.126697540283203, "blob_id": "52c8de4563867d1b686f4f0a3b54c49b5e24caf1", "content_id": "2959af169e729db8be7ba1725d5b1686b6c154d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6437, "license_type": "permissive", "max_line_length": 79, "num_lines": 221, "path": "/b.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Copyright (C) 2013-2016 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\n============\nb.py command\n============\n\n\nCommands\n========\n\n============= =======================\ncommand supported services\n============= =======================\n``blogs`` ``b``\n``post`` ``b``, ``wp``\n``generate`` ``base``, ``b``, ``wp``\n``checklink`` ``base``, ``b``, ``wp``\n``search`` ``b``\n============= =======================\n\nDescriptions:\n\n``blogs``\n list blogs. This can be used for blog IDs lookup.\n\n``post``\n post or update a blog post.\n\n``generate``\n generate HTML file at ``<TEMP>/draft.html``, where ``<TEMP>`` is the system's\n temporary directory.\n\n The generation can output a preview html at ``<TEMP>/preview.html`` if there\n is ``tmpl.html``. It will replace ``%%Title%%`` with post title and\n ``%%Content%%`` with generated HTML.\n\n``checklink``\n check links in generated HTML using lnkckr_.\n\n``search``\n search blog\n\n.. _lnkckr: https://pypi.python.org/pypi/lnkckr\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse as ap\nimport codecs\nimport imp\nimport logging\nimport os\nimport sys\nimport traceback\n\nfrom bpy.handlers import handlers\nfrom bpy.services import find_service, services\n\n__program__ = 'b.py'\n__description__ = 'Post to Blogger or WordPress in markup language seamlessly'\n__copyright__ = 'Copyright 2013-2016, Yu Jie Lin'\n__license__ = 'MIT License'\n__version__ = '0.11.0'\n__website__ = 'http://bitbucket.org/livibetter/b.py'\n\n__author__ = 'Yu-Jie Lin'\n__author_email__ = '[email protected]'\n\n\n# b.py stuff\n############\n\n# filename of local configuration without '.py' suffix.\nBRC = 'brc'\n\n\ndef parse_args():\n\n p = ap.ArgumentParser()\n p.add_argument('--version', action='version',\n version='%(prog)s ' + __version__)\n p.add_argument('-d', '--debug', action='store_true',\n help='turn on debugging messages')\n p.add_argument('-s', '--service', default='base',\n help='what service to use. (Default: %(default)s)')\n sp = p.add_subparsers(help='commands')\n\n pblogs = sp.add_parser('blogs', help='list blogs')\n pblogs.set_defaults(subparser=pblogs, command='blogs')\n\n psearch = sp.add_parser('search', help='search for posts')\n psearch.add_argument('-b', '--blog', help='Blog ID')\n psearch.add_argument('q', nargs='+', help='query text')\n psearch.set_defaults(subparser=psearch, command='search')\n\n pgen = sp.add_parser('generate', help='generate html')\n pgen.add_argument('filename')\n pgen.set_defaults(subparser=pgen, command='generate')\n\n pchk = sp.add_parser('checklink', help='check links in chkerateed html')\n pchk.add_argument('filename')\n pchk.set_defaults(subparser=pchk, command='checklink')\n\n ppost = sp.add_parser('post', help='post or update a blog post')\n ppost.add_argument('filename')\n ppost.set_defaults(subparser=ppost, command='post')\n\n args = p.parse_args()\n return args\n\n\ndef load_config():\n\n rc = None\n try:\n search_path = [os.getcwd()]\n _mod_data = imp.find_module(BRC, search_path)\n print('Loading local configuration...')\n try:\n rc = imp.load_module(BRC, *_mod_data)\n finally:\n if _mod_data[0]:\n _mod_data[0].close()\n except ImportError:\n pass\n except Exception:\n traceback.print_exc()\n print('Error in %s, aborted.' % _mod_data[1])\n sys.exit(1)\n return rc\n\n\ndef main():\n\n args = parse_args()\n\n logging.basicConfig(\n format=(\n '%(asctime)s '\n '%(levelname).4s '\n '%(module)5.5s:%(funcName)-10.10s:%(lineno)04d '\n '%(message)s'\n ),\n datefmt='%H:%M:%S',\n )\n if args.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n\n encoding = sys.stdout.encoding\n if not encoding.startswith('UTF'):\n msg = (\n 'standard output encoding is %s, '\n 'try to set with UTF-8 if there is output issues.'\n )\n logging.warning(msg % encoding)\n if sys.version_info.major == 2:\n sys.stdout = codecs.getwriter(encoding)(sys.stdout, 'replace')\n sys.stderr = codecs.getwriter(encoding)(sys.stderr, 'replace')\n elif sys.version_info.major == 3:\n sys.stdout = codecs.getwriter(encoding)(sys.stdout.buffer, 'replace')\n sys.stderr = codecs.getwriter(encoding)(sys.stderr.buffer, 'replace')\n\n rc = load_config()\n service_options = {'blog': None}\n if rc:\n if hasattr(rc, 'handlers'):\n for name, handler in rc.handlers.items():\n if name in handlers:\n handlers[name].update(handler)\n else:\n handlers[name] = handler.copy()\n if hasattr(rc, 'services'):\n for name, service in rc.services.items():\n if name in services:\n services[name].update(service)\n else:\n services[name] = service.copy()\n if hasattr(rc, 'service'):\n args.service = rc.service\n if hasattr(rc, 'service_options'):\n service_options.update(rc.service_options)\n\n if hasattr(args, 'blog') and args.blog is not None:\n service_options['blog'] = args.blog\n filename = args.filename if hasattr(args, 'filename') else None\n service = find_service(args.service, service_options, filename)\n\n if args.command == 'blogs':\n service.list_blogs()\n elif args.command == 'search':\n service.search(' '.join(args.q))\n elif args.command == 'generate':\n service.generate()\n elif args.command == 'checklink':\n service.checklink()\n elif args.command == 'post':\n service.post()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 17, "blob_id": "95037991d7cf38d8359c9a07d08ae1672c35476f", "content_id": "25cb68a07c641e3266c1143288b44102d73c8910", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 18, "license_type": "permissive", "max_line_length": 17, "num_lines": 1, "path": "/docs/b.py.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": ".. automodule:: b\n" }, { "alpha_fraction": 0.5370675325393677, "alphanum_fraction": 0.5464030504226685, "avg_line_length": 33.037384033203125, "blob_id": "c9749e7b38eda484e032906b907528e61e3b6b88", "content_id": "5eff6f3f39cfdbd199fd1cfa167eb6bf0def077e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3642, "license_type": "permissive", "max_line_length": 98, "num_lines": 107, "path": "/Makefile", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nPACKAGE=b.py\nSCRIPT=b.py\n\nPY2_CMD=python2\nPY3_CMD=python3\nINSTALL_TEST_DIR=/tmp/$(PACKAGE)_install_test\n\nBUILD_CMD=./setup.py sdist --formats gztar,zip bdist_wheel bdist_wininst --plat-name win32\n\nDOC_FILES = docs/conf.py $(wildcard docs/*.rst) CHANGES.rst\nBPY_FILES = b.py $(wildcard bpy/*.py) $(wildcard bpy/*/*.py)\n\n# ============================================================================\n\nbuild:\n\t$(BUILD_CMD)\n\nupload:\n\t$(BUILD_CMD) upload\n\nupload_doc: doc\n\t$(PY2_CMD) setup.py upload_sphinx\n\n# ============================================================================\n\ndoc: apidoc docs/_build/html\n\ndocs/_build/html: $(DOC_FILES) $(BPY_FILES)\n\tmake -C docs html\n\napidoc: docs/apidoc\n\ndocs/apidoc: $(BPY_FILES)\n\trm -rf docs/apidoc\n\tsphinx-apidoc -f -T -o docs/apidoc bpy\n\n# ============================================================================\n\ntest: test_isort test_pep8 test_pyflakes test_test test_setup\n\ntest_%:\n\t@echo '========================================================================================='\n\t$(PY2_CMD) setup.py $(subst test_,,$@)\n\t@echo '-----------------------------------------------------------------------------------------'\n\t$(PY3_CMD) setup.py $(subst test_,,$@)\n\ntest_doc8:\n\t@echo '========================================================================================='\n\tdoc8 ${DOC_FILES}\n\ntest_setup: test_setup_py2 test_setup_py3\n\ntest_setup_py2 test_setup_py3:\n\t@echo '========================================================================================='\n\trm -rf $(INSTALL_TEST_DIR)\n\t$(eval PY_CMD = \\\n\t\t$(if $(findstring py2,$@),\\\n\t\t\t$(PY2_CMD),\\\n\t\t\t$(if $(findstring py3,$@),\\\n\t\t\t\t$(PY3_CMD),\\\n\t\t\t\t$(error Do not know what to do with $@)\\\n\t\t\t)\\\n\t\t)\\\n\t)\n\t$(PY_CMD) -m virtualenv $(INSTALL_TEST_DIR)\n\tLC_ALL=C $(PY_CMD) setup.py --version >/dev/null\n\t$(PY_CMD) $(BUILD_CMD)\n\t$(PY_CMD) setup.py sdist --dist-dir $(INSTALL_TEST_DIR)\n\t$(INSTALL_TEST_DIR)/bin/pip install $(INSTALL_TEST_DIR)/*.tar.gz\n\t@\\\n\t\tCHK_VER=\"`$(PY_CMD) $(SCRIPT) --version 2>&1`\";\\\n\t\tcd $(INSTALL_TEST_DIR);\\\n\t\t. bin/activate;\\\n\t\t[ \"`type $(SCRIPT)`\" = \"$(SCRIPT) is $(INSTALL_TEST_DIR)/bin/$(SCRIPT)\" ] &&\\\n\t\t[ \"$$CHK_VER\" = \"`bin/$(SCRIPT) --version 2>&1`\" ]\n\trm -rf $(INSTALL_TEST_DIR)\n\n# ============================================================================\n\nclean:\n\trm -rf *.pyc build dist __pycache__\n\trm -rf docs/apidoc\n\tmake -C docs clean\n\n# ============================================================================\n\n.PHONY: build upload doc apidoc test_setup test_setup_py2 test_setup_py3 clean\n" }, { "alpha_fraction": 0.639511227607727, "alphanum_fraction": 0.6429056525230408, "avg_line_length": 23.756301879882812, "blob_id": "31aab0aa9812b53a5463e3f85a7600668486dcfb", "content_id": "de61122f618bd87b1a96d3f1827d4e4ee0eb1a5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2946, "license_type": "permissive", "max_line_length": 79, "num_lines": 119, "path": "/bpy/services/__init__.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nServices' IDs:\n\n========= =====================\nservice IDs\n========= =====================\nBase ``base``\nBlogger ``b``, ``blogger``\nWordPress ``wp``, ``wordpress``\n========= =====================\n\n\n.. _service-options:\n\nOptions\n=======\n\nTo assign options to chosen service, add ``service_options`` in :ref:`brc.py`,\nfor example:\n\n.. code:: python\n\n service = \"<service id>\"\n service_options = {\n 'option1': 'value1',\n 'option2': 2,\n }\n\n\n.. _custom-service:\n\nWriting a custom service\n========================\n\nA sample handler ``sample_service.py``:\n\n.. code:: python\n\n from bpy.service import base\n\n class Service(base.Service):\n\n # see bpy/services for examples\n pass\n\nAnd corresponding setting in :ref:`brc.py`:\n\n.. code:: python\n\n import re\n\n # this matches the re\n service = 'foobar'\n\n services = {\n 'SampleService': {\n 'match': re.compile(r'^foobar$'),\n 'module': 'sample_service',\n },\n }\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport traceback\n\nservices = {\n 'Base': {\n 'match': re.compile(r'^base$', re.I),\n 'module': 'bpy.services.base',\n },\n 'Blogger': {\n 'match': re.compile(r'^(b|blogger)$', re.I),\n 'module': 'bpy.services.blogger',\n },\n 'WordPress': {\n 'match': re.compile(r'^(wp|wordpress)$', re.I),\n 'module': 'bpy.services.wordpress',\n },\n}\n\n\ndef find_service(service_name, service_options, *args, **kwargs):\n\n sys.path.insert(0, os.getcwd())\n module = None\n for name, hdlr in services.items():\n if hdlr['match'].match(service_name):\n try:\n module = __import__(hdlr['module'], fromlist=['Service'])\n break\n except Exception:\n print('Cannot load module %s of service %s' % (hdlr['module'], name))\n traceback.print_exc()\n sys.path.pop(0)\n if module:\n return module.Service(service_options, *args, **kwargs)\n return None\n" }, { "alpha_fraction": 0.7071713209152222, "alphanum_fraction": 0.717131495475769, "avg_line_length": 29.89230728149414, "blob_id": "0c5f85cf54f1c349875e601e0e307a39cde83176", "content_id": "c8e33b9b89e3b53d33864e1ac758337cb61cc40c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2008, "license_type": "permissive", "max_line_length": 79, "num_lines": 65, "path": "/tests/test_bpy_handlers_mkd.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\nfrom __future__ import unicode_literals\n\nimport unittest\n\nimport test_bpy_handlers_base as test_base\nfrom bpy.handlers.mkd import Handler\n\n\nclass HandlerTestCase(test_base.BaseHandlerTestCase):\n\n def setUp(self):\n\n self.handler = Handler(None)\n\n # =====\n\n test_markup_affixes_EXPECT1 = '<p>prefix-content-suffix</p>'\n test_markup_affixes_EXPECT2 = '<p>foobar</p>'\n\n # =====\n\n test_generate_title_common_markup_EXPECT = 'foo <em>bar</em>'\n\n # =====\n\n test_generate_str_EXPECT = '<p>\\xc3\\xa1</p>'\n\n # =====\n\n test_smartypants_EXPECT = '<p>foo &#8220;bar&#8221;</p>'\n\n # =====\n\n @unittest.skip('tested in BaseHandler')\n def test_embed_images(self):\n\n pass\n\n test_embed_images_generate_SOURCE = '![tests/test.png](tests/test.png)'\n test_embed_images_generate_EXPECT = (\n '<p><img alt=\"tests/test.png\" src=\"%s\" /></p>' % (\n test_base.BaseHandlerTestCase.test_embed_images_data_URI\n )\n )\n" }, { "alpha_fraction": 0.6627675890922546, "alphanum_fraction": 0.6656367182731628, "avg_line_length": 27.318750381469727, "blob_id": "d0dc56c0d01b4c3bd503b380cb70efd9ed7d9813", "content_id": "b78a3f6e8b959c569f35dd29ca3e1881906ea421", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4531, "license_type": "permissive", "max_line_length": 79, "num_lines": 160, "path": "/bpy/handlers/rst.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2011-2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nYou can specify settings-overrides_ for reStructuredText in :ref:`brc.py` or\nthe embed_images_, for example:\n\n.. code:: python\n\n handlers = {\n 'reStructuredText': {\n 'options': {\n 'embed_images': True,\n 'register_directives': {\n 'dir_name': MyDir,\n },\n 'register_roles': {\n 'role_name': MyRole,\n },\n 'settings_overrides': {\n 'footnote_references': 'brackets',\n },\n },\n },\n }\n\n.. _settings-overrides:\n http://docutils.sourceforge.net/docs/user/config.html#html4css1-writer\n\n\nCustom Directives and Roles\n===========================\n\nFor adding your own custom reStructuredText directives or roles, you can do it\nin :ref:`brc.py` with one of the following method:\n\n* by calling register functions of docutils directly,\n* by adding in b.py's option as shown above, or\n* by using decorator of b.py, for example:\n\n .. code:: python\n\n from docutils.parsers.rst import Directive\n from bpy.handlers.rst import register_directive, register_role\n\n @register_directive('mydir')\n class MyDir(Directive):\n pass\n\n @register_role('myrole')\n def myrole(name, rawtext, text, lineno, inliner, options=None,\n content=None):\n pass\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nfrom docutils.core import publish_parts\nfrom docutils.parsers.rst import directives, roles\n\nfrom bpy.handlers import base\n\n\ndef register_directive(dir_name):\n \"\"\"For lazy guys\n\n .. code:: python\n\n @register_directive(name)\n class MyDirective(Directive):\n pass\n \"\"\"\n def _register_directive(directive):\n directives.register_directive(dir_name, directive)\n return directive\n return _register_directive\n\n\ndef register_role(role_name):\n\n def _register_role(role):\n\n roles.register_canonical_role(role_name, role)\n return role\n\n return _register_role\n\n\nclass Handler(base.BaseHandler):\n \"\"\"Handler for reStructuredText markup language\n\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n .. !b\n title: foobar\n <BLANKLINE>\n \"\"\"\n\n PREFIX_HEAD = '.. '\n PREFIX_END = ''\n HEADER_FMT = ' %s: %s'\n\n def __init__(self, filename, options=None):\n\n super(Handler, self).__init__(filename, options)\n\n if not options:\n return\n\n for dir_name, directive in options.get('register_directives', {}).items():\n directives.register_directive(dir_name, directive)\n for role_name, role in options.get('register_roles', {}).items():\n roles.register_canonical_role(role_name, role)\n\n def _generate(self, markup=None):\n \"\"\"Generate HTML from Markdown\n\n >>> handler = Handler(None)\n >>> print(handler._generate('a *b*'))\n <p>a <em>b</em></p>\n \"\"\"\n if markup is None:\n markup = self.markup\n\n settings_overrides = {\n 'output_encoding': 'utf8',\n 'initial_header_level': 2,\n 'doctitle_xform': 0,\n 'footnote_references': 'superscript',\n }\n settings_overrides.update(self.options.get('settings_overrides', {}))\n\n id_affix = self.id_affix\n if id_affix:\n settings_overrides['id_prefix'] = id_affix + '-'\n self.set_header('id_affix', id_affix)\n\n doc_parts = publish_parts(markup,\n settings_overrides=settings_overrides,\n writer_name=\"html\")\n\n html = doc_parts['body_pre_docinfo'] + doc_parts['body'].rstrip()\n return html\n" }, { "alpha_fraction": 0.6952869892120361, "alphanum_fraction": 0.705086350440979, "avg_line_length": 22.811111450195312, "blob_id": "54afd4a4a30d7b8a297f411a4b0a7b8d167c80f2", "content_id": "d5635a096c62b8697d373467ce1b246870f5e58d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2143, "license_type": "permissive", "max_line_length": 79, "num_lines": 90, "path": "/docs/header.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "======\nHeader\n======\n\nA header is used to specify the meta-data of a post, such as title or labels,\nit is also used to store information which is needed to update a post later on,\nsuch as ``id``.\n\nGenerally, header can be simply formed as the following regardless which markup\nlanguage handler you use::\n\n !b\n key1: value1\n key2: value2\n\n post content goes here\n\nThe handler will automatically reformed the header into *comment* after posting\nor updating, the format of comment depends on the markup language. For example,\nin reStructuredText, a header look like\n\n.. code:: rst\n\n .. !b\n service: blogger\n kind: post\n title: Title of \"something.\"\n labels: comma, separated, list\n categories: another, comma, separated, list\n draft: False\n blog: 12345\n id: 54321\n id_affix: foobar\n url: http://example.com/2013/01/title-of-something.html\n\nMaking header into comment, so it wouldn't be rendered out if it's processed by\ntools other than *b.py*.\n\n\nKeys\n====\n\n``service``:\n used for processing.\n\n It could be added automatically after successfully posting.\n\n .. seealso:: :doc:`apidoc/bpy.services`\n\n``blog``:\n used in updating post and should not be edited by the user normally.\n\n It could be added automatically after successfully posting.\n\n``id``:\n used in updating post and should not be edited by the user normally.\n\n It could be added automatically after successfully posting.\n\n``title``:\n override the post title.\n\n If not specified, the post title will be the filename without the extension.\n\n``kind``:\n type of the posting, ``post`` or ``page``, default is ``post``.\n\n It could be added automatically after successfully posting.\n\n``labels``:\n labels or tags, comma-separated list.\n\n``categories``:\n categories, comma-separated list.\n\n Only WordPress service uses this.\n\n``draft``:\n the post or page status, ``true``, ``yes``, or ``1`` for draft post,\n otherwise published post or page.\n\n``url``:\n link of the post.\n\n It could be added automatically after successfully posting.\n\n``id_affix``:\n the affix to HTML element ID.\n\n .. seealso:: :ref:`id_affix` in handler options.\n" }, { "alpha_fraction": 0.6483120322227478, "alphanum_fraction": 0.6522451639175415, "avg_line_length": 28.05714225769043, "blob_id": "061c5cb7c4ed549b7a43ff47b7d11384cb8d6fa1", "content_id": "1508d68afa008f1336b1a9093a410f9a7209ecfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3051, "license_type": "permissive", "max_line_length": 79, "num_lines": 105, "path": "/bpy/handlers/text.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nThe Text handler for plain text always escape HTML, and add ``<br/>`` if not\n``pre_wrap``.\n\nYou can specify the following options for plain text in :ref:`brc.py`, for\nexample:\n\n.. code:: python\n\n handlers = {\n 'Text': {\n 'options': {\n 'pre_wrap': False\n },\n },\n }\n\n``pre_wrap`` will wrap output in ``<pre/>`` tag.\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nimport cgi\nimport re\n\nfrom bpy.handlers import base\n\n\nclass Handler(base.BaseHandler):\n \"\"\"Handler for plain text\n\n >>> handler = Handler(None)\n >>> handler.markup = 'post <content>\\\\n & something'\n >>> print(handler.generate())\n post &lt;content&gt;<br/>\n &amp; something\n >>> handler.options['pre_wrap'] = True\n >>> print(handler.generate())\n <pre>post &lt;content&gt;\n &amp; something</pre>\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n !b\n title: foobar\n <BLANKLINE>\n \"\"\"\n\n PREFIX_HEAD = ''\n PREFIX_END = ''\n HEADER_FMT = '%s: %s'\n\n SUPPORT_EMBED_IMAGES = False\n\n def generate_title(self, markup=None):\n \"\"\"Generate HTML from plain text\n\n >>> handler = Handler(None)\n >>> print(handler.generate_title('a < b\\\\nc & d\\\\n\\\\nfoo'))\n a &lt; b c &amp; d foo\n \"\"\"\n html = super(Handler, self).generate_title(markup)\n html = html.replace('<pre>', '').replace('</pre>', '')\n return re.sub('(<br/> )+', ' ', html)\n\n def _generate(self, markup=None):\n \"\"\"Generate HTML from plain text\n\n >>> handler = Handler(None)\n >>> print(handler._generate('a < b\\\\nc & d\\\\n\\\\xc3\\\\xa1'))\n a &lt; b<br/>\n c &amp; d<br/>\n \\xc3\\xa1\n >>> handler.options['pre_wrap'] = True\n >>> print(handler._generate('abc\\\\ndef'))\n <pre>abc\n def</pre>\n \"\"\"\n if markup is None:\n markup = self.markup\n\n html = cgi.escape(markup)\n if self.options.get('pre_wrap', False):\n return '<pre>%s</pre>' % html\n else:\n return html.replace('\\n', '<br/>\\n')\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7344912886619568, "avg_line_length": 39.29999923706055, "blob_id": "21c452d7cfbd6fc0cea5b6d3994c366baf07869c", "content_id": "40195b06358aaed848c706eb80a5df04e929c7ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1612, "license_type": "permissive", "max_line_length": 79, "num_lines": 40, "path": "/tests/test_setup.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport unittest\n\nfrom docutils.core import publish_string\n\n\nclass SetupTestCase(unittest.TestCase):\n\n def test_long_description(self):\n \"\"\"Ensure long description can be generated\"\"\"\n with open('README.rst') as f:\n long_description = f.read()\n\n overrides = {\n # raises exception at warning level (2)\n 'halt_level': 2,\n 'raw_enabled': False,\n }\n html = publish_string(long_description, writer_name='html',\n settings_overrides=overrides)\n self.assertTrue(html)\n" }, { "alpha_fraction": 0.652363121509552, "alphanum_fraction": 0.6612411737442017, "avg_line_length": 26.420047760009766, "blob_id": "a5c661996721fc9c201c2768f3a47a892dcfb9a0", "content_id": "24e553e73bc7a9fa7df3e66b51800a2f8ae03e88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11489, "license_type": "permissive", "max_line_length": 79, "num_lines": 419, "path": "/tests/test_bpy_handlers_base.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom bpy.handlers.base import BaseHandler\n\n\nclass Handler(BaseHandler):\n\n def _generate(self, source=None):\n\n return source\n\n\nclass BaseHandlerTestCase(unittest.TestCase):\n\n def setUp(self):\n\n self.handler = Handler(None)\n\n def tearDown(self):\n\n self.handler = None\n\n def test_header_no_labels(self):\n\n handler = self.handler\n handler.source = '''!b\n\npost content'''\n header, markup = handler.split_header_markup()\n self.assertEqual(header, {})\n self.assertEqual(markup, 'post content')\n\n def test_header_labels_none(self):\n\n handler = self.handler\n handler.source = '''!b\nlabels:\n\npost content'''\n header, markup = handler.split_header_markup()\n self.assertEqual(header, {'labels': []})\n self.assertEqual(markup, 'post content')\n\n def test_header_labels_single(self):\n\n handler = self.handler\n handler.source = '''!b\nlabels: foobar\n\npost content'''\n header, markup = handler.split_header_markup()\n self.assertEqual(header, {'labels': ['foobar']})\n self.assertEqual(markup, 'post content')\n\n def test_header_labels_two(self):\n\n handler = self.handler\n handler.source = '''!b\nlabels: foo, bar\n\npost content'''\n header, markup = handler.split_header_markup()\n self.assertEqual(header, {'labels': ['foo', 'bar']})\n self.assertEqual(markup, 'post content')\n\n def test_header_labels_with_empty_label(self):\n\n handler = self.handler\n handler.source = '''!b\nlabels: foo, , bar\n\npost content'''\n header, markup = handler.split_header_markup()\n self.assertEqual(header, {'labels': ['foo', 'bar']})\n self.assertEqual(markup, 'post content')\n\n # =====\n\n def test_merge_header(self):\n\n handler = self.handler\n header = {'id': '123'}\n\n handler.header = header.copy()\n handler.merge_header(header.copy())\n self.assertEqual(handler.header, header)\n\n header['id'] = '456'\n header['blah'] = 'lol'\n handler.merge_header(header.copy())\n del header['blah']\n self.assertEqual(handler.header, header)\n\n header['id'] = '789'\n uheader = {'id': '789'}\n handler.merge_header(uheader.copy())\n self.assertEqual(handler.header, header)\n self.assertIsInstance(handler.header['id'], type(''))\n\n header['id'] = '123'\n uheader = {'id': '123'}\n handler.merge_header(uheader.copy())\n self.assertEqual(handler.header, header)\n self.assertIsInstance(handler.header['id'], type(''))\n self.assertEqual(list(handler.header.keys()), ['id'])\n self.assertIsInstance(list(handler.header.keys())[0], type(''))\n\n handler.header = {}\n handler.merge_header(uheader.copy())\n self.assertEqual(handler.header, header)\n self.assertIsInstance(handler.header['id'], type(''))\n self.assertEqual(list(handler.header.keys()), ['id'])\n self.assertIsInstance(list(handler.header.keys())[0], type(''))\n\n # =====\n\n def test_id_affix(self):\n\n handler = self.handler\n handler.title = 'test'\n\n def test_header_override():\n\n handler.header['id_affix'] = None\n self.assertEqual(handler.id_affix, None)\n\n handler.header['id_affix'] = ''\n self.assertEqual(handler.id_affix, '098f')\n\n handler.header['id_affix'] = 'prefix'\n self.assertEqual(handler.id_affix, 'prefix')\n\n # -----\n\n self.assertEqual(handler.id_affix, None)\n\n # -----\n\n handler.options['id_affix'] = None\n self.assertEqual(handler.id_affix, None)\n\n test_header_override()\n\n # -----\n\n del handler.header['id_affix']\n\n handler.options['id_affix'] = ''\n self.assertEqual(handler.id_affix, '098f')\n\n test_header_override()\n\n # -----\n\n del handler.header['id_affix']\n\n handler.options['id_affix'] = 'prefix'\n self.assertEqual(handler.id_affix, 'prefix')\n\n test_header_override()\n\n # =====\n\n test_markup_affixes_EXPECT1 = 'prefix-content-suffix'\n test_markup_affixes_EXPECT2 = 'foobar'\n test_markup_affixes_EXPECT3 = 'title'\n\n def test_markup_affixes(self):\n\n handler = self.handler\n handler.title = 'title'\n handler.markup = 'content'\n handler.options['markup_prefix'] = 'prefix-'\n handler.options['markup_suffix'] = '-suffix'\n\n self.assertEqual(\n handler.generate(),\n self.test_markup_affixes_EXPECT1)\n\n self.assertEqual(\n handler.generate('foobar'),\n self.test_markup_affixes_EXPECT2)\n\n self.assertEqual(\n handler.generate_title(),\n self.test_markup_affixes_EXPECT3)\n\n # =====\n\n def test_split_header_markup(self):\n\n handler = self.handler\n handler.source = '''xoxo !b oxox\nabc= foo\n def:bar\n\npost content'''\n header, markup = handler.split_header_markup()\n expect = {'abc': 'foo', 'def': 'bar'}\n self.assertEqual(header, expect)\n self.assertEqual(markup, 'post content')\n\n source = '%s!b\\n' % handler.PREFIX_HEAD\n source += handler.HEADER_FMT % ('abc', 'foo') + '\\n'\n source += handler.HEADER_FMT % ('def', 'bar') + '\\n'\n if handler.PREFIX_END:\n source += handler.PREFIX_END + '\\n'\n source += '\\npost content'\n handler.source = source\n header, markup = handler.split_header_markup()\n self.assertEqual(header, expect)\n self.assertEqual(markup, 'post content')\n\n # =====\n\n def test_generate_header(self):\n\n handler = self.handler\n handler.set_header('id', '123')\n expect = '%s!b\\n%s\\n' % (handler.PREFIX_HEAD,\n handler.HEADER_FMT % ('id', '123'))\n if handler.PREFIX_END:\n expect += handler.PREFIX_END + '\\n'\n\n self.assertEqual(handler.generate_header(), expect)\n\n # =====\n\n def test_generate_title_oneline(self):\n\n handler = self.handler\n title = 'foobar'\n expect = 'foobar'\n\n result = handler.generate_title(title)\n self.assertEqual(result, expect)\n\n def test_generate_title_multiline(self):\n\n handler = self.handler\n title = 'foo\\nbar\\n\\nblah'\n expect = 'foo bar blah'\n\n result = handler.generate_title(title)\n self.assertEqual(result, expect)\n\n test_generate_title_common_markup_EXPECT = 'foo *bar*'\n\n def test_generate_title_common_markup(self):\n\n handler = self.handler\n title = 'foo *bar*'\n\n result = handler.generate_title(title)\n expect = self.test_generate_title_common_markup_EXPECT\n self.assertEqual(result, expect)\n\n # =====\n\n test_generate_str_MARKUP = '\\xc3\\xa1'\n test_generate_str_EXPECT = '\\xc3\\xa1'\n\n def test_generate__str(self):\n\n handler = self.handler\n\n html = handler._generate(self.test_generate_str_MARKUP)\n self.assertEqual(html, self.test_generate_str_EXPECT)\n self.assertIsInstance(html, type(''))\n\n def test_generate_str(self):\n\n handler = self.handler\n handler.markup = self.test_generate_str_MARKUP\n\n html = handler.generate()\n self.assertEqual(html, self.test_generate_str_EXPECT)\n self.assertIsInstance(html, type(''))\n\n # =====\n\n test_smartypants_MARKUP = 'foo \"bar\"'\n test_smartypants_EXPECT = 'foo &#8220;bar&#8221;'\n\n def test_smartypants(self):\n\n handler = self.handler\n handler.options['smartypants'] = True\n handler.markup = self.test_smartypants_MARKUP\n\n html = handler.generate()\n self.assertEqual(html, self.test_smartypants_EXPECT)\n self.assertIsInstance(html, type(''))\n\n # =====\n\n def test_generate_post(self):\n\n handler = self.handler\n handler.source = '''!b\nabc=foo\ntitle=the title\nid=123\nblog: 456\n\npost content'''\n header, markup = handler.split_header_markup()\n handler.header = header\n post = handler.generate_post()\n\n self.assertEqual(post, {\n 'title': 'the title',\n 'draft': False,\n 'id': '123',\n 'blog': {'id': '456'}\n })\n\n # =====\n\n def test_update_source(self):\n\n handler = self.handler\n source = '%s!b\\n%s\\n' % (handler.PREFIX_HEAD,\n handler.HEADER_FMT % ('id', '123'))\n if handler.PREFIX_END:\n source += handler.PREFIX_END + '\\n'\n source += '\\npost content'\n handler.source = source\n\n header, markup = handler.split_header_markup()\n handler.header = header\n handler.markup = markup\n\n handler.update_source()\n self.assertEqual(handler.source, source)\n\n handler.options['markup_prefix'] = 'PREFIX'\n\n handler.update_source()\n self.assertEqual(handler.source, source)\n\n # =====\n\n test_embed_images_src = 'tests/test.png'\n test_embed_images_data_URI = (\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAI'\n 'AAACQd1PeAAAADElEQVQI12Oorq4GAALmAXLRBAkWAAAAAElFTkSuQmCC'\n )\n\n test_embed_images_SOURCE1 = '<img src=\"http://example.com/example.png\"/>'\n test_embed_images_EXPECT1 = test_embed_images_SOURCE1\n\n test_embed_images_SOURCE2 = '<img src=\"tests/test.png\"/>'\n test_embed_images_EXPECT2 = '<img src=\"%s\"/>' % test_embed_images_data_URI\n\n test_embed_images_SOURCE3 = '<img alt=\"foo\" src=\"tests/test.png\"/>'\n test_embed_images_EXPECT3 = '<img alt=\"foo\" src=\"%s\"/>' % (\n test_embed_images_data_URI)\n\n test_embed_images_SOURCE4 = '<img src=\"tests/test.png\" title=\"bar\"/>'\n test_embed_images_EXPECT4 = '<img src=\"%s\" title=\"bar\"/>' % (\n test_embed_images_data_URI)\n\n test_embed_images_SOURCE5 = '<img src=\"%s\"/>' % test_embed_images_data_URI\n test_embed_images_EXPECT5 = test_embed_images_SOURCE5\n\n def test_embed_images(self):\n\n handler = self.handler\n\n result = handler.embed_images(self.test_embed_images_SOURCE1)\n self.assertEqual(result, self.test_embed_images_EXPECT1)\n\n result = handler.embed_images(self.test_embed_images_SOURCE2)\n self.assertEqual(result, self.test_embed_images_EXPECT2)\n\n result = handler.embed_images(self.test_embed_images_SOURCE3)\n self.assertEqual(result, self.test_embed_images_EXPECT3)\n\n result = handler.embed_images(self.test_embed_images_SOURCE4)\n self.assertEqual(result, self.test_embed_images_EXPECT4)\n\n result = handler.embed_images(self.test_embed_images_SOURCE5)\n self.assertEqual(result, self.test_embed_images_EXPECT5)\n\n test_embed_images_generate_SOURCE = '<img src=\"tests/test.png\"/>'\n test_embed_images_generate_EXPECT = '<img src=\"%s\"/>' % (\n test_embed_images_data_URI)\n\n def test_embed_images_generate(self):\n\n handler = self.handler\n handler.options['embed_images'] = True\n\n handler.markup = self.test_embed_images_generate_SOURCE\n html = handler.generate()\n self.assertEqual(html, self.test_embed_images_generate_EXPECT)\n" }, { "alpha_fraction": 0.6172046661376953, "alphanum_fraction": 0.619401752948761, "avg_line_length": 26.393518447875977, "blob_id": "a8552ac648b21d4afe803a7e78148d3bcd7a0fa4", "content_id": "0355cbfc93d484e18893263dd163657230f97163", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5917, "license_type": "permissive", "max_line_length": 79, "num_lines": 216, "path": "/bpy/handlers/__init__.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nMarkup handlers' IDs and extensions:\n\n==================== ========================================================\nID extensions\n==================== ========================================================\n``AsciiDoc`` ``.asciidoc``\n``HTML`` ``.html``, ``.htm``, ``.raw``\n``Markdown`` ``.md``, ``.mkd``, ``.mkdn``, ``.mkdown``, ``.markdown``\n``reStructuredText`` ``.rst``\n``Text`` ``.txt``, ``.text``\n==================== ========================================================\n\n\nOptions\n=======\n\nThe general options are supported by all handlers, defined in\n:class:`bpy.handlers.base.BaseHandler`, but they have to be specified per\nhandler basis, the following sample code shows the options and their default\nvalue:\n\n.. code:: python\n\n handlers = {\n '<MARKUP HANDLER ID>': {\n 'options': {\n # prefix string to HTML ID to avoid conflict\n 'id_affix': None,\n\n # string to prepend to actual markup\n 'markup_prefix': '',\n\n # string to append to actual markup\n 'markup_suffix': '',\n\n # use smartypant to process the output of markup processor\n 'smartypants': False,\n\n # support image embedding via data URI scheme\n 'embed_images': False,\n },\n },\n }\n\n.. _id_affix:\n\n``id_affix``\n------------\n\n``id_affix`` is used to avoid conflict across posts' HTML element ID. It may be\na prefix or suffix, depending on handler's implementation and markup library's\nsupport. It has three types of value:\n\n1. ``None``: no affix to ID.\n2. non-empty string: the string is the affix.\n3. empty string: the affix is generated automatically.\n\nCurrently supported markup handler:\n\n* :mod:`bpy.handlers.rst`\n\n``markup_prefix`` and ``markup_suffix``\n---------------------------------------\n\n``markup_prefix`` and ``markup_suffix`` can be useful for adding header and\nfooter content for posts. Another useful case in reStructuredText is you can\nuse it for setting up some directives, for example ``.. sectnum::``, so you can\nensure all posts have prefixing section number if in use conjunction with\n``.. contents::``.\n\n``smartypants``\n---------------\n\nIf ``smartypants`` is enabled, then all generated HTML from markup processor\nwill be processed by smartypants_ library.\n\n.. _smartypants: https://pypi.python.org/pypi/smartypants\n\n.. _embed_images:\n\n``embed_images``\n----------------\n\n.. note::\n\n Only :mod:`bpy.handlers.text` does not support this option.\n\nWhen this option is enabled, it looks for the ``src`` attribute of ``img`` tag\nin rendered HTML, see if there is a local files, excluding ``http``, ``https``,\nand ``data`` schemes, if found, it reads the file and embeds with Base64\nencoded content.\n\nFor example, in reStructuredText:\n\n.. code:: rst\n\n .. image:: /path/to/test.png\n\nInstead of\n\n.. code:: html\n\n <img alt=\"/path/to/test.png\" src=\"/path/to/test.png\" />\n\nIt could be replaced with, if ``/path/to/test.png`` exists:\n\n.. code:: html\n\n <img alt=\"/path/to/test.png\" src=\"data:image/png;base64,...\" />\n\nIf the image file can't be found, a message will be printed out, the rendered\nimage tag will be kept untouched.\n\n.. _custom-handler:\n\nWriting a custom handler\n========================\n\nA sample handler ``sample_handler.py``:\n\n.. code:: python\n\n from bpy.handlers import base\n\n class Handler(base.BaseHandler):\n PREFIX_HEAD = ''\n PREFIX_END = ''\n HEADER_FMT = '%s: %s'\n\n def _generate(self, markup=None):\n if markup is None:\n markup = self.markup\n\n html = do_process(markup)\n return html\n\nAnd corresponding setting in ``brc.py``:\n\n.. code:: python\n\n import re\n\n handlers = {\n 'SampleHandler': {\n 'match': re.compile(r'.*\\.ext$'),\n 'module': 'sample_handler',\n },\n }\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport traceback\n\nhandlers = {\n 'AsciiDoc': {\n 'match': re.compile(r'.*\\.asciidoc$'),\n 'module': 'bpy.handlers.asciidoc',\n },\n 'HTML': {\n 'match': re.compile(r'.*\\.(html?|raw)$'),\n 'module': 'bpy.handlers.html',\n },\n 'Markdown': {\n 'match': re.compile(r'.*\\.(markdown|md(own)?|mkdn?)$'),\n 'module': 'bpy.handlers.mkd',\n },\n 'reStructuredText': {\n 'match': re.compile(r'.*\\.rst$'),\n 'module': 'bpy.handlers.rst',\n },\n 'Text': {\n 'match': re.compile(r'.*\\.te?xt$'),\n 'module': 'bpy.handlers.text',\n },\n}\n\n\ndef find_handler(filename):\n\n sys.path.insert(0, os.getcwd())\n module = None\n for name, hdlr in handlers.items():\n if hdlr['match'].match(filename):\n try:\n module = __import__(hdlr['module'], fromlist=['Handler'])\n break\n except Exception:\n print('Cannot load module %s of handler %s' % (hdlr['module'], name))\n traceback.print_exc()\n sys.path.pop(0)\n if module:\n return module.Handler(filename, hdlr.get('options', {}))\n return None\n" }, { "alpha_fraction": 0.5965356826782227, "alphanum_fraction": 0.6019433736801147, "avg_line_length": 27.656173706054688, "blob_id": "6237aeb16a61740c6ab60135b2247f47889c869b", "content_id": "b5c8e372aa5e40d55d922ea880c35d7a76f5667d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11835, "license_type": "permissive", "max_line_length": 79, "num_lines": 413, "path": "/bpy/handlers/base.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013-2015 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\nfrom __future__ import print_function, unicode_literals\n\nimport codecs\nimport logging\nimport re\nimport warnings\nfrom abc import ABCMeta, abstractmethod\nfrom base64 import b64encode\nfrom hashlib import md5\nfrom os.path import basename, exists, splitext\n\nHAS_SMARTYPANTS = False\ntry:\n import smartypants\n HAS_SMARTYPANTS = True\nexcept ImportError:\n pass\n\n\nclass BaseHandler():\n \"\"\"The base clase of markup handler\"\"\"\n __metaclass__ = ABCMeta\n\n # default handler options\n OPTIONS = {\n 'markup_prefix': '',\n 'markup_suffix': '',\n 'smartypants': False,\n 'id_affix': None,\n }\n\n MERGE_HEADERS = ('service', 'kind', 'blog', 'id', 'url', 'draft')\n HEADER_FMT = '%s: %s'\n PREFIX_HEAD = ''\n PREFIX_END = ''\n\n RE_SPLIT = re.compile(r'^(?:([^\\n]*?!b.*?)\\n\\n)?(.*)',\n re.DOTALL | re.MULTILINE)\n RE_HEADER = re.compile(r'.*?([a-zA-Z0-9_-]+)\\s*[=:]\\s*(.*)\\s*')\n\n SUPPORT_EMBED_IMAGES = True\n RE_IMG = re.compile(\n r'''\n (?P<prefix><img.*?)\n src=\"(?!data:image/|https?://)(?P<src>[^\"]*)\"\n (?P<suffix>.*?>)\n ''',\n re.VERBOSE\n )\n\n def __init__(self, filename, options=None):\n\n self.filename = filename\n self.title = ''\n self.options = self.OPTIONS.copy()\n self.options.update(options or {})\n if filename:\n with codecs.open(filename, 'r', 'utf8') as f:\n self.source = f.read()\n header, markup = self.split_header_markup()\n self.title = splitext(basename(filename))[0]\n else:\n header = {}\n markup = ''\n self.header = header\n self.markup = markup\n self.modified = False\n\n def set_header(self, k, v):\n \"\"\"Set header\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> handler = Handler(None)\n >>> print(handler.header)\n {}\n >>> handler.modified\n False\n >>> handler.set_header('foo', 'bar')\n >>> print(handler.header['foo'])\n bar\n >>> handler.modified\n True\n \"\"\"\n if k in self.header and self.header[k] == v:\n return\n\n self.header[k] = v\n self.modified = True\n\n def merge_header(self, header):\n \"\"\"Merge header\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> handler = Handler(None)\n >>> handler.merge_header({'id': 12345, 'bogus': 'blah'})\n >>> print(handler.header['id'])\n 12345\n >>> handler.modified\n True\n \"\"\"\n for k, v in header.items():\n if k not in self.MERGE_HEADERS:\n continue\n if k == 'blog':\n v = v['id']\n elif k == 'kind':\n v = v.replace('blogger#', '')\n self.set_header(k, v)\n\n @property\n def markup(self):\n \"\"\"Return markup with markup_prefix and markup_suffix\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> options = {\n ... 'markup_prefix': 'the prefix\\\\n',\n ... 'markup_suffix': '\\\\nthe suffix',\n ... }\n >>> handler = Handler(None, options)\n >>> handler.markup = 'content'\n >>> print(handler.markup)\n the prefix\n content\n the suffix\n \"\"\"\n return '%s%s%s' % (\n self.options['markup_prefix'],\n self._markup,\n self.options['markup_suffix'],\n )\n\n @markup.setter\n def markup(self, markup):\n \"\"\"Set the markup\"\"\"\n self._markup = markup\n\n @property\n def id_affix(self):\n \"\"\"Return id_affix\n\n The initial value is from self.options, and can be overriden by\n self.header.\n\n Returns\n\n * None if it's None.\n * value if value is not ''\n * first 4 digits of md5 of value if value is '', and assign back to\n self.options. _generate method of Handler should write back to\n self.header.\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> options = {\n ... 'id_affix': None,\n ... }\n >>> handler = Handler(None, options)\n >>> print(repr(handler.id_affix))\n None\n >>> handler.options['id_affix'] = 'foobar'\n >>> print(handler.id_affix)\n foobar\n >>> # auto generate an id affix from title\n >>> handler.options['id_affix'] = ''\n >>> handler.title = 'abc'\n >>> print(handler.id_affix)\n 9001\n >>> handler.header['id_affix'] = 'override-affix'\n >>> print(handler.id_affix)\n override-affix\n \"\"\"\n id_affix = self.options['id_affix']\n # override?\n if 'id_affix' in self.header:\n id_affix = self.header['id_affix']\n if self.header['id_affix'] and id_affix != 'None':\n return self.header['id_affix']\n\n # second case is from header of post, has to use string 'None'\n if id_affix is None or id_affix == 'None':\n return None\n\n if id_affix:\n return id_affix\n\n m = md5()\n # if self.title is Unicode-type string, then encode it,\n # otherwise it's byte-type, then just update with it.\n # The __future__.unicode_literals ensures '' is unicode-type.\n if isinstance(self.title, type('')):\n m.update(self.title.encode('utf8'))\n else:\n m.update(self.title)\n return m.hexdigest()[:4]\n\n @abstractmethod\n def _generate(self, markup=None):\n \"\"\"Generate HTML of markup source\"\"\"\n raise NotImplementedError\n\n def generate(self, markup=None):\n \"\"\"Generate HTML\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, markup=None): return markup\n >>> handler = Handler(None)\n >>> print(handler.generate('foo \"bar\"'))\n foo \"bar\"\n >>> handler.options['smartypants'] = True\n >>> print(handler.generate('foo \"bar\"'))\n foo &#8220;bar&#8221;\n \"\"\"\n\n if markup is None:\n markup = self.markup\n\n html = self._generate(markup)\n\n if self.options.get('smartypants', False):\n if not HAS_SMARTYPANTS:\n warnings.warn(\"smartypants option is set, \"\n \"but the library isn't installed.\", RuntimeWarning)\n return html\n Attr = smartypants.Attr\n html = smartypants.smartypants(html, Attr.set1 | Attr.w)\n\n if self.SUPPORT_EMBED_IMAGES and self.options.get('embed_images', False):\n html = self.embed_images(html)\n\n return html\n\n def generate_header(self, header=None):\n \"\"\"Generate header in text for writing back to the file\n\n >>> class Handler(BaseHandler):\n ... PREFIX_HEAD = 'foo '\n ... PREFIX_END = 'bar'\n ... HEADER_FMT = '--- %s: %s'\n ... def _generate(self, source=None): pass\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n foo !b\n --- title: foobar\n bar\n <BLANKLINE>\n >>> print(handler.generate_header({'labels': ['foo', 'bar']}))\n foo !b\n --- labels: foo, bar\n bar\n <BLANKLINE>\n \"\"\"\n if header is None:\n header = self.header\n\n lines = [self.PREFIX_HEAD + '!b']\n for k, v in header.items():\n if k in ('labels', 'categories'):\n v = ', '.join(v)\n elif k == 'draft':\n v = repr(v)\n lines.append(self.HEADER_FMT % (k, v))\n lines.append(self.PREFIX_END)\n return '\\n'.join([_f for _f in lines if _f]) + '\\n'\n\n def generate_title(self, title=None):\n \"\"\"Generate title for posting\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> handler = Handler(None)\n >>> print(handler.generate_title('foo \"bar\"'))\n foo \"bar\"\n >>> print(handler.generate_title('foo\\\\nbar\\\\n\\\\n'))\n foo bar\n >>> handler.options['smartypants'] = True\n >>> print(handler.generate_title('foo \"bar\"'))\n foo &#8220;bar&#8221;\n \"\"\"\n if title is None:\n title = self.header.get('title', self.title)\n\n title = self.generate(title)\n title = title.replace('<p>', '').replace('</p>', '')\n # no trailing newlines\n title = re.sub(r'\\n+', ' ', title).rstrip()\n return title\n\n def generate_post(self):\n \"\"\"Generate dict for merging to post object of API\"\"\"\n post = {'title': self.generate_title(), 'draft': False}\n for k in ('blog', 'id', 'labels', 'categories', 'draft'):\n if k not in self.header:\n continue\n if k == 'blog':\n post[k] = {'id': self.header[k]}\n else:\n post[k] = self.header[k]\n return post\n\n def split_header_markup(self, source=None):\n \"\"\"Split source into header and markup parts\n\n It also parses header into a dict.\"\"\"\n if source is None:\n source = self.source\n\n header, markup = self.RE_SPLIT.match(source).groups()\n if not header:\n logging.warning('found no header')\n if not markup:\n logging.warning('markup is empty')\n logging.debug('markup length = %d' % len(markup))\n\n _header = {}\n if header:\n for item in header.split('\\n'):\n m = self.RE_HEADER.match(item)\n if not m:\n continue\n k, v = list(map(type('').strip, m.groups()))\n if k in ('labels', 'categories'):\n v = [_f for _f in [label.strip() for label in v.split(',')] if _f]\n elif k == 'draft':\n v = v.lower() in ('true', 'yes', '1')\n _header[k] = v\n header = _header\n\n logging.debug('header = %r' % header)\n\n return header, markup\n\n def update_source(self, header=None, markup=None, only_returned=False):\n\n if header is None:\n header = self.header\n if markup is None:\n markup = self._markup\n\n source = self.generate_header(header) + '\\n' + markup\n if not only_returned:\n self.source = source\n return source\n\n def write(self, forced=False):\n \"\"\"Write source back to file\"\"\"\n if not self.modified:\n if not forced:\n return\n else:\n self.update_source()\n\n with codecs.open(self.filename, 'w', 'utf8') as f:\n f.write(self.source)\n self.modified = False\n\n def embed_images(self, html):\n \"\"\"Embed images on local filesystem as data URI\n\n >>> class Handler(BaseHandler):\n ... def _generate(self, source=None): return source\n >>> handler = Handler(None)\n >>> html = '<img src=\"http://example.com/example.png\"/>'\n >>> print(handler.embed_images(html))\n <img src=\"http://example.com/example.png\"/>\n >>> html = '<img src=\"tests/test.png\"/>'\n >>> print(handler.embed_images(html)) #doctest: +ELLIPSIS\n <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...QmCC\"/>\n \"\"\"\n if not self.SUPPORT_EMBED_IMAGES:\n raise RuntimeError('%r does not support embed_images' % type(self))\n\n return self.RE_IMG.sub(self._embed_image, html)\n\n @staticmethod\n def _embed_image(match):\n\n src = match.group('src')\n if not exists(src):\n print('%s is not found.' % src)\n return match.group(0)\n\n with open(src, 'rb') as f:\n data = b64encode(f.read()).decode('ascii')\n\n return '%ssrc=\"%s\"%s' % (\n match.group('prefix'),\n 'data:image/%s;base64,%s' % (splitext(src)[1].lstrip('.'), data),\n match.group('suffix'),\n )\n" }, { "alpha_fraction": 0.652554988861084, "alphanum_fraction": 0.6573083996772766, "avg_line_length": 27.525423049926758, "blob_id": "50036e1eb86e25d45e48047633bf5b1408e36de3", "content_id": "032dde74c242c9d897ac38f752c11400aeb4d5b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6732, "license_type": "permissive", "max_line_length": 79, "num_lines": 236, "path": "/bpy/services/blogger.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013-2016 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\n\nBlogger service recognizes the following options in :ref:`brc.py`:\n\n.. _blogger-brc:\n.. code:: python\n\n service = 'blogger'\n service_options = {\n client_id: '<your client ID>',\n client_secret: '<your client secret>',\n 'blog': <blog id>,\n }\n\nYou can use ``blogs`` command to quickly get the blog ID.\n\n\n.. _Authorization:\n\nAuthorization\n=============\n\nYou need to authorize *b.py* to access your Blogger account with your OAuth\n`client ID`_. Simply using ``blogs`` command (see *Commands* section) to start\nthe authorization process:\n\n.. code:: sh\n\n b.py blogs\n\nOnce you follow the prompted steps, there should be a b.dat_ created under the\ncurrent working directory, you should keep it safe.\n\n.. _Client ID:\n\nClient ID\n=========\n\nYou will need to obtain a OAuth Client ID in order to use *b.py*.\n\n1. Go to `Google Developers Console`_.\n2. Create a new project.\n3. Enable *Blogger API*.\n4. Create a *OAuth client ID* credential with *Other* application type.\n5. Download the credential JSON for *Client Secret*.\n6. Add *Client ID* and *Client Secert* to your :ref:`brc.py` as shown here__.\n\n.. _Google Developers Console: https://console.developers.google.com/\n__ blogger-brc_\n\n.. _b.dat:\n\n``b.dat``\n=========\n\n``b.dat`` is a credential file for Blogger service, it's read by *b.py* from\nthe current directory.\n\nTo create the file, please follow Authorization_.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport httplib2\n\nfrom bpy.services.base import Service as BaseService\n\nif sys.version_info.major == 2:\n from apiclient.discovery import build\n from oauth2client.client import OAuth2WebServerFlow\n from oauth2client.file import Storage as BaseStorage\n from oauth2client.tools import run_flow, argparser\n\n API_STORAGE = 'b.dat'\n\n class Storage(BaseStorage):\n \"\"\"Inherit the API Storage to suppress CredentialsFileSymbolicLinkError\n \"\"\"\n\n def __init__(self, filename):\n\n super(Storage, self).__init__(filename)\n self._filename_link_warned = False\n\n def _validate_file(self):\n\n if os.path.islink(self._filename) and not self._filename_link_warned:\n print('File: %s is a symbolic link.' % self._filename)\n self._filename_link_warned = True\n\n\nclass Service(BaseService):\n\n service_name = 'blogger'\n\n def __init__(self, *args, **kwargs):\n\n super(Service, self).__init__(*args, **kwargs)\n\n self.http = None\n self.service = None\n\n if 'client_id' not in self.options or 'client_secret' not in self.options:\n raise RuntimeError(\n 'You need to supply client ID and secret, see '\n 'http://pythonhosted.org/b.py/apidoc/bpy.services.html#client-id'\n )\n\n self.client_id = self.options['client_id']\n self.client_secret = self.options['client_secret']\n\n def auth(self):\n\n if sys.version_info.major != 2:\n msg = ('This command requires google-api-python-client, '\n 'which only support Python 2')\n raise RuntimeError(msg)\n\n if self.http and self.service:\n return\n\n FLOW = OAuth2WebServerFlow(\n self.client_id,\n self.client_secret,\n 'https://www.googleapis.com/auth/blogger',\n auth_uri='https://accounts.google.com/o/oauth2/auth',\n token_uri='https://accounts.google.com/o/oauth2/token',\n )\n\n storage = Storage(API_STORAGE)\n credentials = storage.get()\n if credentials is None or credentials.invalid:\n credentials = run_flow(FLOW, storage, argparser.parse_args([]))\n\n http = httplib2.Http()\n self.http = credentials.authorize(http)\n self.service = build(\"blogger\", \"v3\", http=self.http)\n\n def list_blogs(self):\n\n self.auth()\n blogs = self.service.blogs()\n req = blogs.listByUser(userId='self')\n resp = req.execute(http=self.http)\n print('%-20s: %s' % ('Blog ID', 'Blog name'))\n for blog in resp['items']:\n print('%-20s: %s' % (blog['id'], blog['name']))\n\n def post(self):\n\n handler, post = self.make_handler_post()\n\n if 'blog' not in post:\n print('You need to specify which blog to post on '\n 'in either brc.py or header of %s.' % handler.filename)\n sys.exit(1)\n\n self.auth()\n\n kind = post['kind'].replace('blogger#', '')\n title = post['title']\n\n if kind == 'post':\n posts = self.service.posts()\n elif kind == 'page':\n posts = self.service.pages()\n else:\n raise ValueError('Unsupported kind: %s' % kind)\n\n data = {\n 'blogId': post['blog']['id'],\n 'body': post,\n }\n if 'id' in post:\n data['%sId' % kind] = post['id']\n action = 'revert' if post['draft'] else 'publish'\n data[action] = True\n print('Updating a %s: %s' % (kind, title))\n req = posts.update(**data)\n else:\n data['isDraft'] = post['draft']\n print('Posting a new %s: %s' % (kind, title))\n req = posts.insert(**data)\n\n resp = req.execute(http=self.http)\n\n resp['draft'] = resp['status'] == 'DRAFT'\n\n handler.merge_header(resp)\n handler.write()\n\n def search(self, q):\n\n if self.options['blog'] is None:\n raise ValueError('no blog ID to search')\n\n self.auth()\n\n fields = 'items(labels,published,title,url)'\n posts = self.service.posts()\n req = posts.search(blogId=self.options['blog'], q=q, fields=fields)\n resp = req.execute(http=self.http)\n items = resp.get('items', [])\n print('Found %d posts on Blog %s' % (len(items), self.options['blog']))\n print()\n for post in items:\n print(post['title'])\n labels = post.get('labels', [])\n if labels:\n print('Labels:', ', '.join(labels))\n print('Published:', post['published'])\n print(post['url'])\n print()\n" }, { "alpha_fraction": 0.6748091578483582, "alphanum_fraction": 0.677251935005188, "avg_line_length": 27.982301712036133, "blob_id": "a86e1465db03763a668dc207e82e15157ae59f17", "content_id": "571a5ef28e888cf0dc806ad43e8d7504306f3a52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3275, "license_type": "permissive", "max_line_length": 79, "num_lines": 113, "path": "/bpy/services/base.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nBase recognizes no options, it's only used for ``generate`` or ``checklink``\ncommands.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport codecs\nimport os\nimport sys\nfrom io import StringIO\nfrom os import path\nfrom tempfile import gettempdir\n\nfrom bpy.handlers import find_handler\n\nHAS_LNKCKR = False\ntry:\n from lnkckr.checkers.html import Checker\n HAS_LNKCKR = True\nexcept ImportError:\n pass\n\n\nTEMPLATE_PATH = path.join(os.getcwd(), 'tmpl.html')\n\n\nclass Service(object):\n \"\"\"The base clase of markup handler\"\"\"\n\n service_name = 'base'\n\n def __init__(self, options, filename=None):\n\n self.options = options\n self.filename = filename\n\n def post(self):\n \"\"\"Publish the post to the service\"\"\"\n raise NotImplementedError\n\n def make_handler_post(self):\n\n handler = find_handler(self.filename)\n if not handler:\n print('No handler for the file!')\n sys.exit(1)\n\n hdr = handler.header\n\n post = {\n 'service': self.service_name,\n # default resource kind is blogger#post\n 'kind': 'blogger#%s' % hdr.get('kind', 'post'),\n 'content': handler.generate(),\n }\n if isinstance(self.options['blog'], int):\n post['blog'] = {'id': self.options['blog']}\n post.update(handler.generate_post())\n\n return handler, post\n\n def generate(self):\n\n handler, post = self.make_handler_post()\n with codecs.open(path.join(gettempdir(), 'draft.html'), 'w',\n encoding='utf8') as f:\n f.write(post['content'])\n\n if path.exists(TEMPLATE_PATH):\n with codecs.open(TEMPLATE_PATH, encoding='utf8') as f:\n html = f.read()\n html = html.replace('%%Title%%', post['title'])\n html = html.replace('%%Content%%', post['content'])\n with codecs.open(path.join(gettempdir(), 'preview.html'), 'w',\n encoding='utf8') as f:\n f.write(html)\n\n def checklink(self):\n\n if not HAS_LNKCKR:\n print('You do not have lnkckr library')\n return\n handler, post = self.make_handler_post()\n c = Checker()\n c.process(StringIO(post['content']))\n c.check()\n print()\n c.print_all()\n\n def search(self, q):\n \"\"\"Search posts\"\"\"\n raise NotImplementedError\n" }, { "alpha_fraction": 0.6528906226158142, "alphanum_fraction": 0.6607847809791565, "avg_line_length": 26.259492874145508, "blob_id": "62668bb04c34d5fe9c8ef95a9e8b9ea8dbff7c98", "content_id": "c4b6eb0e0a572f250fbef6294b1a5bbad8a3f05a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4307, "license_type": "permissive", "max_line_length": 79, "num_lines": 158, "path": "/tests/test_bpy_handlers_rst.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom docutils import nodes\nfrom docutils.parsers.rst import Directive\n\nimport test_bpy_handlers_base as test_base\nfrom bpy.handlers.rst import Handler, register_directive, register_role\n\n\nclass HandlerTestCase(test_base.BaseHandlerTestCase):\n\n def setUp(self):\n\n self.handler = Handler(None)\n\n # =====\n\n def test_options_register_directive_decorator(self):\n\n source = '.. dtestdir::'\n expect = '<p>TEST</p>'\n\n @register_directive('dtestdir')\n class dTestDir(Directive):\n\n def run(self):\n\n return [nodes.raw('', expect, format='html')]\n\n handler = Handler(None)\n\n self.assertEqual(handler.generate(source), expect)\n\n def test_options_register_role_decorator(self):\n\n source = 'abc :dtestrole:`123` def'\n expect = '<p>abc <em>TEST</em> def</p>'\n\n @register_role('dtestrole')\n def dTestRole(*args, **kwds):\n\n return [nodes.raw('', '<em>TEST</em>', format='html')], []\n\n handler = Handler(None)\n\n self.assertEqual(handler.generate(source), expect)\n\n def test_options_register_directives(self):\n\n source = '.. testdir::'\n expect = '<p>TEST</p>'\n\n class TestDir(Directive):\n\n def run(self):\n\n return [nodes.raw('', expect, format='html')]\n\n options = {'register_directives': {'testdir': TestDir}}\n handler = Handler(None, options)\n\n self.assertEqual(handler.generate(source), expect)\n\n def test_options_register_roles(self):\n\n source = 'abc :testrole:`123` def'\n expect = '<p>abc <em>TEST</em> def</p>'\n\n def TestRole(*args, **kwds):\n\n return [nodes.raw('', '<em>TEST</em>', format='html')], []\n\n options = {'register_roles': {'testrole': TestRole}}\n handler = Handler(None, options)\n\n self.assertEqual(handler.generate(source), expect)\n\n # =====\n\n def test_id_affix(self):\n\n handler = self.handler\n handler.title = 'test'\n source = ('Test Handler\\n'\n '------------')\n\n html_base = ('<div class=\"section\" id=\"%stest-handler\">\\n'\n '<h2>Test Handler</h2>\\n'\n '</div>')\n\n html = html_base % ''\n self.assertEqual(handler.generate(source), html)\n\n handler.header['id_affix'] = ''\n html = html_base % '098f-'\n self.assertEqual(handler.generate(source), html)\n self.assertEqual(handler.modified, True)\n self.assertEqual(handler.generate_header(), '''.. !b\n id_affix: 098f\n''')\n\n handler.header['id_affix'] = 'foobar-prefix'\n html = html_base % 'foobar-prefix-'\n self.assertEqual(handler.generate(source), html)\n\n # =====\n\n test_markup_affixes_EXPECT1 = '<p>prefix-content-suffix</p>'\n test_markup_affixes_EXPECT2 = '<p>foobar</p>'\n\n # =====\n\n test_generate_title_common_markup_EXPECT = 'foo <em>bar</em>'\n\n # =====\n\n test_generate_str_EXPECT = '<p>\\xc3\\xa1</p>'\n\n # =====\n\n test_smartypants_EXPECT = '<p>foo &#8220;bar&#8221;</p>'\n\n # =====\n\n @unittest.skip('tested in BaseHandler')\n def test_embed_images(self):\n\n pass\n\n test_embed_images_generate_SOURCE = '.. image:: tests/test.png'\n test_embed_images_generate_EXPECT = (\n '<img alt=\"tests/test.png\" src=\"%s\" />' % (\n test_base.BaseHandlerTestCase.test_embed_images_data_URI\n )\n )\n" }, { "alpha_fraction": 0.6714461445808411, "alphanum_fraction": 0.6759524941444397, "avg_line_length": 28.059524536132812, "blob_id": "2ba47e73153b7d380803440cc0c6e7c235ff63fe", "content_id": "2eda53d2fdbae7bccff8c707d826d398fdd15cf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2441, "license_type": "permissive", "max_line_length": 79, "num_lines": 84, "path": "/bpy/handlers/asciidoc.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nYou can specify embed_images_, for example:\n\n.. code:: python\n\n handlers = {\n 'AsciiDoc': {\n 'options': {\n 'embed_images': True,\n },\n },\n }\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nimport StringIO\n\nfrom bpy.api.asciidocapi import AsciiDocAPI\nfrom bpy.handlers import base\n\n\nclass Handler(base.BaseHandler):\n \"\"\"Handler for AsciiDoc markup language\n\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n // !b\n // title: foobar\n <BLANKLINE>\n \"\"\"\n\n PREFIX_HEAD = '// '\n PREFIX_END = ''\n HEADER_FMT = '// %s: %s'\n\n def _generate(self, markup=None):\n \"\"\"Generate HTML from AsciiDoc\n\n >>> handler = Handler(None)\n >>> print(handler._generate('a *b*'))\n <p>a <strong>b</strong></p>\n >>> print(handler._generate('a\\\\nb'))\n <p>a\n b</p>\n >>> print(handler._generate('a\\\\nb\\\\n\\\\nc'))\n <p>a\n b</p>\n <p>c</p>\n \"\"\"\n if markup is None:\n markup = self.markup\n markup = markup.encode('utf8')\n\n asciidoc = AsciiDocAPI()\n infile = StringIO.StringIO(markup)\n outfile = StringIO.StringIO()\n asciidoc.options('--no-header-footer')\n asciidoc.execute(infile, outfile, backend='html4')\n\n html = outfile.getvalue().decode('utf8')\n html = html.replace('\\r\\n', '\\n').rstrip()\n return html\n" }, { "alpha_fraction": 0.683132529258728, "alphanum_fraction": 0.6927710771560669, "avg_line_length": 22.05555534362793, "blob_id": "a112701dbf713df55ca7f2fcc3fe018932c50334", "content_id": "79b52990b48b10cf0cce715b91c620c7c351de90", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 830, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/README.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "b.py\n====\n\n.. important::\n\n As of 2016-02-26, this project is under bugfix-only status and you are also\n required to provide your own OAuth `Client ID`_ if you are using *b.py* with\n Blogger; and you will need to re-authorize.\n\n .. _Client ID:\n http://pythonhosted.org/b.py/apidoc/bpy.services.html#client-id\n\n If you would like to take over the project, please contact project owner on\n Bitbucket.\n\nEnabling bloggers to publish posts in their favorite markup language to Blogger\nor WordPress.\n\nExamples\n--------\n\n.. code:: sh\n\n b.py -s blogger post foobar.rst\n b.py -s wordpress post foobar.md\n\nMore information\n----------------\n\n* Documentation_\n* b.py_ on Bitbucket\n* PyPI_\n\n.. _documentation: http://pythonhosted.org/b.py/\n.. _b.py: http://bitbucket.org/livibetter/b.py\n.. _PyPI: https://pypi.python.org/pypi/b.py\n" }, { "alpha_fraction": 0.6932095885276794, "alphanum_fraction": 0.6971177458763123, "avg_line_length": 28.242856979370117, "blob_id": "f6f517488ed2454ab9ce141d29b991b04e7ca065", "content_id": "4c311ff74e32418bba05fdfc22310a805750c674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2047, "license_type": "permissive", "max_line_length": 79, "num_lines": 70, "path": "/bpy/handlers/html.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014 Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nHTML handler simply takes the file content as its output, and assume it's valid\nHTML, therefore the handler doesn't edit or validate the content.\n\nYou can specify embed_images_, for example:\n\n.. code:: python\n\n handlers = {\n 'HTML': {\n 'options': {\n 'embed_images': True,\n },\n },\n }\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nfrom bpy.handlers import base\n\n\nclass Handler(base.BaseHandler):\n \"\"\"Handler for HTML\n\n >>> handler = Handler(None)\n >>> print(handler.generate_header({'title': 'foobar'}))\n <!-- !b\n title: foobar\n -->\n <BLANKLINE>\n \"\"\"\n\n PREFIX_HEAD = '<!-- '\n PREFIX_END = '-->'\n HEADER_FMT = '%s: %s'\n\n def _generate(self, markup=None):\n \"\"\"Return markup untouched\n\n This handler doesn't do anything to the markup.\n\n >>> handler = Handler(None)\n >>> print(handler._generate('<br/>'))\n <br/>\n \"\"\"\n if markup is None:\n markup = self.markup\n\n return markup\n" }, { "alpha_fraction": 0.6424825191497803, "alphanum_fraction": 0.6617133021354675, "avg_line_length": 18.70689582824707, "blob_id": "f03bad95f644feb7ac538656d0105f845692cf72", "content_id": "5ea5e1c8e7291a5d01fa2657fab3468317413ceb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1144, "license_type": "permissive", "max_line_length": 80, "num_lines": 58, "path": "/docs/index.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": ".. b.py documentation master file, created by\n sphinx-quickstart on Tue Aug 20 23:04:45 2013.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nb.py documentation\n==================\n\n.. important::\n\n As of 2016-02-26, this project is under bugfix-only status and you are also\n required to provide your own OAuth :ref:`Client ID` if you are using *b.py*\n with Blogger; and you will need to re-authorize.\n\n .. _Client ID: http://pythonhosted.org/b.py/apidoc/bpy.services.html#client-id\n\n If you would like to take over the project, please contact project owner on\n Bitbucket.\n\nContents\n--------\n\n.. toctree::\n :maxdepth: 2\n\n introduction\n tutorial\n b.py\n configuration\n header\n Changes <changes>\n copyright\n\nReferences\n----------\n\n.. toctree::\n :maxdepth: 4\n\n apidoc/bpy\n\nLinks\n-----\n\n* b.py_ on Bitbucket\n* PyPI_\n\n.. _documentation: http://pythonhosted.org/b.py/\n.. _b.py: http://bitbucket.org/livibetter/b.py\n.. _PyPI: https://pypi.python.org/pypi/b.py\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n" }, { "alpha_fraction": 0.6531909704208374, "alphanum_fraction": 0.6577675938606262, "avg_line_length": 29.02290153503418, "blob_id": "d155d995e2b5ebcf466900a2e8548e94d4182c96", "content_id": "34f93ce0cae6633f58e69969e640a987b9ef10b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3933, "license_type": "permissive", "max_line_length": 79, "num_lines": 131, "path": "/bpy/services/wordpress.py", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "# Copyright (C) 2013, 2014, 2016 by Yu-Jie Lin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nWordPress service recognizes the following options in :ref:`brc.py`:\n\n.. code:: python\n\n service = 'wordpress'\n service_options = {\n 'blog': <blog url>,\n 'username': 'user01',\n 'password': 'secret',\n }\n\n``blog`` should be the URL of WordPress blog, for example,\n``http://<something>.wordpress.com/`` or ``http://example.com/wordpress/``.\nNote that the tailing slash must be included.\n\nIn order to use WordPress XML-RPC API, you must provide ``username`` and\n``password``.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport sys\n\nfrom bpy.handlers import find_handler\nfrom bpy.services.base import Service as BaseService\n\n# isort has different result for Python 2 and 3, so skip them\nfrom wordpress_xmlrpc import Client, WordPressPage, WordPressPost # isort:skip\nfrom wordpress_xmlrpc.methods import posts # isort:skip\n\n\nclass Service(BaseService):\n\n service_name = 'wordpress'\n\n def __init__(self, *args, **kwargs):\n\n super(Service, self).__init__(*args, **kwargs)\n\n self.service = None\n\n def auth(self):\n\n self.service = Client(self.options['blog'] + 'xmlrpc.php',\n self.options['username'],\n self.options['password'])\n\n def make_handler_post(self):\n\n handler = find_handler(self.filename)\n if not handler:\n print('No handler for the file!')\n sys.exit(1)\n\n hdr = handler.header\n\n post = {\n 'service': self.service_name,\n 'kind': hdr.get('kind', 'post'),\n 'content': handler.generate(),\n }\n if isinstance(self.options['blog'], type('')):\n post['blog'] = {'id': self.options['blog']}\n post.update(handler.generate_post())\n\n return handler, post\n\n def post(self):\n\n handler, post = self.make_handler_post()\n\n if 'blog' not in post:\n print('You need to specify which blog to post on '\n 'in either brc.py or header of %s.' % handler.filename)\n sys.exit(1)\n\n self.auth()\n\n kind = post['kind']\n title = post['title']\n\n if kind == 'post':\n wpost = WordPressPost()\n else:\n wpost = WordPressPage()\n\n wpost.title = title\n wpost.content = post['content']\n wpost.post_status = 'draft' if post['draft'] else 'publish'\n wpost.terms_names = {\n 'post_tag': post.get('labels', []),\n 'category': post.get('categories', []),\n }\n\n resp = {}\n if 'id' in post:\n print('Updating a %s: %s' % (kind, title))\n self.service.call(posts.EditPost(post['id'], wpost))\n else:\n print('Posting a new %s: %s' % (kind, title))\n wpost.id = self.service.call(posts.NewPost(wpost))\n wpost = self.service.call(posts.GetPost(wpost.id))\n resp['id'] = wpost.id\n resp['url'] = wpost.link\n\n for k in ('service', 'blog', 'kind', 'draft'):\n resp[k] = post[k]\n\n handler.merge_header(resp)\n handler.write()\n" }, { "alpha_fraction": 0.5178869962692261, "alphanum_fraction": 0.5262454152107239, "avg_line_length": 21.473684310913086, "blob_id": "4da4fc9da5b665a7967f808628a21aa880c493aa", "content_id": "f200d4c5a3203e993e6ad4aec5da6b39cb8073ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2991, "license_type": "permissive", "max_line_length": 101, "num_lines": 133, "path": "/b.sh", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nCMD=$1\nSRC=$2\n\nGEN_HTML=/tmp/draft.html\nGEN_PREVIEW=/tmp/preview.html\nRC=$(pwd)/b.rc\n\ngen() {\n # Only generate HTML file when needed\n if [[ -f \"$GEN_HTML\" ]] && [[ $(stat -c %y \"$SRC\") == $(stat -c %y \"$GEN_HTML\") ]]; then\n return\n fi\n\n case \"$markup\" in\n mkd)\n MARKUP='markdown2 --extras=code-friendly,footnotes=^'\n ;;\n rst)\n MARKUP='my-rst2html.py'\n ;;\n *)\n echo 'Unknown markup language: $markup' >&2\n exit 1\n esac\n\n if [[ $HAS_HEADER == yes ]]; then\n $MARKUP <(sed '1,/^$/d' \"$SRC\") > \"$GEN_HTML\"\n else\n $MARKUP \"$SRC\" > \"$GEN_HTML\"\n fi\n\n sed \"s/%%Title%%/$title/\" tmpl/tmpl1.html > \"$GEN_PREVIEW\"\n cat \"$GEN_HTML\" >> \"$GEN_PREVIEW\"\n cat tmpl/tmpl2.html >> \"$GEN_PREVIEW\"\n\n # match the timestamp\n touch -r \"$SRC\" \"$GEN_HTML\" \"$GEN_PREVIEW\"\n}\n\nget_headers() {\n sed -n '1d;/^$/q;p' \"$SRC\"\n}\n\ninsert_url() {\n if [[ $HAS_HEADER == yes ]] && get_headers | grep 'url=' >/dev/null; then\n return\n fi\n\n # extract the URL and insert into source of markup file\n URL=$(echo \"$RESULT\" | sed -n '/Post \\(created\\|updated\\)/ s/Post \\(created\\|updated\\): //p')\n if [[ $URL == http* ]]; then\n sed -i \"1 a\\\\url=$URL\" \"$SRC\"\n if [[ $HAS_HEADER == no ]]; then\n sed -i \"1 a\\\\!b\" \"$SRC\"\n fi\n fi\n}\n\npost() {\n if [[ $HAS_HEADER == yes ]] && get_headers | grep 'url=' >/dev/null; then\n echo \"Found a url in header, about posting!\" >&2\n exit 1\n fi\n\n RESULT=$(google blogger post --blog \"$blog\" --title \"$title\" -t \"$tags\" --src \"$GEN_HTML\" 2>&1)\n echo \"$RESULT\"\n insert_url\n}\n\nupdate() {\n if [[ ! -z $new_title ]]; then\n # need to update title\n RESULT=$(google blogger update --blog \"$blog\" --title \"$title\" \\\n --new-title \"$new_title\" -t \"$tags\" --src \"$GEN_HTML\" 2>&1)\n if [[ $RESULT == 'Post updated*' ]]; then\n # new_title=... -> title=...\n sed -i '1,/^$/ {/^title/d}' \"$SRC\"\n sed -i '1,/^$/ s/^new_title/title/' \"$SRC\"\n fi\n else\n RESULT=$(google blogger update --blog \"$blog\" --title \"$title\" -t \"$tags\" --src \"$GEN_HTML\" 2>&1)\n fi\n echo \"$RESULT\"\n insert_url\n}\n\ncheck_header() {\n if [[ $(head -1 \"$SRC\") == *!b* ]]; then\n HAS_HEADER=yes\n _blog=$(get_headers | sed -n '/^blog=/ {s/^blog=//;p}')\n blog=${blog:-$_blog}\n title=$(get_headers | sed -n '/^title=/ {s/^title=//;p}')\n new_title=$(get_headers | sed -n '/^new_title=/ {s/^new_title=//;p}')\n tags=$(get_headers | sed -n '/^tags=/ {s/^tags=//;p}')\n url=$(get_headers | sed -n '/^url=/ {s/^url=//;p}')\n else\n HAS_HEADER=no\n fi\n markup=${SRC##*.}\n\n _title=$(basename \"$SRC\")\n _title=\"${_title%.*}\"\n title=${title:-$_title}\n unset _blog _title\n}\n\n# Source configuration file, currently only for $blog\nif [[ -f \"$RC\" ]]; then\n source \"$RC\"\nfi\n\ncase \"$CMD\" in\n gen)\n check_header\n gen\n ;;\n post)\n check_header\n gen\n post\n ;;\n update)\n check_header\n gen\n update\n ;;\n *)\n echo \"Unknown command: $CMD\" >&2\n exit 1\n ;;\nesac\n\n\n" }, { "alpha_fraction": 0.44117647409439087, "alphanum_fraction": 0.44117647409439087, "avg_line_length": 10.333333015441895, "blob_id": "03937022b92550a06ffa2e81511ef8214282e052", "content_id": "c8ee9b7d848bef2d673521b97772c8c1139b5fcd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 68, "license_type": "permissive", "max_line_length": 23, "num_lines": 6, "path": "/docs/copyright.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "=========\nCopyright\n=========\n\n.. include:: ../COPYING\n :literal:\n" }, { "alpha_fraction": 0.54815673828125, "alphanum_fraction": 0.6150780320167542, "avg_line_length": 28.9601993560791, "blob_id": "a0d1316b6eb9f0ed73c374de7217764421aa52ec", "content_id": "932aa860af4e48f1c2c5f79d2d752f8ea6609b30", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6022, "license_type": "permissive", "max_line_length": 116, "num_lines": 201, "path": "/CHANGES.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "=======\nCHANGES\n=======\n\nVersion 0.11.0 (2016-02-26T06:04:23Z)\n=====================================\n\n* require to provide OAuth client ID and secret\n\nVersion 0.10.1 (2016-01-31T23:01:48Z)\n=====================================\n\n* fix missing ``labels`` header causing exception for WordPress service\n* add note about ``$HOME/.local/bin`` in ``$PATH`` for user scheme installation\n\nVersion 0.10.0 (2015-06-30T19:13:44Z)\n=====================================\n\n* fix ``UnicodeDecodeError`` when filename with Unicode characters\n* add ``-d``/``--debug`` for debugging messages\n* show warning about ``stdout`` encoding not ``UTF-*``, and set ``errors`` to ``replace``\n\nVersion 0.9.1 (2015-05-28T20:17:33Z)\n====================================\n\n* fix Blogger authentication warning on the deprecation of ``oauth2client.tools.run`` by switching_ to ``run_flow``.\n\n .. _switching: https://github.com/pydata/pandas/issues/8327#issuecomment-97282417\n\nVersion 0.9.0 (2014-09-09T03:06:03Z)\n====================================\n\n* Makefile\n\n * fix ``doc`` for ``CHANGES.rst`` prerequisite\n\n* add ``embed_images`` configuration option to embed image files via data URI\n scheme for all but text handler (pull request #2, by Adam Kemp)\n\n * skip ``http``, ``https``, and ``data`` schemes\n * if file not found, a message is printed out, rendered HTML tag is kept\n untouched\n * related doctest and unittest tests are added, testing ``embed_images``\n function and with ``generate``, if with text handler, it will raise\n ``RuntimeError`` or treat ``img`` tag as plain text, respectively\n * ``BaseHandler`` has class attribute ``SUPPORT_EMBED_IMAGES`` for subclass\n to turn off the support as text handler utilizing it\n\nVersion 0.8.0 (2014-08-26T12:17:09Z)\n====================================\n\n* Makefile\n\n + add ``test_doc8`` for doc8 test\n + add ``test_isort`` for import style check\n\n * rename target ``install_test`` to ``test_setup``\n * target ``test_setup``\n\n + add test for packages build\n + add test for ``LC_ALL=C``\n\n+ add Python Wheel to build process\n\n* add Blogger page draft support (#15)\n\n also simplify the post draft, both post and page use publish and revert\n action to update post or page for the draft status\n\nVersion 0.7.0 (2013-10-17T03:31:14Z)\n====================================\n\n* add documentation generation\n* setup.py\n\n + add ``build_sphinx`` and ``upload_sphinx`` commands\n\n* Makefile\n\n + add ``doc`` for documentation generation\n + add ``upload_doc`` for uploading to PyPI\n + add ``clean`` for cleaning up built files\n\n* add Blogger page support (#1)\n* add Blogger post draft support (#2)\n\n #2 is split, #15 created for page kind, which doesn't have same draft setting\n support as post kind.\n\nVersion 0.6.2 (2013-08-18T11:51:37Z)\n====================================\n\n* add test, test_pep0, test_pyflakes test_test (unittest), install_test\n Makefile targets\n* update for smartypants >= 1.8.0\n\nVersion 0.6.1 (2013-08-14T07:41:25Z)\n====================================\n\n* remove smartypants Python 3 exception, which now supports Python 3 since\n v1.7.1\n\nVersion 0.6.0 (2013-08-07T21:40:36Z)\n====================================\n\n* Port to Python 3, use Unicode in Python 2\n* Modularize Blogger API use, new services for adding new services\n* Add ``service_options`` to rc:\n\n The options for a service can be specified using ``service_options`` which is\n a ``dict``. Previous ``blog``, now must be assigned within\n ``service_options``, for example:\n\n .. code:: python\n\n service = 'blogger'\n service_options = {\n 'blog': 12345,\n 'other_option': 'other value',\n }\n\n The options will be supplied when initialize the service.\n\n* Add ``bpy.services.wordpress``\n\n * Options: ``username`` and ``password``\n * Headers: ``categories`` and ``draft``\n\n* ``service`` will be added to headers\n\nVersion 0.5.2 (2013-07-29T03:37:44Z)\n====================================\n\n* fix options doesn't get read properly\n\nVersion 0.5.1 (2013-07-29T00:49:19Z)\n====================================\n\n* fix smartypants isn't optional.\n* fix handler import on Windows. (#13)\n* fix HTML files generation location on system other than Linux\n\nVersion 0.5.0 (2013-07-25T02:55:42Z)\n====================================\n\n* remove ``client_secrets.json``, now its data is included in code. (#11)\n* fix checklink output, use lnkckr's ``print_all()``.\n\nVersion 0.4.1 (2013-03-31T14:02:39Z)\n====================================\n\n* add ``do_search`` for very simple search command\n* add ``--version`` option\n* fix unclear message, NameError on ``CLIENT_SECRETS``, when\n ``client_secrets.json`` isn't in the search path. (#10)\n\nVersion 0.4 (2013-02-13T13:33:19Z)\n==================================\n\n* add tests for ``register_directive`` and ``register_role`` decorators\n* add setup.py pylint command\n* add linkcheck command for checking links\n\nVersion 0.3.1 (2013-02-09T09:41:19Z)\n====================================\n\n* add ``register_directives`` and ``register_roles`` options of rst handler\n* remove all existing directives and roles of rst handler\n\nVersion 0.3 (2013-02-06T11:31:43Z)\n==================================\n\n* fix ``update_source`` cannot handle unicode and utf8 enocded str by ensuring\n everything is utf8 encoded internally\n* add Text handler for plain text\n* add HTML handler\n\nVersion 0.2 (2013-02-02T12:02:10Z)\n==================================\n\n* Fix trailing newlines becoming spaces in title\n* fix empty label '' in labels array\n* Add handler options ``markup_prefix`` and ``markup_suffix``\n* Add header and handler option ``id_affix`` to avoid HTML element ID conflict\n across posts\n* Add handler for AsciiDoc\n\nVersion 0.1.2 (2013-01-18T05:47:16Z)\n====================================\n\n* Fix handler rst ``settings_overrides`` not getting updates\n\nVersion 0.1.1 (2013-01-17T20:29:46Z)\n====================================\n\n* Fix handlers not getting update of options\n\nVersion 0.1 (2013-01-17T05:22:54Z)\n==================================\n\n* First versioned release\n" }, { "alpha_fraction": 0.6656760573387146, "alphanum_fraction": 0.669638454914093, "avg_line_length": 23.621952056884766, "blob_id": "e85438e3989addbdf1fd4d753486b793dae47804", "content_id": "6a4e830214cbc1d194e549446232d0bccc087f51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2019, "license_type": "permissive", "max_line_length": 79, "num_lines": 82, "path": "/docs/tutorial.rst", "repo_name": "lbarchive/b.py", "src_encoding": "UTF-8", "text": "========\nTutorial\n========\n\n\nSetting up\n==========\n\nYou should have completed the steps in :ref:`Installation` and the service\nsections, that is having the following file(s) reside in the directory for your\nposts and all :ref:`Dependencies` installed properly.\n\n* :mod:`Blogger service <bpy.services.blogger>`: :ref:`brc.py`,\n :ref:`b.dat`, and :ref:`client ID`; or\n* :mod:`WordPress service <bpy.services.wordpress>`: :ref:`brc.py`\n\n\nCreating the first post\n=======================\n\nLet's create a first post, ``my-first-post.rst`` or ``my-first-post.md``,\nwhatever markup language floats your boat:\n\n.. code:: rst\n\n !b\n service: blogger\n title: My First Post\n labels: blogging\n\n Hooray, posting frm commandline!\n\nThe first three lines are called :doc:`header`, when *b.py* sees ``!b`` in the\nbeginning of file, it knows what to do with the header. If you are using\nWordPress, change service line to::\n\n service: wordpress\n\n\nPosting to the service\n======================\n\nAfter saves the file, run the following command to post it to the service:\n\n.. code:: sh\n\n b.py post my-first-post.rst\n\nIf it runs without any problems, then open the file again, the header part\nshould have been edited by *b.py* and may look like:\n\n.. code:: rst\n\n .. !b\n service: blogger\n kind: post\n url: http://[...].blogspot.com/2013/01/my-first-post.html\n labels: blogging\n id_affix: 5e5f\n blog: <THE BLOG ID>\n id: <THE POST ID>\n title: My First Post\n\n*b.py* will insert some data to header and make header into a comment.\n\n.. seealso:: For the detail of header, please see :doc:`header`.\n\n\nUpdating the post\n=================\n\nAfter posting to the service, you spot there is a typo ``frm`` and you correct\nit. To update the post, run the same command as posting:\n\n.. code:: sh\n\n b.py post my-first-post.rst\n\nThe post should be updated on the service.\n\nIf *b.py* sees ``blog`` and ``id`` in header, then it knows that's a post\nalready published, so it will update it instead of creating a new post.\n" } ]
27
gbourgh/freesas
https://github.com/gbourgh/freesas
45fc3d7b5094e457343e55ddcd754a5052e55376
d5490e96b4b3288ecdcfa9a3e5269b331129f8a9
bae99beb465c202aee889151c0a761ad41aad925
refs/heads/master
2021-01-15T12:20:26.951239
2015-08-28T15:55:01
2015-08-28T15:55:01
34,841,133
0
0
null
2015-04-30T07:41:49
2015-05-18T14:58:30
2015-05-28T09:01:44
Python
[ { "alpha_fraction": 0.6958763003349304, "alphanum_fraction": 0.7027491331100464, "avg_line_length": 26.714284896850586, "blob_id": "8972adbe103ad7771c0965b22e19735275e316e3", "content_id": "8b5699f1a3260930323265acc9ced6711b90deb1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "permissive", "max_line_length": 49, "num_lines": 21, "path": "/test/test_all.py", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "__author__ = \"Guillaume\"\n__license__ = \"MIT\"\n__copyright__ = \"2015, ESRF\"\n\nimport unittest\nfrom test_model import test_suite_all_model\nfrom test_align import test_suite_all_alignment\nfrom test_distance import test_suite_all_distance\n\n\ndef test_suite_all():\n testSuite = unittest.TestSuite()\n testSuite.addTest(test_suite_all_model())\n testSuite.addTest(test_suite_all_alignment())\n testSuite.addTest(test_suite_all_distance())\n return testSuite\n\nif __name__ == '__main__':\n mysuite = test_suite_all()\n runner = unittest.TextTestRunner()\n runner.run(mysuite)\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6790123581886292, "avg_line_length": 19, "blob_id": "b45f316853a08db622fa64d9c191ec4ee903d0a6", "content_id": "80d8dc9f97697aeecdc9ab83f0b3fabd999c36a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "permissive", "max_line_length": 62, "num_lines": 4, "path": "/README.md", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "freesas\n=======\n\nSmall angle scattering tools ... but unlike most others, free. \n" }, { "alpha_fraction": 0.6854174137115479, "alphanum_fraction": 0.6907918453216553, "avg_line_length": 37.24657440185547, "blob_id": "f0884b90b68bc7d20ea46a60acb61df7db7154d1", "content_id": "d379126ffb2b6db1cb3d47014067e3687d4deb67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2791, "license_type": "permissive", "max_line_length": 154, "num_lines": 73, "path": "/scripts/supycomb.py", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n__author__ = \"Guillaume Bonamis\"\n__license__ = \"MIT\"\n__copyright__ = \"2015, ESRF\"\n\nimport argparse\nfrom os.path import dirname, abspath\nbase = dirname(dirname(abspath(__file__)))\nfrom freesas.align import InputModels, AlignModels\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"log_freesas\")\n\nusage = \"supycomb.py FILES [OPTIONS]\"\ndescription = \"align several models and calculate NSD\"\nparser = argparse.ArgumentParser(usage=usage, description=description)\nparser.add_argument(\"file\", metavar=\"FILE\", nargs='+', help=\"pdb files to align\")\nparser.add_argument(\"-m\", \"--mode\",dest=\"mode\", type=str, choices=[\"SLOW\", \"FAST\"], default=\"SLOW\", help=\"Either SLOW or FAST, default: %(default)s)\")\nparser.add_argument(\"-e\", \"--enantiomorphs\",type=str, choices=[\"YES\", \"NO\"], default=\"YES\", help=\"Search enantiomorphs, YES or NO, default: %(default)s)\")\nparser.add_argument(\"-q\", \"--quiet\", type=str, choices=[\"ON\", \"OFF\"], default=\"ON\", help=\"Hide log or not, default: %(default)s\")\nparser.add_argument(\"-g\", \"--gui\", type=str, choices=[\"YES\", \"NO\"], default=\"YES\", help=\"Use GUI for figures or not, default: %(default)s\")\nparser.add_argument(\"-o\", \"--output\", type=str, default=\"aligned.pdb\", help=\"output filename, default: %(default)s\")\n\nargs = parser.parse_args()\ninput_len = len(args.file)\nlogger.info(\"%s input files\"%input_len)\nselection = InputModels()\n\nif args.mode==\"SLOW\":\n slow = True\n logger.info(\"SLOW mode\")\nelse:\n slow = False\n logger.info(\"FAST mode\")\n\nif args.enantiomorphs==\"YES\":\n enantiomorphs = True\nelse:\n enantiomorphs = False\n logger.info(\"NO enantiomorphs\")\n\nif args.quiet==\"OFF\":\n logger.setLevel(logging.DEBUG)\n logger.info(\"setLevel: Debug\")\n\nif args.gui==\"NO\":\n save = True\n logger.info(\"Figures saved automatically : \\n R factor values and selection => Rfactor.png \\n NSD table and selection => nsd.png\")\nelse:\n save = False\n\nalign = AlignModels(args.file, slow=slow, enantiomorphs=enantiomorphs)\nif input_len==2:\n align.outputfiles = args.output\n align.assign_models()\n dist = align.alignment_2models()\n logger.info(\"%s and %s aligned\"%(args.file[0], args.file[1]))\n logger.info(\"NSD after optimized alignment = %.2f\" % dist)\nelse:\n align.outputfiles = [\"model-%02i.pdb\" % (i+1) for i in range(input_len)]\n selection.inputfiles = args.file\n selection.models_selection()\n selection.rfactorplot(save=save)\n align.models = selection.sasmodels\n align.validmodels = selection.validmodels\n\n align.makeNSDarray()\n align.alignment_reference()\n logger.info(\"valid models aligned on the model %s\"%(align.reference+1))\n align.plotNSDarray(rmax=round(selection.rmax, 4), save=save)\n\nif not save and input_len > 2:\n raw_input(\"Press any key to exit\")" }, { "alpha_fraction": 0.5686367154121399, "alphanum_fraction": 0.5717887878417969, "avg_line_length": 29.35885238647461, "blob_id": "520af5d26cfb22d4da1a8915c67c052c710900da", "content_id": "367b26ab7ee466081cd4a72f21e3d2cf389000f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6345, "license_type": "permissive", "max_line_length": 85, "num_lines": 209, "path": "/setup.py", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport platform\nimport glob\nimport numpy\nfrom setuptools import setup\nfrom setuptools.command.build_ext import build_ext as _build_ext\nfrom numpy.distutils.core import Extension as _Extension\n\ncmdclass = {}\n\n#########\n# Cython\n#########\n\ndef check_cython():\n \"\"\"\n Check if cython must be activated fron te command line or the environment.\n \"\"\"\n\n if \"WITH_CYTHON\" in os.environ and os.environ[\"WITH_CYTHON\"] == \"False\":\n print(\"No Cython requested by environment\")\n return False\n\n if (\"--no-cython\" in sys.argv):\n sys.argv.remove(\"--no-cython\")\n os.environ[\"WITH_CYTHON\"] = \"False\"\n print(\"No Cython requested by command line\")\n return False\n\n try:\n import Cython.Compiler.Version\n except ImportError:\n return False\n else:\n if Cython.Compiler.Version.version < \"0.17\":\n return False\n return True\n\ndef check_openmp():\n \"\"\"\n Do we compile with OpenMP ?\n \"\"\"\n if \"WITH_OPENMP\" in os.environ:\n print(\"OpenMP requested by environment: \" + os.environ[\"WITH_OPENMP\"])\n if os.environ[\"WITH_OPENMP\"] == \"False\":\n return False\n else:\n return True\n if (\"--no-openmp\" in sys.argv):\n sys.argv.remove(\"--no-openmp\")\n os.environ[\"WITH_OPENMP\"] = \"False\"\n print(\"No OpenMP requested by command line\")\n return False\n elif (\"--openmp\" in sys.argv):\n sys.argv.remove(\"--openmp\")\n os.environ[\"WITH_OPENMP\"] = \"True\"\n print(\"OpenMP requested by command line\")\n return True\n\n if platform.system() == \"Darwin\":\n # By default Xcode5 & XCode6 do not support OpenMP, Xcode4 is OK.\n osx = tuple([int(i) for i in platform.mac_ver()[0].split(\".\")])\n if osx >= (10, 8):\n return False\n return True\n\n\nUSE_OPENMP = \"openmp\" if check_openmp() else \"\"\nUSE_CYTHON = check_cython()\nif USE_CYTHON:\n from Cython.Build import cythonize\n\n\ndef Extension(name, source=None, can_use_openmp=False, extra_sources=None, **kwargs):\n \"\"\"\n Wrapper for distutils' Extension\n \"\"\"\n if source is None:\n sources = name.split(\".\")\n else:\n sources = source.split(\"/\")\n cython_c_ext = \".pyx\" if USE_CYTHON else \".c\"\n sources = [os.path.join(*sources) + cython_c_ext]\n if extra_sources:\n sources.extend(extra_sources)\n if \"include_dirs\" in kwargs:\n include_dirs = set(kwargs.pop(\"include_dirs\"))\n include_dirs.add(numpy.get_include())\n include_dirs = list(include_dirs)\n else:\n include_dirs = [numpy.get_include()]\n\n if can_use_openmp and USE_OPENMP:\n extra_compile_args = set(kwargs.pop(\"extra_compile_args\", []))\n extra_compile_args.add(USE_OPENMP)\n kwargs[\"extra_compile_args\"] = list(extra_compile_args)\n\n extra_link_args = set(kwargs.pop(\"extra_link_args\", []))\n extra_link_args.add(USE_OPENMP)\n kwargs[\"extra_link_args\"] = list(extra_link_args)\n\n ext = _Extension(name=name, sources=sources, include_dirs=include_dirs, **kwargs)\n\n if USE_CYTHON:\n cext = cythonize([ext], compile_time_env={\"HAVE_OPENMP\": bool(USE_OPENMP)})\n if cext:\n ext = cext[0]\n return ext\n\n\next_modules = [\n Extension(\"freesas._distance\", can_use_openmp=True),\n ]\n\nscript_files = glob.glob(\"scripts/*.py\")\n\n# ################### #\n# build_doc commandes #\n# ################### #\n\ntry:\n import sphinx\n import sphinx.util.console\n sphinx.util.console.color_terminal = lambda: False\n from sphinx.setup_command import BuildDoc\nexcept ImportError:\n sphinx = None\n\nif sphinx:\n class build_doc(BuildDoc):\n def run(self):\n\n # make sure the python path is pointing to the newly built\n # code so that the documentation is built on this and not a\n # previously installed version\n\n build = self.get_finalized_command('build')\n sys.path.insert(0, os.path.abspath(build.build_lib))\n\n # Build the Users Guide in HTML and TeX format\n for builder in ('html', 'latex'):\n self.builder = builder\n self.builder_target_dir = os.path.join(self.build_dir, builder)\n self.mkpath(self.builder_target_dir)\n BuildDoc.run(self)\n sys.path.pop(0)\n cmdclass['build_doc'] = build_doc\n\nclass build_ext(_build_ext):\n \"\"\"\n We subclass the build_ext class in order to handle compiler flags\n for openmp and opencl etc in a cross platform way\n \"\"\"\n translator = {\n # Compiler\n # name, compileflag, linkflag\n 'msvc': {\n 'openmp': ('/openmp', ' '),\n 'debug': ('/Zi', ' '),\n 'OpenCL': 'OpenCL',\n },\n 'mingw32': {\n 'openmp': ('-fopenmp', '-fopenmp'),\n 'debug': ('-g', '-g'),\n 'stdc++': 'stdc++',\n 'OpenCL': 'OpenCL'\n },\n 'default': {\n 'openmp': ('-fopenmp', '-fopenmp'),\n 'debug': ('-g', '-g'),\n 'stdc++': 'stdc++',\n 'OpenCL': 'OpenCL'\n }\n }\n\n def build_extensions(self):\n # print(\"Compiler: %s\" % self.compiler.compiler_type)\n if self.compiler.compiler_type in self.translator:\n trans = self.translator[self.compiler.compiler_type]\n else:\n trans = self.translator['default']\n\n for e in self.extensions:\n e.extra_compile_args = [trans[arg][0] if arg in trans else arg\n for arg in e.extra_compile_args]\n e.extra_link_args = [trans[arg][1] if arg in trans else arg\n for arg in e.extra_link_args]\n e.libraries = [trans[arg] for arg in e.libraries if arg in trans]\n _build_ext.build_extensions(self)\n\ncmdclass['build_ext'] = build_ext\n\n\nsetup(name=\"freesas\",\n version=\"0.3\",\n author=\"Guillaume Bonamis, Jerome Kieffer\",\n author_email=\"[email protected]\",\n description=\"Free tools to analyze Small angle scattering data\",\n packages=[\"freesas\"],\n test_suite=\"test\",\n data_files=glob.glob(\"testdata/*\"),\n scripts=script_files,\n install_requires=['numpy'],\n ext_modules=ext_modules,\n cmdclass=cmdclass\n )\n" }, { "alpha_fraction": 0.9137930870056152, "alphanum_fraction": 0.9137930870056152, "avg_line_length": 10.800000190734863, "blob_id": "1414a8ef8d386284a636f528428aa5a23223b504", "content_id": "c10bcfb5f12529750006cea7cd6bacc178079fd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 58, "license_type": "permissive", "max_line_length": 27, "num_lines": 5, "path": "/requirements.txt", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "numpy\ncython\nmatplotlib\nsphinx\nsphinxcontrib-programoutput" }, { "alpha_fraction": 0.6745283007621765, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 34.33333206176758, "blob_id": "27e2be80a20dbc46b0e06d020ac5e33751e42a43", "content_id": "abb468d6c676160727dd488cb714e4dac8a9f531", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "permissive", "max_line_length": 70, "num_lines": 12, "path": "/test/utilstests.py", "repo_name": "gbourgh/freesas", "src_encoding": "UTF-8", "text": "import sys, glob, os\nfrom os.path import dirname, abspath, join\nbase = dirname(dirname(abspath(__file__)))\nlibdirs = glob.glob(join(base,\"build\",\"lib*\"))\nif not libdirs: \n #let's compile cython extensions\n os.system(\"cd %s;%s setup.py build; cd -\"%(base, sys.executable)) \n libdirs = glob.glob(join(base,\"build\",\"lib*\"))\nlibdir = libdirs[0] \nprint(libdir)\nif base not in sys.modules:\n sys.path.insert(0, libdir)\n" } ]
6
Louis-dM/Advent-of-code-2020
https://github.com/Louis-dM/Advent-of-code-2020
b69b0dd62d53872abd579816122b532cf7702f6c
4e1dad525f69b97afd949a111534e76d19380265
8aa5813c09d6d59e8029f2752f817cddb1a0890c
refs/heads/main
2023-02-07T10:26:07.872736
2020-12-23T15:49:26
2020-12-23T15:49:26
317,836,579
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6414645910263062, "alphanum_fraction": 0.6623870730400085, "avg_line_length": 34.92982482910156, "blob_id": "090d5bcd9ba7c2871a28e582892f3826d48ffeb3", "content_id": "470f7e91dbaf1eba49c6969e28ec5ff3058ad83c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2103, "license_type": "no_license", "max_line_length": 103, "num_lines": 57, "path": "/Day10.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### IMPORT + FORMAT DATA ###\r\nsetwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\nadaptors <- sort(as.integer(readLines(\"Day10data.txt\"))) # sort data while importing\r\n# let's also add the power supply and the device's built-in adaptor\r\nadaptors <- c(0, adaptors, adaptors[length(adaptors)] + 3)\r\n\r\n\r\n### PART 1 ###\r\n\r\ndiffs <- function(ratings) {\r\n # DESCRIPTION #\r\n # Given a list of joltage ratings, returns how many 1-, 2- and 3-joltage gaps there are\r\n \r\n # PARAMETERS #\r\n # ratings: a *sorted* list of joltage ratings for adaptors, with gaps of size 1-3 (no more, no less)\r\n \r\n # RETURNS #\r\n # c(# of 1-gaps, # of 2-gaps, # of 3-gaps)\r\n \r\n \r\n gaps <- numeric(3)\r\n \r\n for (i in 1:(length(ratings) - 1)) {\r\n gap <- ratings[i+1] - ratings[i] # calculate size of gap to next number up\r\n gaps[gap] <- gaps[gap] + 1 # add to the tally of gap sizes\r\n }\r\n \r\n return(gaps)\r\n}\r\n\r\nadaptordiffs <- diffs(adaptors)\r\nprint(adaptordiffs[1] * adaptordiffs[3])\r\n\r\n\r\n### PART 2 ###\r\n\r\nwaystoreach <- numeric(length(adaptors)) # this will contain the # of ways to reach each joltage\r\nwaystoreach[adaptors == 0] <- 1 # start out by saying there's 1 way to reach 0\r\n\r\n# let's manually find how many ways there are to reach 1 and 2 so we dont get errors when subtracting 3\r\n# (there are adaptors of both voltages so this is ok. doing this \"properly\" would be a massive pain\r\n# since you'd have to do 3 checks for two numbers thanks to how r handles empty vectors) \r\nwaystoreach[adaptors == 1] <- waystoreach[adaptors == 0]\r\nwaystoreach[adaptors == 2] <- waystoreach[adaptors == 0] + waystoreach[adaptors == 1]\r\n\r\n# now we can check everything else\r\nfor (i in 4:length(adaptors)) {\r\n # find number of ways to reach i-3, i-2, i-1, and add them, jump-up-stairs-problem style\r\n for (j in 1:3) {\r\n if ((adaptors[i] - j) %in% adaptors) {\r\n waystoreach[i] <- waystoreach[i] + waystoreach[adaptors == adaptors[i] - j]\r\n }\r\n }\r\n}\r\n\r\n# have to stop R using scientific notation for displaying numbers this big, stupid data language\r\nformat(waystoreach[length(adaptors)], scientific = FALSE)" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5654659867286682, "avg_line_length": 19.862499237060547, "blob_id": "a24c9e65bf2b8502a6d75cb73d6f854934db2cc1", "content_id": "da794bd0dc0a4deabcd30da271c35348db786c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1749, "license_type": "no_license", "max_line_length": 85, "num_lines": 80, "path": "/Day3.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### IMPORT + FORMAT DATA ###\r\nsetwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\nhill <- read.table(text = gsub(\"#\", \"T\", readLines(\"Day3data.txt\")),\r\n sep = \"\",\r\n stringsAsFactors = FALSE)\r\n# Change to vector for ease of use\r\nhill <- hill$V1\r\n\r\n# Dimensions of hill\r\nheight <- length(hill)\r\nwidth <- nchar(hill[1])\r\n\r\nmove <- function(posn, r, d) {\r\n # DESCRIPTION #\r\n # Performs individual moves down the slope\r\n \r\n # PARAMETERS #\r\n # posn: current position (vector, length 2)\r\n # r, d: number of tiles right/down to be moved\r\n \r\n # RETURNS #\r\n # position after moving (vector, length 2)\r\n \r\n \r\n \r\n return(\r\n c(\r\n ( (posn[1] + r - 1) %% width ) + 1,\r\n posn[2] + d\r\n )\r\n )\r\n}\r\n\r\n\r\n### PART 1 ###\r\nSlopeTrees <- function(R, D) {\r\n # DESCRIPTION #\r\n # Given a step size, calculates # of trees encountered throughout the whole journey\r\n \r\n # PARAMETERS #\r\n # R, D: The number of squares Right and Down we are to travel each step\r\n \r\n # RETURNS #\r\n # Number of trees encountered along path\r\n \r\n \r\n \r\n # Initialise\r\n posn <- c(1, 1)\r\n numTrees <- 0\r\n \r\n # Go down slope, checking for trees\r\n repeat {\r\n # Move:\r\n posn <- move(posn, R, D)\r\n \r\n # Check for tree at current location:\r\n if (substr(hill[posn[2]], posn[1], posn[1]) == \"T\") {\r\n numTrees <- numTrees + 1\r\n }\r\n \r\n # Check if at end of slope yet:\r\n if (posn[2] + D > height) break\r\n }\r\n \r\n return(numTrees)\r\n}\r\n\r\nprint(SlopeTrees(3, 1))\r\n\r\n\r\n### PART 2 ###\r\n\r\nTreeProd <- SlopeTrees(1, 1)\r\nTreeProd <- TreeProd * SlopeTrees(3, 1)\r\nTreeProd <- TreeProd * SlopeTrees(5, 1)\r\nTreeProd <- TreeProd * SlopeTrees(7, 1)\r\nTreeProd <- TreeProd * SlopeTrees(1, 2)\r\n\r\nprint(TreeProd)\r\n" }, { "alpha_fraction": 0.5087040662765503, "alphanum_fraction": 0.5145067572593689, "avg_line_length": 22.619047164916992, "blob_id": "0306c9861cadd7b64fff9d07af32f3db3e797915", "content_id": "90f70645069fdbb63bcc9d70c7051e1ce138e78f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 99, "num_lines": 63, "path": "/Day9.py", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### INPUT ###\r\n\r\nwith open('Data\\Day9data.txt') as file:\r\n XMAS = [int(n) for n in file.read().split('\\n')[:-1]]\r\n\r\nN = len(XMAS)\r\n\r\n\r\n### FUNCTIONS ###\r\n\r\ndef xmascheck(pre, xmas):\r\n '''\r\n \r\n Parameters\r\n ----------\r\n pre : length of preamble\r\n xmas : XMAS encryption file\r\n\r\n Returns\r\n -------\r\n List of numbers which are not valid in the xmas file\r\n\r\n '''\r\n \r\n invalid = [] # to be returned after filling with invalid numbers\r\n \r\n for i in range(pre, N):\r\n # lets have a variable for checking if xmas[i] is valid or not\r\n valid = False\r\n # can we find a way around this with stuff like pass/break?\r\n # because i know this is bad\r\n \r\n for j in range(pre):\r\n if xmas[i] - xmas[i - (j+1)] in xmas[i-pre:i]:\r\n valid = True\r\n \r\n if valid == False:\r\n invalid.append(xmas[i])\r\n \r\n return(invalid)\r\n\r\n\r\n### DAY 1 ###\r\n\r\nweakness = xmascheck(25, XMAS)[0]\r\nprint(weakness)\r\n\r\n\r\n### DAY 2 ###\r\n\r\ndef foo():\r\n # returns smallest/greatest values in the sum\r\n # made it a function because its the easiest way to get out of loops when you're done with them\r\n \r\n for i in range(N): # XMAS[i] is the first value in the sum\r\n for j in range(i, N): # XMAS[j-1] is the last value in the sum\r\n if sum(XMAS[i:j]) > weakness:\r\n break\r\n if sum(XMAS[i:j]) == weakness:\r\n return([min(XMAS[i:j]), max(XMAS[i:j])])\r\n \r\n \r\nprint(sum(foo()))\r\n" }, { "alpha_fraction": 0.41545894742012024, "alphanum_fraction": 0.4589371979236603, "avg_line_length": 18.032258987426758, "blob_id": "39e8f1082f8967efc83d6a3721a96f26730a27fa", "content_id": "eb2542b8e5ce49bb07a3e4e845d822d046c68e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 621, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/Day1.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "setwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\nexpenses <- scan(\"Day1data.txt\")\r\nn <- length(expenses)\r\n\r\n\r\n### PART 1 ###\r\npart1 <- function() {\r\n for (i in 1:(n-1)) {\r\n for (j in (i+1):n) {\r\n if (expenses[i] + expenses[j] == 2020) {\r\n return(expenses[i] * expenses[j])\r\n }\r\n }\r\n }\r\n}\r\npart1()\r\n\r\n\r\n### PART 2 ###\r\npart2 <- function() {\r\n for (i in 1:(n-2)) {\r\n for (j in (i+1):(n-1)) {\r\n for (k in (j+1):n) {\r\n if (expenses[i] + expenses[j] + expenses[k] == 2020) {\r\n return(expenses[i] * expenses[j] * expenses[k])\r\n }\r\n }\r\n }\r\n }\r\n}\r\npart2()\r\n" }, { "alpha_fraction": 0.5432624220848083, "alphanum_fraction": 0.5659574270248413, "avg_line_length": 25.153846740722656, "blob_id": "9b4cc62cfee591b4dcfd1a9d56a1032ae712d709", "content_id": "51b756ee8c795548702bcb82f793ea1e8ca752ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1410, "license_type": "no_license", "max_line_length": 98, "num_lines": 52, "path": "/Day2.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "library(stringr)\r\n\r\n### IMPORT + FORMAT DATA ###\r\nsetwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\n\r\n# we want to separate the data into four columns:\r\n# min(restricted_letter), max(restricted_letter), restricted_letter, password\r\n# to split up data by both \"-\" and \" \", we sub in \" \" into every \"-\" and then use sep = \" \"\r\npws <- read.table(text = gsub(\"-\", \" \", readLines(\"Day2data.txt\")),\r\n sep = \" \",\r\n stringsAsFactors = FALSE)\r\n# colons are still in col3 but we'll deal with them when we need to to avoid looping unnecessarily\r\n\r\nn <- nrow(pws)\r\n\r\n\r\n### PART 1 ###\r\ncount <- 0\r\n\r\nfor (i in 1:n) {\r\n # first, since we're in a loop anyway, let's fix the colons\r\n pws[i, 3] <- sub(\":\", \"\", pws[i, 3])\r\n \r\n # Now we check if there are the correct number of letters in the password\r\n letter <- pws[i, 3]\r\n nletter <- str_count(pws[i, 4], letter)\r\n if ((pws[i, 1] <= nletter) && (nletter <= pws[i, 2])) {\r\n count <- count + 1\r\n }\r\n}\r\nprint(count)\r\n\r\n\r\n### PART 2 ###\r\ncount <- 0\r\n\r\nfor (i in 1:n) {\r\n # my code isn't ugly right?\r\n pos1 <- pws[i, 1]\r\n pos2 <- pws[i, 2]\r\n letter <- pws[i, 3]\r\n pw <- pws[i, 4]\r\n \r\n # ok now everything is readable lets do this\r\n if (\r\n abs( (substr(pw, pos1, pos1) == letter) - (substr(pw, pos2, pos2) == letter) )\r\n # this works because 1 = TRUE and 0 = FALSE\r\n ) {\r\n count <- count + 1\r\n }\r\n}\r\nprint(count)" }, { "alpha_fraction": 0.5511651635169983, "alphanum_fraction": 0.5724417567253113, "avg_line_length": 22.674999237060547, "blob_id": "ad556c746e594ac19feaa46be6e05a545f6b0fed", "content_id": "0b7820663c65b36c44df4afcfcf315c4f354db30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1974, "license_type": "no_license", "max_line_length": 101, "num_lines": 80, "path": "/Day5.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### IMPORT + FORMAT DATA ###\r\nsetwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\n# read in data and substitute 1s/0s in place of letters\r\nrawdata <- gsub(\"F|L\", 0,\r\n gsub(\"B|R\", 1,\r\n readLines(\"Day5data.txt\")\r\n )\r\n )\r\nn <- nrow(BPs)\r\nBPs <- matrix(0, nrow = n, ncol = 10) # set up matrix for data\r\nfor (i in 1:n) {\r\n BPs[i,] <- as.integer(unlist(strsplit(rawdata[i], split = \"\"))) # split strings and fill matrix\r\n}\r\n\r\n\r\n### FUNCTIONS ###\r\nBProw <- function(BP) {\r\n # DESCRIPTION #\r\n # Takes a single Boarding Pass and gives the row number\r\n \r\n # PARAMETERS #\r\n # BP: Vector of length 10. First 7 digits correspond to Row number, last 3 are column number.\r\n \r\n # RETURNS #\r\n # Row number\r\n \r\n \r\n return(sum(BP[1:7] * 2^(6:0)))\r\n}\r\n\r\n\r\nBPcol <- function(BP) {\r\n # DESCRIPTION #\r\n # Takes a single Boarding Pass and gives the column number\r\n \r\n # PARAMETERS #\r\n # BP: Vector of length 10. First 7 digits correspond to Row number, last 3 are column number.\r\n \r\n # RETURNS #\r\n # Column number\r\n \r\n \r\n return(sum(BP[8:10] * 2^(2:0)))\r\n}\r\n\r\n\r\nBPseat <- function(r, c) {\r\n # DESCRIPTION #\r\n # Takes a row and column number and returns the seat ID\r\n \r\n # PARAMETERS #\r\n # r: row number\r\n # c: column number\r\n \r\n # RETURNS #\r\n # Seat ID\r\n \r\n \r\n return(r*8 + c)\r\n}\r\n\r\n\r\n### PART 1 ###\r\nseatIDs <- numeric(n)\r\n\r\nfor (i in 1:n) {\r\n seatIDs[i] <- BPseat(BProw(BPs[i,]),\r\n BPcol(BPs[i,])\r\n )\r\n}\r\nmax(seatIDs)\r\n\r\n\r\n### PART 2 ###\r\nmin(seatIDs[as.logical(1 - ((seatIDs+1) %in% seatIDs))]) + 1\r\n# A much-needed explanation:\r\n# The inner part checks which seats have the following seat missing\r\n# It does this by checking which seats have the following seat *present*, and doing as.logical(1 - x)\r\n# There should only be two: the highest seat number, and 1 less than your seat number\r\n# So, take the minimum of these and add 1\r\n" }, { "alpha_fraction": 0.5513849258422852, "alphanum_fraction": 0.5594097971916199, "avg_line_length": 24.82638931274414, "blob_id": "dfc8746c4490ed69e6c3cf03d055dd28c702f8b6", "content_id": "4526e54a588d996c4ba6468fced58d92d7016329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3863, "license_type": "no_license", "max_line_length": 102, "num_lines": 144, "path": "/Day8.R", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### IMPORT + FORMAT DATA ###\r\nsetwd(\"~/Other/Programming/Advent of code/2020/Data\")\r\nboot <- read.table(text = gsub(\"-\", \"- \",\r\n gsub(\"\\\\+\", \"\\\\+ \",\r\n readLines(\"Day8data.txt\"))),\r\n sep = \" \",\r\n stringsAsFactors = FALSE)\r\n\r\n\r\n### FUNCTIONS ###\r\nupdateACC <- function(acc, op, num) {\r\n # DESCRIPTION #\r\n # Originally designed to update the accumulator according to given instructions\r\n # However, it also serves to update the instruction line when a jump command is used\r\n \r\n # PARAMETERS #\r\n # acc: current value in accumulator OR current instruction line\r\n # op: operation (\"+\" or \"-\")\r\n # num: value by which accumulator OR current instruction line is to be updated by, in direction\r\n # specified by op\r\n return(\r\n eval(\r\n parse(\r\n text = paste(\r\n toString(acc),\r\n op,\r\n toString(num)\r\n )\r\n )\r\n )\r\n )\r\n}\r\n\r\nread <- function(bootcode, acc, inst) {\r\n # DESCRIPTION #\r\n # takes current accumulator value and instruction line number and returns their updated values after\r\n # reading and parsing the current line of code\r\n \r\n # PARAMETERS #\r\n # bootcode: table of boot instructions\r\n # acc: current acumulator value\r\n # inst: current instruction line\r\n \r\n # RETURNS\r\n # c(updated accumulator value, updated boot code line)\r\n \r\n \r\n fn <- bootcode[inst, 1]\r\n sgn <- bootcode[inst, 2]\r\n num <- bootcode[inst, 3]\r\n \r\n if (fn == \"nop\") {\r\n return(c(acc,\r\n inst + 1))\r\n } else if (fn == \"acc\") {\r\n return(c(updateACC(acc,\r\n sgn,\r\n num),\r\n inst + 1))\r\n } else {\r\n return(c(acc,\r\n updateACC(inst,\r\n sgn,\r\n num)))\r\n}\r\n\r\n### PART 1 ###\r\nACC <- 0\r\ninstr <- 1\r\nn <- nrow(boot)\r\nvisited <- numeric(n)\r\n\r\nwhile (visited[instr] == 0) {\r\n visited[instr] <- 1\r\n # we can update accumulator and instruction line separately ONLY IF WE UPDATE THE ACCUMULATOR FIRST\r\n # (because instr affects the next update of ACC, but ACC does not affect the next update of instr)\r\n ACC <- read(boot, ACC, instr)[1]\r\n instr <- read(boot, ACC, instr)[2]\r\n }\r\n}\r\n\r\nprint(ACC)\r\n\r\n\r\n\r\n### PART 2 ###\r\nrunboot <- function(bootcode) {\r\n # DESCRIPTION #\r\n # Runs entire boot sequence and checks for errors (e.g. index oob or a loop)\r\n\r\n # PARAMETERS\r\n # bootcode: table of boot instructions\r\n \r\n # RETURNS\r\n # either \"ERROR\" if there is a loop or the index goes oob,\r\n # or the value of the accumulator if the code works\r\n \r\n \r\n # reset boot sequence\r\n ACC <- 0\r\n instr <- 1\r\n visited <- numeric(n)\r\n \r\n repeat {\r\n # check if we've left the range of instructions (or reached a loop) and act accordingly\r\n # order matters: the third check needs to be done after the first two\r\n if (instr > n+1) {\r\n return(\"ERROR\")\r\n }\r\n if (instr == n+1) {\r\n return(ACC)\r\n }\r\n if (visited[instr] == 1) {\r\n return(\"ERROR\")\r\n }\r\n \r\n # and if we haven't, carry on as normal\r\n visited[instr] <- 1\r\n \r\n ACC <- read(bootcode, ACC, instr)[1]\r\n instr <- read(bootcode, ACC, instr)[2]\r\n }\r\n}\r\n\r\n# Now we can loop through, changing each instruction and running the new versions of the code\r\nfor (i in 1:n) {\r\n newboot <- boot\r\n \r\n if (boot[i, 1] == \"jmp\") {\r\n newboot[i, 1] <- \"nop\" # make attempt to fix instruction\r\n result <- runboot(newboot) # run new boot code\r\n if (result != \"ERROR\") { # print result if code works\r\n print(result)\r\n break\r\n }\r\n } else if (boot[i, 1] == \"nop\") {\r\n newboot[i, 1] <- \"jmp\" # make attempt to fix instruction\r\n result <- runboot(newboot) # run new boot code\r\n if (result != \"ERROR\") { # print result if code works\r\n print(result)\r\n break\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.39596468210220337, "alphanum_fraction": 0.4199243485927582, "avg_line_length": 18.86842155456543, "blob_id": "bb04aa8e9db73af2c0d8fa95f52d1039c613763d", "content_id": "7f3d704387deb42289182b4b5568ba2389882d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 793, "license_type": "no_license", "max_line_length": 61, "num_lines": 38, "path": "/Day1.py", "repo_name": "Louis-dM/Advent-of-code-2020", "src_encoding": "UTF-8", "text": "### INPUT ###\r\n\r\nwith open('Data\\Day1data.txt') as file:\r\n expenses = [int(n) for n in file.read().split('\\n')[:-1]]\r\n\r\nN = len(expenses)\r\n\r\n\r\n### PART 1 ###\r\n\r\ndef expcheck2(total):\r\n for i in range(N):\r\n n = expenses[i]\r\n for j in range(i+1, N):\r\n m = expenses[j]\r\n if n + m == total:\r\n return(n*m)\r\n \r\n return(\"Error\")\r\n \r\nprint(expcheck2(2020))\r\n\r\n\r\n### PART 2 ###\r\n\r\ndef expcheck3(total):\r\n for i in range(N):\r\n n = expenses[i]\r\n for j in range(i+1, N):\r\n m = expenses[j]\r\n for k in range(j+1, N):\r\n l = expenses[k]\r\n if n + m + l == total:\r\n return(n*m*l)\r\n \r\n return(\"Error\")\r\n\r\nprint(expcheck3(2020))\r\n" } ]
8
sridevi-mk/factorial_test
https://github.com/sridevi-mk/factorial_test
8b24b9a1875bc56461d193371a3ff8f9f5125963
a12c5f8896428ffddf3e50e08d0cc6a650eab688
e90b2a95608a91adc2e2de14cd93f13c71ca9d0f
refs/heads/main
2023-08-07T00:39:40.883718
2021-09-22T19:13:00
2021-09-22T19:13:00
409,237,498
0
0
null
2021-09-22T14:30:12
2021-09-22T19:11:03
2021-09-22T19:13:00
Python
[ { "alpha_fraction": 0.5863747000694275, "alphanum_fraction": 0.6034063100814819, "avg_line_length": 19.549999237060547, "blob_id": "0090410af51af0556073848b9e906fc3e51c03b4", "content_id": "f9bd81a534d69fa5a0807ab3e69a33465ad26c87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 58, "num_lines": 20, "path": "/fact.py", "repo_name": "sridevi-mk/factorial_test", "src_encoding": "UTF-8", "text": "def factorial(a):\n if a==1:\n return a\n else:\n return a*factorial(a-1)\n\na=int(input(\"Enter a number : \"))\n\nif a<0:\n print(\"There is no factorial for 0.\")\nelif a == 0:\n print(\"The factorial of 0 is 1.\")\nelse:\n print(\"The factorial of\",a,\"is\",str(factorial(a))+\".\")\n \nPrint(\"testing for the new branch merge\")\n\nprint(\"This is a factorial program\")\n \n#added a new comment to test\n" } ]
1
jagan-singh/adventure_game
https://github.com/jagan-singh/adventure_game
e10b1ee3bda144bb0d63ff30659d3a91a1eaae0a
6a9bf71ca77749d2527488eaa44fa121c1d523a9
ac06b2044005bf4a3f054dac4a0f556d5da38f32
refs/heads/master
2023-06-10T20:09:51.254214
2019-07-16T03:52:58
2019-07-16T03:52:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5168289542198181, "alphanum_fraction": 0.5349393486976624, "avg_line_length": 30.809782028198242, "blob_id": "02c229fa265e4f448b73364e809682e761026ec6", "content_id": "97768ebff5a7900e70753dc61aa6d933718fb48f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5853, "license_type": "no_license", "max_line_length": 79, "num_lines": 184, "path": "/adventure_game.py", "repo_name": "jagan-singh/adventure_game", "src_encoding": "UTF-8", "text": "import time\nimport random\n\n# List of all the enemies in the game to randomize.\nenemies = [\"Dragon\", \"Troll\", \"Pirate\", \"Vampire\", \"Gorgon\", \"Ghost\"]\n\n# boolean to check if the game is being played for the first time\nfirstTime = True\n\n# Boolean to check if the game is being restarted\nrestart = False\n\n# to check if the player have the sword or not\nsword = False\n\n\ndef house(name, weap):\n print(\"You approach the door of the house.\")\n time.sleep(1.5)\n print(\"You are about to knock when the door opens and\"\n \" out steps a \" + name + \".\")\n time.sleep(1.5)\n print(\"Eep! This is the \" + name + \"\\'s house!\")\n time.sleep(1.5)\n print(\"The \" + name + \" attacks you!\")\n time.sleep(1.5)\n if not weap:\n print(\"You feel a bit under-prepared for this, \"\n \"what with only having a tiny dagger.\")\n time.sleep(1.5)\n print(\"Would you like to (1) fight or (2) run away?\")\n res = input(\"Please enter 1 or 2\\n\")\n while True:\n if res == \"1\":\n if weap:\n print(\"As the \" + name + \" moves to attack, \"\n \"you unsheath your new sword.\")\n time.sleep(1.5)\n print(\"The Sword of Ogoroth shines brightly in your hand\"\n \" as you brace yourself for the attack.\")\n time.sleep(1.5)\n print(\"But the \" + name + \" takes one look at \"\n \"your shiny new toy and runs away!\")\n time.sleep(1.5)\n print(\"You have rid the town of the \" + name +\n \". You are victorious!\")\n time.sleep(1.5)\n else:\n print(\"You do your best...\")\n time.sleep(1.5)\n print(\"but your dagger is no match for the wicked fairie.\")\n time.sleep(1.5)\n print(\"You have been defeated!\")\n time.sleep(1.5)\n break\n elif res == \"2\":\n field()\n break\n else:\n res = input(\"Please enter 1 or 2\\n\")\n\n\ndef cave(weapo):\n print(\"You peer cautiously into the cave.\")\n time.sleep(1.5)\n if not weapo:\n print(\"It turns out to be only a very small cave.\")\n time.sleep(1.5)\n print(\"Your eye catches a glint of metal behind a rock.\")\n time.sleep(1.5)\n print(\"You have found the magical Sword of Ogoroth!\")\n time.sleep(1.5)\n print(\"You discard your silly old dagger and take the sword with you.\")\n weapo = True\n time.sleep(1.5)\n print(\"You walk back out to the field.\")\n time.sleep(1.5)\n print(\"\\nEnter 1 to knock on the door of the house.\")\n time.sleep(1.5)\n print(\"Enter 2 to peer into the cave.\")\n time.sleep(1.5)\n print(\"What would you like to do?\")\n else:\n print(\"You've been here before, and gotten all the good stuff.\"\n \" It's just an empty cave now.\")\n time.sleep(1.5)\n print(\"You walk back out to the field.\")\n time.sleep(1.5)\n print(\"\\nEnter 1 to knock on the door of the house.\")\n time.sleep(1.5)\n print(\"Enter 2 to peer into the cave.\")\n time.sleep(1.5)\n print(\"What would you like to do?\")\n\n n = input(\"Please enter 1 or 2\\n\")\n while True:\n if n == \"1\":\n house(enemy, weapo)\n break\n elif n == \"2\":\n cave(weapo)\n break\n else:\n n = input(\"Please enter 1 or 2\\n\")\n\n\ndef field():\n print(\"You run back into the field. Luckily, \"\n \"you don't seem to have been followed.\")\n time.sleep(1.5)\n print(\"\")\n print(\"Enter 1 to knock on the door of the house.\")\n time.sleep(1.5)\n print(\"Enter 2 to peer into the cave.\")\n time.sleep(1.5)\n print(\"What would you like to do?\")\n num = input(\"Please enter 1 or 2\\n\")\n while True:\n if num == \"1\":\n house(enemy, sword)\n break\n elif num == \"2\":\n cave(sword)\n break\n else:\n num = input(\"Please enter 1 or 2\\n\")\n\n\ndef play_again():\n response = input(\"Would you like to play again? (y/n)\\n\")\n while True:\n if response == \"y\":\n print(\"Excellent! Restarting the game\\n\")\n time.sleep(2)\n return True\n elif response == \"n\":\n print(\"Thanks for playing! See you next time.\")\n time.sleep(2)\n return False\n else:\n response = input(\"Would you like to play again? (y/n)\\n\")\n return False\n\n\nwhile firstTime or restart:\n enemy = random.choice(enemies)\n sword = False\n firstTime = False\n restart = False\n weapon = False\n print(\"You find yourself standing in an open field,\"\n \" filled with grass and yellow wildflowers.\")\n time.sleep(1.5)\n print(\"Rumor has it that a \" + enemy +\n \" is somewhere around here, and\"\n \" has been terrifying the nearby village.\")\n time.sleep(1.5)\n print(\"In front of you is a house.\")\n time.sleep(1.5)\n print(\"To your right is a dark cave.\")\n time.sleep(1.5)\n print(\"In your hand you hold your trusty (but not very effective) dagger.\")\n print(\"\")\n time.sleep(1.5)\n print(\"Enter 1 to knock on the door of the house.\")\n time.sleep(1.5)\n print(\"Enter 2 to peer into the cave.\")\n time.sleep(1.5)\n print(\"What would you like to do?\")\n num = input(\"Please enter 1 or 2\\n\")\n\n# while loop is used to get specific input from the user (1 or 2 only)\n while True:\n if num == \"1\":\n house(enemy, sword)\n break\n elif num == \"2\":\n cave(sword)\n sword = True\n break\n else:\n num = input(\"Please enter 1 or 2\\n\")\n\n restart = play_again()\n" } ]
1
Ashafix/argparse2HTML
https://github.com/Ashafix/argparse2HTML
cbab644c23acbaeb3b1514794c061566ae645ffa
a9695d3e8ef61cf3f2cfb05420031f17e8f4da32
bf05fe6c5ea3ce0d2b260c4745cf07d18ecf56bf
refs/heads/master
2020-12-26T18:37:58.363131
2020-03-22T19:34:41
2020-03-22T19:34:41
237,600,117
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6344961524009705, "alphanum_fraction": 0.6414728760719299, "avg_line_length": 32.07692337036133, "blob_id": "203eb6fa338fafde498a406c3b0c7a0b9595b848", "content_id": "b38317b794f81ef6b67dcaf2f56dbaf008e613d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2580, "license_type": "no_license", "max_line_length": 90, "num_lines": 78, "path": "/blueprints/celery_task.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import os\nimport logging\nimport contextlib\nimport dill\nimport binascii\nfrom flask import request, jsonify, Response\nfrom flask import Blueprint, redirect, url_for\nfrom celery import Celery\nfrom args import get_cli\nfrom config import JOB_FOLDER, CELERY_BROKER_URL, RESULT_BACKEND\n\n\ncelery = Celery('argparser_server', broker=CELERY_BROKER_URL, backend=RESULT_BACKEND)\n\nFILENAME_LOG = os.path.join(JOB_FOLDER, '{}.log')\n\napp_with_celery = Blueprint('app_with_celery', __name__,\n template_folder='templates')\n\n\[email protected](name='server.background_task', bind=True)\ndef background_task(self, function, args):\n logger = logging.getLogger(self.request.id)\n filehandler = logging.FileHandler(FILENAME_LOG.format(self.request.id))\n logger.addHandler(filehandler)\n\n function = dill.loads(binascii.a2b_base64(function))\n args = dill.loads(binascii.a2b_base64(args))\n\n with contextlib.redirect_stdout(LoggerWriter(logger, 20)):\n return function(args)\n\n\n@app_with_celery.route('/run/<command>', methods=['POST'])\ndef run_post(command):\n params = request.get_json()\n found, cli = get_cli(command)\n if not found:\n return redirect (url_for('list_available_commands'))\n func = binascii.b2a_base64(dill.dumps(cli.function)).decode()\n args = cli.parser.parse_args(params)\n base64_args = binascii.b2a_base64(dill.dumps(args)).decode()\n task = background_task.apply_async(args=(func, base64_args))\n return task.id\n\n\n@app_with_celery.route('/status/<task_id>')\ndef task_status(task_id):\n task = background_task.AsyncResult(task_id)\n if request.headers.get('accept') == 'text/event-stream':\n def status():\n while task.status not in ('SUCCESS', 'FAILURE', 'REVOKED'):\n fname = FILENAME_LOG.format(task_id)\n resp = ['data: \\n']\n if os.path.isfile(fname):\n with open(fname, 'r') as f:\n resp = [\"data: {}\".format(line.strip()) for line in f.readlines()]\n resp.append('\\n')\n\n yield '\\n'.join(resp)\n yield \"data: \\n\\n\"\n return Response(status(), content_type='text/event-stream')\n if task.status == 'SUCCESS':\n return jsonify(task.result)\n return jsonify(task.status)\n\n\nclass LoggerWriter:\n def __init__(self, logger, level):\n self.logger = logger\n self.level = level\n\n def write(self, message):\n if message != '\\n':\n self.logger.log(logging.CRITICAL, message)\n\n def flush(self, *kargs, **kwargs):\n pass\n" }, { "alpha_fraction": 0.5505026578903198, "alphanum_fraction": 0.5567256808280945, "avg_line_length": 32.67741775512695, "blob_id": "da996c209ca5b38aef0d5fc11005e336cd36abb2", "content_id": "bc9c22c9924f5662d2c4c32ae6c94c6da336b34a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2089, "license_type": "no_license", "max_line_length": 105, "num_lines": 62, "path": "/example_argparser.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import argparse\nimport itertools\nimport time\nimport builtins\n\nparser1 = argparse.ArgumentParser(prog='simple math', description='a simple math command line interface')\nparser1.add_argument('x', help='first value',\n default='2',\n type=int)\nparser1.add_argument('y', help='second value',\n default='3',\n type=int)\nparser1.add_argument('--action', help='which method to apply',\n default='min', choices=['min', 'max', 'sum'],\n type=str)\n\nparser_cycler = argparse.ArgumentParser(prog='cycler')\nparser_cycler.add_argument('--delay', help='delay in seconds',\n default=0.1,\n type=float)\nparser_cycler.add_argument('--max', help='Number of iterations',\n default=20,\n type=int)\nparser_cycler.add_argument('--characters', help='Cycle through those characters',\n default='\\\\|/-',\n type=str)\n\nparser_wrapper = argparse.ArgumentParser(prog='wrapper')\nparser_wrapper.add_argument('columns', help='List of comma separated column names',\n default='a,b,c',\n type=str)\nparser_wrapper.add_argument('values', help='List of comma separated values',\n default='1,2,3',\n type=str)\n\n\ndef simple_math(args):\n vals = [args.x, args.y]\n f = getattr(builtins, args.action)\n return f(vals)\n\n\ndef cycler(args):\n for i, c in enumerate(itertools.cycle(args.characters)):\n print(c)\n time.sleep(args.delay)\n if i >= args.max:\n break\n return 'Finished after {} iterations'.format(i)\n\n\ndef wrapper(args):\n columns = args.columns.split(',')\n values = args.values.split(',')\n return complex_function(columns, values)\n\n\ndef complex_function(columns, values):\n resp = []\n for c, col in enumerate(columns):\n resp.append('{}: {}'.format(col, values[c]))\n return '\\n'.join(resp)\n\n" }, { "alpha_fraction": 0.6485355496406555, "alphanum_fraction": 0.6523012518882751, "avg_line_length": 31.189189910888672, "blob_id": "6f97be2092b0a2078e846689acb708b544c29f74", "content_id": "42fe12835f20c95851e9726f4d702c2258213c17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2390, "license_type": "no_license", "max_line_length": 117, "num_lines": 74, "path": "/README.md", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "# argparse2HTML\n\n## Features\n* Converts an `argparse.ArgumentParser` object into a GUI/HTML input form.\n* Arbitrary Python functions can be executed asynchronously via a simple web interface\n* Hot swapping of functions/parser possible\n* Execution via `subprocess` or `celery`\n* Runs on Linux and Windows\n* Automatic translation of `ArgumentParser` attributes in GUI elements\n * `choices` become radio buttons\n * `type=int` becomes numeric only input form\n * `help` text is shown in hover info\n * `default` values are applied\n\n## Usage\n\n* Create a function which takes a `ArgumentParser` namespace as its input and a corresponding `ArgumentParser` object\n ```\n # our function which needs a GUI \n def simple_math(args):\n vals = [args.x, args.y]\n f = getattr(builtins, args.action)\n return f(vals)\n\n # our ArgumentParser\n parser = argparse.ArgumentParser(prog='simple math', description='a simple math command line interface')\n parser1.add_argument('x', help='first value',\n default='2',\n type=int)\n parser1.add_argument('y', help='second value',\n default='3',\n type=int)\n parser1.add_argument('--action', help='which method to apply',\n default='min', choices=['min', 'max', 'sum'],\n type=str)\n ```\n\n* Import the function in `args.py`\n\n ```\n from example_argparser import parser1, simple_math\n ```\n* Add it to the `parsers` in `args.py`\n ```\n parsers = [Parser(name=parser1.prog,\n parser=parser1,\n function=simple_math)\n ]\n ```\n\n* Start the Flask webserver\n\n ```\n python server.py\n ```\n* All your registered functions/argparsers are available\n\n ![Available commands screenshot](docs/images/available_commands.png \"Available commands\")\n\n* Execute the Python script\n\n ![Simle Math function](docs/images/demo.gif \"Demonstration\")\n\n\n## Configuration\n\n* Modify `config.py`\n * `USE_CELERY`: if `True` celery is used for starting jobs\n * `JOB_FOLDER`: where your job results and log files are stored\n * `SERVER_PORT`: on which port the server is listening\n \n* Register your Python functions and parsers in `args.py`\n* Hot-swap them by opening `/refresh`\n* The layout of the forms can be modified by changing `main.css` in the `static/css` directory\n \n\n\n\n" }, { "alpha_fraction": 0.541907012462616, "alphanum_fraction": 0.545300304889679, "avg_line_length": 29.989473342895508, "blob_id": "3e871cd3762f74d7cdd0e6eb31de429453c7005d", "content_id": "a6b192d63f562caa4bba3263c976235e45ce24b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2947, "license_type": "no_license", "max_line_length": 158, "num_lines": 95, "path": "/blueprints/subprocess_task.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport uuid\nimport psutil\nimport subprocess\nfrom flask import request, jsonify, Response\nfrom flask import Blueprint, redirect, url_for\n\nfrom args import get_cli\nfrom config import JOB_FOLDER\n\nFILENAME_LOG = os.path.join(JOB_FOLDER, '{}.log')\nFILENAME_PID = os.path.join(JOB_FOLDER, '{}.pid')\n\nSEP = '=-' * 30\n\napp_with_subprocess = Blueprint('app_with_subprocess ', __name__,\n template_folder='templates')\n\n\n@app_with_subprocess.route('/run/<command>', methods=['POST'])\ndef run_post(command):\n params = request.get_json()\n found, cli = get_cli(command)\n if not found:\n return redirect(url_for('list_available_commands'))\n\n args = cli.parser.parse_args(params)\n code = 'from {module} import {function}; import argparse; args = argparse.Namespace(**{args}); r = ({function}(args)); print(\\'{SEP}\\'); print(r)'.format(\n module=cli.function.__module__,\n function=cli.function.__name__,\n SEP=SEP,\n args=args.__dict__\n )\n\n task_id = str(uuid.uuid4())\n\n f = open(FILENAME_LOG.format(task_id), 'w+')\n\n p = subprocess.Popen([sys.executable, '-u', '-c', code], stderr=f, stdout=f, bufsize=0)\n with open(FILENAME_PID.format(task_id), 'w') as ff:\n ff.write(str(p.pid))\n return str(task_id)\n\n\n@app_with_subprocess.route('/status/<task_id>')\ndef task_status(task_id):\n\n try:\n with open(FILENAME_PID.format(task_id), 'r') as f:\n pid = int(f.read())\n process = psutil.Process(pid)\n except (FileNotFoundError, psutil.NoSuchProcess, psutil.AccessDenied):\n process = None\n\n fname = FILENAME_LOG.format(task_id)\n\n if request.headers.get('accept') == 'text/event-stream':\n def status():\n while process is not None:\n try:\n process_running = process.status() == psutil.STATUS_RUNNING\n except psutil.NoSuchProcess:\n process_running = False\n if not process_running:\n break\n try:\n with open(fname, 'r') as f:\n resp = [\"data: {}\".format(line.strip()) for line in f.readlines()]\n except (FileNotFoundError, IOError):\n resp = ['data: \\n']\n\n resp.append('\\n')\n\n yield '\\n'.join(resp)\n yield 'data: \\n\\n'\n return Response(status(), content_type='text/event-stream')\n\n try:\n with open(fname, 'r') as f:\n lines = f.readlines()\n i = len(lines) - 1\n while i >= 0:\n\n if lines[i].strip() == SEP:\n break\n i -= 1\n if len(lines) > 0 and i >= 0:\n resp = '\\n'.join([line.strip() for line in lines[i + 1:]])\n else:\n resp = ''\n except (FileNotFoundError, IOError):\n resp = ''\n\n return jsonify(resp)\n\n\n\n" }, { "alpha_fraction": 0.5931642651557922, "alphanum_fraction": 0.6030871272087097, "avg_line_length": 29.233333587646484, "blob_id": "481859a4f0569b2a19459281ab3b53c2fa34e6f9", "content_id": "1fafd004167960454208a663387acb3d6eeb0657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/args.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "from example_argparser import parser1, simple_math\nfrom example_argparser import parser_cycler, cycler\nfrom example_argparser import parser_wrapper, wrapper\n\nfrom collections import namedtuple\n\nParser = namedtuple('CLI', ('name', 'parser', 'function'))\n\n\nparsers = [Parser(name=parser1.prog,\n parser=parser1,\n function=simple_math),\n Parser(name=parser_cycler.prog,\n parser=parser_cycler,\n function=cycler),\n Parser(name=parser_wrapper.prog,\n parser=parser_wrapper,\n function=wrapper)\n ]\n\n\ndef get_cli(cmd):\n cmds = [parser for parser in parsers if parser.name == cmd]\n\n if len(cmds) == 0:\n return False, None\n if len(cmds) > 1:\n return False, (500, \"more than one parser with prog name '{}' found \".format(cmd))\n cli = cmds[0]\n return True, cli\n" }, { "alpha_fraction": 0.6125461459159851, "alphanum_fraction": 0.6134686470031738, "avg_line_length": 39.14814758300781, "blob_id": "154b63dc57ea3ec823ed04c3df3a9e37c5d9b881", "content_id": "eb6e2c23a1cef67b5a8298649634485c0416a105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 116, "num_lines": 27, "path": "/argparse2dict.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import argparse\nfrom collections import OrderedDict\n\n\ndef argparser_to_dict(parser):\n \"\"\"\n Converts an ArgumentParser from the argparse module to a dictionary\n :param parser: ArgumentParser, argparser which should be converted to a dictionary\n :return: dict, key: argparser.dest, value: dict with key: argparse.attribute and value: argparse.attribute_value\n \"\"\"\n\n args = [a for a in parser._actions if type(a) not in (argparse._HelpAction, argparse._VersionAction)]\n arg_dict = OrderedDict()\n\n for arg in args:\n arg_dict[arg.dest] = {k: arg.__getattribute__(k) for k in dir(arg)\n if (not k.startswith('_') and k not in ('container', ))}\n type_ = arg_dict[arg.dest].get('type')\n if type_ is not None:\n type_ = str(type_)\n if type_.startswith('<class') and \"'\" in type_:\n arg_dict[arg.dest]['type'] = type_.split(\"'\")[1]\n default = arg_dict[arg.dest].get('default', False)\n if default is None:\n del arg_dict[arg.dest]['default']\n\n return arg_dict\n" }, { "alpha_fraction": 0.6535087823867798, "alphanum_fraction": 0.7149122953414917, "avg_line_length": 21.799999237060547, "blob_id": "efddf1e11e4ab9b7fb004c9d1e9609e141324a87", "content_id": "265d2095ea86336532f2e8d1b1de92f1347116cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/config.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import os\n\nCELERY_BROKER_URL = 'redis://localhost:6379/0'\nRESULT_BACKEND = 'redis://localhost:6379/0'\nUSE_CELERY = False\nSERVER_PORT = 5000\n\nJOB_FOLDER = os.path.join(os.getcwd(), 'jobs')\n\nos.makedirs(JOB_FOLDER, exist_ok=True)\n" }, { "alpha_fraction": 0.656897246837616, "alphanum_fraction": 0.6600234508514404, "avg_line_length": 30.592592239379883, "blob_id": "18872f437b1348f741d2b8d7eca36772705b2625", "content_id": "d6342a4b24d446f684d56c3a4bc60d51efc05f7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2559, "license_type": "no_license", "max_line_length": 99, "num_lines": 81, "path": "/server.py", "repo_name": "Ashafix/argparse2HTML", "src_encoding": "UTF-8", "text": "import os\nfrom collections import OrderedDict\nimport importlib\nimport socket\nfrom flask import Flask, request, url_for, redirect\nimport jinja2\n\nimport args\nfrom argparse2dict import argparser_to_dict\nfrom config import CELERY_BROKER_URL, RESULT_BACKEND, USE_CELERY, SERVER_PORT\n\napp = Flask(__name__)\n\nif USE_CELERY:\n from blueprints.celery_task import app_with_celery\n app.config['CELERY_BROKER_URL'] = CELERY_BROKER_URL\n app.config['result_backend'] = RESULT_BACKEND\n\n app.config['task_track_started'] = True\n app.config['worker_redirect_stdouts'] = False\n app.config['worker_hijack_root_logger'] = False\n app.register_blueprint(app_with_celery)\n\nelse:\n from blueprints.subprocess_task import app_with_subprocess\n app.register_blueprint(app_with_subprocess)\n\n\nTEMPLATE_FOLDER = './templates'\nTEMPLATE_FILE = \"default_template.html\"\n\nSERVER_NAME = socket.gethostbyname(socket.gethostname())\n\n\ntemplate_loader = jinja2.FileSystemLoader(searchpath=TEMPLATE_FOLDER)\ntemplate_env = jinja2.Environment(loader=template_loader)\n\n\[email protected]('/')\ndef show_command_line_options():\n cmd = request.args.get('command')\n\n found, cli = args.get_cli(cmd)\n if not found:\n return redirect(url_for('list_available_commands'))\n parser = cli.parser\n\n if os.path.isfile(os.path.join(TEMPLATE_FOLDER, '{}.html'.format(cmd))):\n template_file = '{}.html'.format(cmd)\n else:\n template_file = TEMPLATE_FILE\n template = template_env.get_template(template_file)\n server = 'http://{}:{}/run/{}'.format(SERVER_NAME, SERVER_PORT, cmd)\n\n return template.render(title=cli.name,\n description=cli.parser.description,\n args=argparser_to_dict(parser),\n server=server,\n css_url=url_for('static', filename='css/main.css'))\n\n\[email protected]('/list')\ndef list_available_commands():\n template = template_env.get_template('list_commands.html')\n cmds = {parser.name: 'http://{}:{}/?command={}'.format(SERVER_NAME, SERVER_PORT,\n parser.name) for parser in args.parsers}\n cmds_sorted = OrderedDict()\n for cmd in sorted(cmds.keys()):\n cmds_sorted[cmd] = cmds[cmd]\n\n return template.render(args=cmds_sorted, css_url=url_for('static', filename='css/main.css'))\n\n\[email protected]('/refresh')\ndef refresh():\n importlib.reload(args)\n return 'refreshed argparsers'\n\n\nif __name__ == '__main__':\n app.run(threaded=True, host='0.0.0.0', port=SERVER_PORT)\n" } ]
8
severinson/cli-passthrough
https://github.com/severinson/cli-passthrough
fe8ca92f0d35e372ac5beae39aaf00c60b9484cd
5b5e7d65188b5aec746b7a208a6ef5d6fda4796d
7bdd4a58dc0217c5253bc53f8f4a28ac73750164
refs/heads/master
2022-10-26T18:57:47.235491
2020-06-14T11:58:15
2020-06-14T11:58:15
271,258,309
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5729281902313232, "alphanum_fraction": 0.5756906270980835, "avg_line_length": 30.75438690185547, "blob_id": "55259b92077af6deef8b913826eefedfb2f5f183", "content_id": "c86f8773de388da5dff70ee1ce79eddfd597ff97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1810, "license_type": "no_license", "max_line_length": 93, "num_lines": 57, "path": "/passthrough.py", "repo_name": "severinson/cli-passthrough", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Script for logging stdin/stdout of a separate process. Useful to\n# monitor an application that is automated via its CLI. Runs the\n# argument(s) given to this script as a separate process, while\n# passing stdin and stdout through and writing them to files.\n\nimport os\nimport sys\nimport subprocess\n\n# command to run\ncmd = \"./echo.py\"\n\nr_in, w_in = os.pipe()\nr_out, w_out = os.pipe()\nprocessid = os.fork()\nif processid: # process responsible for logging\n processid = os.fork()\n if processid: # process responsible for stdin\n w_in = os.fdopen(w_in, \"w\")\n stdin_file = open(cmd + \" \" + \" \".join(sys.argv[1:]) + \" stdin.txt\", \"w\")\n for line in sys.stdin:\n line = line.strip()\n print(line, file=stdin_file) # write to file\n print(line, file=w_in) # write to subprocess\n w_in.flush()\n stdin_file.flush()\n os.close(r_in)\n os.close(w_in)\n os.close(r_out)\n os.close(w_out)\n stdin_file.close()\n sys.exit(0)\n else:\n r_out = os.fdopen(r_out)\n stdout_file = open(cmd + \" \" + \" \".join(sys.argv[1:]) + \" stdout.txt\", \"w\")\n for line in r_out:\n line = line.strip()\n print(line, file=sys.stdout) # write to stdout\n print(line, file=stdout_file) # write to file\n sys.stdout.flush()\n stdout_file.flush()\n os.close(r_in)\n os.close(w_in)\n os.close(r_out)\n os.close(w_out)\n stdout_file.close()\n sys.stdout.close()\n sys.exit()\nelse: # process responsible for running cmd\n subprocess.run([cmd] + sys.argv[1:], stdin=os.fdopen(r_in), stdout=os.fdopen(w_out, \"w\"))\n os.close(r_in)\n os.close(w_in)\n os.close(r_out)\n os.close(w_out)\n sys.exit()\n" }, { "alpha_fraction": 0.7628865838050842, "alphanum_fraction": 0.7628865838050842, "avg_line_length": 34.272727966308594, "blob_id": "c8406a132e9fb8846629c0a655ac03fcf99f6a49", "content_id": "654eaa63c872346bd48a23d9986178161903ed63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 776, "license_type": "no_license", "max_line_length": 104, "num_lines": 22, "path": "/README.md", "repo_name": "severinson/cli-passthrough", "src_encoding": "UTF-8", "text": "# cli-passthrough\n\nScript for logging stdin/stdout of a separate process. Useful to\nmonitor an application that is automated via its CLI. Runs the\nargument(s) given to this script as a separate process, while passing\nstdin and stdout through and writing them to files.\n\nA simple echo script (`echo.py`) is included to showcase the\n`passthrough.py` script. Change the `cmd` global variable in\n`passthrough.py` to run another command.\n\n## Example\n```\n./passthrough.py foobar # run echo.py with argument foobar through passthrough.py\n\n# in a second terminal:\ntail -f tail -f echo.py\\ foobar\\ stdin.txt\n\n# in a third terminal:\ntail -f tail -f echo.py\\ foobar\\ stdout.txt\n```\nAs you write text into the first terminal window you should see it logged to the stdin and stdout files.\n" }, { "alpha_fraction": 0.5916954874992371, "alphanum_fraction": 0.5951557159423828, "avg_line_length": 21.230770111083984, "blob_id": "89927be2bc1958be6c84623a6b73d085de77b47f", "content_id": "4513fb705d888dbd9c586b812fff90771eebe9a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/echo.py", "repo_name": "severinson/cli-passthrough", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# Echo input on stdin to stdout\n\nimport sys\n\ndef main():\n print(\"echo started with arguments\", \" \".join(sys.argv))\n for line in sys.stdin:\n print(\"echo \" + line.strip(), file=sys.stdout)\n sys.stdout.flush()\n\nif __name__ == '__main__':\n main()\n" } ]
3
rohitChan/ifacWC2020
https://github.com/rohitChan/ifacWC2020
53da9377a535655831133a57351770f2d58f7bd8
fff964578b77926d2ac9229709b5ddf1f7fd7227
c70047f0bcf3f82a65d8ba5c50e5bdc4c1a887b5
refs/heads/master
2020-03-28T19:19:14.743435
2019-11-18T16:31:20
2019-11-18T16:31:20
148,964,795
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6177105903625488, "alphanum_fraction": 0.6349892020225525, "avg_line_length": 17.559999465942383, "blob_id": "6693dbc8ece649f6eb7d9a376a9cdb46a1360a15", "content_id": "6561d71ae8108e56feb61807409f23a59efef77d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 463, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/dq_robotics/src/test/test_graph.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <vector>\n#include <vector>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/baxter_poseControl_server.h>\n#include \"dq_robotics/graph.cpp\"\nusing namespace std;\n\nint main(int argc,char **argv) \n{\n ros::init(argc, argv, \"graph_test\");\n ros::NodeHandle n;\n\tplot p;\n\tfor(int a=0;a<100;a++) {\n\t\tvector<float> x,y;\n\t\tfor(int k=a;k<a+200;k++) {\n\t\t\tx.push_back(k);\n\t\t\ty.push_back(k*k);\n\t\t}\n\t\tp.plot_data(x,y);\n\t}\n\twhile(true)\n\t{}\n\treturn 0;\n}" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7800095677375793, "avg_line_length": 45.488887786865234, "blob_id": "38f4138488171fb0b27ef221c70fa45323fb4a81", "content_id": "560cdf84162a98b14ebe66a20a83e62659c4ff31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2091, "license_type": "no_license", "max_line_length": 333, "num_lines": 45, "path": "/dq_robotics/include/dq_robotics/manipulation_task_controller.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#ifndef MANIPULATION_TASK_CONTROLLER_H\n#define MANIPULATION_TASK_CONTROLLER_H\n\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/baxter_poseControl_server.h>\n#include <visualization_msgs/Marker.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <boost/thread.hpp>\n#include \"tf/transform_datatypes.h\"\n#include <tf_conversions/tf_eigen.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <dq_robotics/ControllerPerformance.h>\n#include <ar10_local/ar10_joint_cmds.h>\n\nusing namespace Eigen;\n\nclass ManipulationTaskController\n{\nprivate:\n\tdq_robotics::BaxterControl srv;\n\tros::NodeHandle nh;\n\tros::ServiceClient pose_control_client;\n\tros::Publisher controller_error_publisher, hand_cmds_publisher;\n\tstd::string right_object_name, right_ref_frame, left_object_name, left_ref_frame; \n\tar10_local::ar10_joint_cmds hand_cmds_msg;\n\t// boost::thread thr;\n\tvoid publishPose2Rviz(float rate, Matrix<double,8,1> pose, std::string ref_frame);\npublic:\n\tros::Publisher rviz_pub;\n\t// boost::thread* thr;\n\tbool ToPreGraspToGrasp(Matrix<double,8,1> grasp_location, std::string reference_frame, double distance, RowVectorXd approach_direction, int controller_mode, bool use_velocity_control);\n\tbool go2Pose_withPrecision(Matrix<double,8,1> pose_desired_abs, Matrix<double,8,1> pose_desired_rel, double error_threshold, int controller_mode, bool use_velocity_control);\n\tbool go2Pose_constVelocity(Matrix<double,8,1> pose_desired_abs , Matrix<double,8,1> pose_desired_rel, int controller_mode, int total_time, bool use_velocity_control);\n\tbool doRotationOrTranslation(bool rotation, Matrix<double,8,1> initial_pose, RowVectorXd axis, double initial_vm_jp, double final_vm_jp, double vm_velocity, int controller_mode, bool use_velocity_control, Matrix<double,8,1> pose_right, Matrix<double,8,1> pose_relative, bool vm_relative, Matrix<double,8,1>& final_pose_commanded);\t\n\tvoid init_task_controller();\n\tbool bimanual_pouringTask();\n\tvoid getHTMfromTFTransform(Matrix4d &htm, tf::StampedTransform transform);\n\tManipulationTaskController();\n\t~ManipulationTaskController();\n};\n\n#endif" }, { "alpha_fraction": 0.5573164820671082, "alphanum_fraction": 0.6688381433486938, "avg_line_length": 54.5945930480957, "blob_id": "3c09cd4c5a6608211156f594ae7a3309e6866adc", "content_id": "737749a8f2ba652f2a118def903354d882b132e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10285, "license_type": "no_license", "max_line_length": 301, "num_lines": 185, "path": "/dq_robotics/src/baxter_setJointToZero.py", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Copyright (c) 2013-2015, Rethink Robotics\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of the Rethink Robotics nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nBaxter RSDK Joint Position Example: file playback\n\"\"\"\n\nimport argparse\nimport sys\nimport rospy\nimport baxter_interface\nimport numpy\nfrom sensor_msgs.msg import JointState\nfrom baxter_interface import CHECK_VERSION\nfrom baxter_trajectory_interface.srv import *\n\n\ndef setJointPositions(joint_name_right, joint_name_left, joint_desired_pose_right, joint_desired_pose_left):\n left = baxter_interface.Limb('left')\n right = baxter_interface.Limb('right')\n\n rate = rospy.Rate(1000)\n\n position_right={\n joint_name_right[0]: joint_desired_pose_right[0],\n joint_name_right[1]: joint_desired_pose_right[1],\n joint_name_right[2]: joint_desired_pose_right[2],\n joint_name_right[3]: joint_desired_pose_right[3],\n joint_name_right[4]: joint_desired_pose_right[4],\n joint_name_right[5]: joint_desired_pose_right[5],\n joint_name_right[6]: joint_desired_pose_right[6]\n }\n\n position_left={\n joint_name_left[0]: joint_desired_pose_left[0],\n joint_name_left[1]: joint_desired_pose_left[1],\n joint_name_left[2]: joint_desired_pose_left[2],\n joint_name_left[3]: joint_desired_pose_left[3],\n joint_name_left[4]: joint_desired_pose_left[4],\n joint_name_left[5]: joint_desired_pose_left[5],\n joint_name_left[6]: joint_desired_pose_left[6]\n }\n \n left.move_to_joint_positions(position_left)\n right.move_to_joint_positions(position_right) \n left.set_joint_positions(position_left)\n rate.sleep()\n right.set_joint_positions(position_right)\n rate.sleep()\n return;\n\ndef getCurrentJointState(joint_name_right, joint_name_left):\n current_joint_states=rospy.wait_for_message(\"/robot/joint_states\", JointState) \n joint_states_right=[0, 0, 0, 0, 0, 0, 0]\n joint_states_left=[0, 0, 0, 0, 0, 0, 0]\n for i in range(len(joint_name_right)):\n for j in range(len(current_joint_states.name)):\n if current_joint_states.name[j]==joint_name_right[i]:\n joint_states_right[i]=current_joint_states.position[j]\n for i in range(len(joint_name_left)):\n for j in range(len(current_joint_states.name)):\n if current_joint_states.name[j]==joint_name_left[i]:\n joint_states_left[i]=current_joint_states.position[j]\n print joint_states_right\n print joint_states_left\n return (joint_states_right, joint_states_left);\n \ndef printSetPositionResult(joint_desired_state_right, joint_states_current_right, joint_desired_state_left, joint_states_current_left, joint_name_right, joint_name_left):\n error=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n error_joint_right=[0, 0, 0, 0, 0, 0, 0]\n error_joint_left=[0, 0, 0, 0, 0, 0, 0]\n for x in range(len(joint_states_current_right)):\n error_joint_right[x]=(joint_states_current_right[x]-joint_desired_state_right[x])\n if (abs(error_joint_right[x])>0.05):\n print \"Target for\", joint_name_right[x],\"not achieved\"\n for x in range(len(joint_states_current_left)):\n error_joint_left[x]=(joint_states_current_left[x]-joint_desired_state_left[x])\n if (abs(error_joint_left[x])>0.05):\n print \"Target for\", joint_name_left[x],\"not achieved\"\n error_joint_right= error_joint_right[::-1]\n error_joint_left=error_joint_left[::-1] \n error=numpy.concatenate((error_joint_right,error_joint_left),axis=0)\n print error\n return error\n\ndef set_joint_positions_server():\n s = rospy.Service('set_joint_position_gazebo', SetJointGoals, setClientJointPosition)\n print \"Ready to set joint positions...\"\n rospy.spin() \n\ndef setClientJointPosition(req):\n joint_name_right=[\"right_s0\", \"right_s1\", \"right_e0\", \"right_e1\", \"right_w0\", \"right_w1\", \"right_w2\"]\n #left_e1 is special. joint limit [-0.05] is the reason. keeping it zero for now \n joint_name_left=[\"left_s0\", \"left_s1\", \"left_e0\", \"left_e1\", \"left_w0\", \"left_w1\", \"left_w2\"]\n joint_desired_state_right=req.desiredJointGoals.position[0:7]\n joint_desired_state_right=joint_desired_state_right[::-1]\n joint_desired_state_right=[ -x for x in joint_desired_state_right]\n joint_desired_state_left=req.desiredJointGoals.position[7:14]\n # joint_desired_state_left=[ -x for x in mylist]\n setJointPositions(joint_name_right, joint_name_left, joint_desired_state_right, joint_desired_state_left)\n joint_states_current_right, joint_states_current_left=getCurrentJointState(joint_name_right, joint_name_left)\n error=printSetPositionResult(joint_desired_state_right, joint_states_current_right, joint_desired_state_left, joint_states_current_left, joint_name_right, joint_name_left)\n response=SetJointPositionResponse()\n response.error=error\n return response\n\ndef main():\n print(\"Initializing node... \")\n rospy.init_node(\"set_joint_positions\")\n#################Resposible for setting joint positions for Baxter ############################################ \n print(\"Getting robot state... \")\n rs = baxter_interface.RobotEnable(CHECK_VERSION)\n init_state = rs.state().enabled\n\n def clean_shutdown():\n print(\"\\nExiting example...\")\n if not init_state:\n print(\"Disabling robot...\")\n rs.disable()\n\n print(\"Enabling robot... \")\n rs.enable()\n #right_e1 is special. joint limit [-0.05] is the reason. keeping it zero for now \n\n #left_e1 is special. joint limit [-0.05] is the reason. keeping it zero for now \n # joint_name_left=[\"left_s0\", \"left_s1\", \"left_e0\", \"left_e1\", \"left_w0\", \"left_w1\", \"left_w2\"]\n # joint_name_right=[\"right_e0\", \"right_e1\", \"right_s0\", \"right_s1\", \"right_w0\", \"right_w1\", \"right_w2\"]\n\n ################################################################################################################### \n # joint_name_left=[\"left_e0\", \"left_e1\", \"left_s0\", \"left_s1\", \"left_w0\", \"left_w1\", \"left_w2\"]\n\n # joint_desired_state_right=[0.7410703227630888, 1.5362719506658014, 0.01001108907777759, -0.7006024655803085, 0.9735489859081357, 1.447864944629445, -0.4520477771263609]\n # joint_desired_state_left=[-0.02477285952504804, 1.5454976873355646, -0.34985937977411385, -0.862626895167157, -1.3115418478918244, 1.8487306917056667, -0.892602931497076] \n ###################################################################################################################\n joint_name_left = ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2']\n joint_desired_state_left= [0.041363752507206364, 1.9348352917089535, -0.2726798000286923, -0.5658538514940457, -1.1000522708348006, 1.7430249026235884, -0.1936378991920895]\n joint_name_right = ['right_e0', 'right_e1', 'right_s0', 'right_s1', 'right_w0', 'right_w1', 'right_w2']\n joint_desired_state_right = [0.6068619915741271, 1.911764079997937, -0.13185736132604742, -0.4816721820621366, 0.790763174233601, 1.304727973182544, -1.0247054998116605]\n\n \n joint_name_left = ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2']\n joint_desired_state_left= [0.4345000581685434, 1.4078108680818384, -1.117505003974524, -0.8383205005793786, -0.35128160042575973, 1.0530778108833365, 0.20401944478876002]\n joint_name_right = ['right_e0', 'right_e1', 'right_s0', 'right_s1', 'right_w0', 'right_w1', 'right_w2']\n joint_desired_state_right = [-0.33824276372873374, 1.5082866096883332, 1.035053536625683, -0.9276748814737039, 0.25080585881926515, 1.0895098545956152, -0.07209709703061444]\n setJointPositions(joint_name_right, joint_name_left, joint_desired_state_right, joint_desired_state_left)\n######################################################################################################################\n#################Resposible for getting joint positions for Baxter from /robot/joint_states topic ############################################ \n\n joint_states_current_right, joint_states_current_left=getCurrentJointState(joint_name_right, joint_name_left) \n printSetPositionResult(joint_desired_state_right, joint_states_current_right, joint_desired_state_left, joint_states_current_left,joint_name_right, joint_name_left)\n\n # set_joint_positions_server()\n\nif __name__ == '__main__':\n main()\n \n\n# name: ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2', 'right_e0', 'right_e1', 'right_s0', 'right_s1', 'right_w0', 'right_w1', 'right_w2']\n# position: [0.4345000581685434, 1.4078108680818384, -1.117505003974524, -0.8383205005793786, -0.35128160042575973, 1.0530778108833365, 0.20401944478876002, -0.33824276372873374, 1.5082866096883332, 1.035053536625683, -0.9276748814737039, 0.25080585881926515, 1.0895098545956152, -0.07209709703061444]\n" }, { "alpha_fraction": 0.5848917961120605, "alphanum_fraction": 0.6285295486450195, "avg_line_length": 65.53658294677734, "blob_id": "cd5a3f37428f36b567e4273db1d9f6508d404bac", "content_id": "5b4a4e1e4a03441346a7e9427aebc2b32347ac50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2727, "license_type": "no_license", "max_line_length": 128, "num_lines": 41, "path": "/dq_robotics/config/acc_control_params.cfg", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nPACKAGE = \"dq_robotics\"\nimport math\nmath.pi\nfrom dynamic_reconfigure.parameter_generator_catkin import *\n\ngen = ParameterGenerator()\n\ngen.add(\"start_controller\", bool_t, 0, \"start control\", False)\ngen.add(\"regulation_control\", bool_t, 0, \"regulation_control\", False)\ngen.add(\"traj_control\", bool_t, 0, \"traj_control\", False)\ngen.add(\"reset_robot\", bool_t, 0, \"reset_robot\", False)\ngen.add(\"redundancy_resol_active\", bool_t, 0, \"redundancy_resol_active\", False)\ngen.add(\"accCntrl_K_JntLmt\", double_t, 0, \"proportional gain for K_JntLmt\", 1, 0, 200)\ngen.add(\"accCntrl_K_pP\", double_t, 0, \"proportional gain for position\", 250, 0, 600)\ngen.add(\"accCntrl_K_pO\", double_t, 0, \"proportional gain for orientation\", 250, 0, 600)\ngen.add(\"accCntrl_K_dP\", double_t, 0, \"derivative gain for position\", 150, 0, 400)\ngen.add(\"accCntrl_K_dO\", double_t, 0, \"derivative gain for orientation\", 150, 0, 400)\ngen.add(\"accCntrl_total_time\", double_t, 0, \"simulation time\", 10, 0, 200)\ngen.add(\"accCntrl_frequency\", double_t, 0, \"desired frequecy of controller\", 1000, 0, 2000)\ngen.add(\"accCntrl_theta_init\", double_t, 0, \"theta_init for rotation task\", 0, 0, math.pi)\ngen.add(\"accCntrl_theta_final\", double_t, 0, \"theta_final for rotation task\", math.pi/2, 0, math.pi)\ngen.add(\"accCntrl_traj_pitch\", double_t, 0, \"pitch for rotation task\", 0, -1, 1)\ngen.add(\"reg_x\", double_t, 0, \"change in x for regulation\", 0, -1, 1)\ngen.add(\"reg_y\", double_t, 0, \"change in y for regulation\", 0, -1, 1)\ngen.add(\"reg_z\", double_t, 0, \"change in z for regulation\", 0, -1, 1)\ngen.add(\"reg_theta_x\", double_t, 0, \"change in theta_x for regulation\", 0, -1.57, 1.57)\ngen.add(\"reg_theta_y\", double_t, 0, \"change in theta_y for regulation\", 0, -1.57, 1.57)\ngen.add(\"reg_theta_z\", double_t, 0, \"change in theta_z for regulation\", 0, -1.57, 1.57)\n# gen.add(\"double_param\", double_t, 0, \"A double parameter\", .5, 0, 1)\n# gen.add(\"str_param\", str_t, 0, \"A string parameter\", \"Hello World\")\n# gen.add(\"bool_param\", bool_t, 0, \"A Boolean parameter\", True)\n\nsize_enum = gen.enum([ gen.const(\"dq_controller\", int_t, 0, \"dq_controller based on screw\"),\n gen.const(\"kdl_controller_quat\", int_t, 1, \"kdl_controller based on quaternion\"),\n gen.const(\"kdl_controller_quatVec\", int_t, 2, \"kdl_controller based on vector part of quaternion\")],\n \"Controller Selection\")\n\ngen.add(\"controller_type\", int_t, 0, \"Controller Selection\", 0, 0, 2, edit_method=size_enum)\n\nexit(gen.generate(PACKAGE, \"dq_robotics\", \"kdl_controller\"))" }, { "alpha_fraction": 0.6353560090065002, "alphanum_fraction": 0.6464869379997253, "avg_line_length": 31.311077117919922, "blob_id": "95f5aebfed82e12c0c1c4b5549357d3002744234", "content_id": "8a0ec512f28e4b0b833e28d341bbdacb33c1cf98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 21292, "license_type": "no_license", "max_line_length": 417, "num_lines": 659, "path": "/dq_robotics/include/dq_robotics/baxter_dq.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_dq.h>\n\nusing namespace Eigen;\n\nManipulatorModDQ::ManipulatorModDQ(){}\nManipulatorModDQ::~ManipulatorModDQ(){}\n\n\nbool ManipulatorModDQ::initialize_baxter()\n{\n\tbool initialized=false;\n\tif(ManipulatorModDQ::getRobotParams_baxter())\n\t\tif(ManipulatorModDQ::loadModel_baxter())\n\t\t\tinitialized=true;\n\t\telse\n\t\t\tROS_ERROR(\"Robot model not loaded\");\n\telse\n\t\tROS_INFO(\"Robot params not loaded\");\n\t\n\tROS_INFO(\"Robot params loaded\");\n\tleft_cmd_pub = rh.advertise<baxter_core_msgs::JointCommand>(\"/robot/limb/left/joint_command\", 10);\n\tright_cmd_pub = rh.advertise<baxter_core_msgs::JointCommand>(\"/robot/limb/right/joint_command\", 10);\n\t\n\tManipulatorModDQ::mapJointName2JointCmds();\n\tcmd_left.mode = baxter_core_msgs::JointCommand::VELOCITY_MODE;\n\tcmd_right.mode = baxter_core_msgs::JointCommand::VELOCITY_MODE;\n\n\t// const sensor_msgs::JointStateConstPtr jointState = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/robot/joint_states\");\n\t// current_time=jointState->header.stamp;\n\tstd::cout << \"joint_size_baxter: \" << joint_size_baxter << std::endl;\n\tq_baxter= RowVectorXd::Zero(joint_size_baxter);\n\tq_vel_baxter= RowVectorXd::Zero(joint_size_baxter);\n\t// std::cout << \"q:\" << std::endl;\n\t// for (int i=0; i<jointState->name.size(); i++)\n\t// {\n\t// \tfor(int j=0; j< joint_size_baxter; j++)\n\t// \t{\n\t// \t\tif (!jointState->name[i].compare(joint_names_baxter[j]) )\n\t// \t\t{\n\t// \t\t\tq_baxter[j]=jointState->position[i];\t\t\n\t// \t\t\t// std::cout << q[j] << std::endl;\t\t\n\t// \t\t\tq_vel_baxter[j]=jointState->velocity[i];\t\t\t\t\n\t// \t\t}\n\t// \t}\t\n\t// }\n\t// q_baxter= RowVectorXd::Zero(joint_size_baxter);\n\t// q_vel_baxter= RowVectorXd::Zero(joint_size_baxter);\n\tjoint_state_sub= rh.subscribe(\"/robot/joint_states\", 1, &ManipulatorModDQ::joint_state_callback, this, ros::TransportHints().tcpNoDelay(true)); \t\n\treturn initialized;\n}\n\n\nvoid ManipulatorModDQ::joint_state_callback(const sensor_msgs::JointState& jointStateConsPtr)\n{\n\t// std::cout << \"did it come here for call back after spinOnce!\" << std::endl;\n\tcurrent_time=jointStateConsPtr.header.stamp;\n\tq_baxter= RowVectorXd::Zero(joint_size_baxter);\n\tq_vel_baxter= RowVectorXd::Zero(joint_size_baxter);\n\t// std::cout << \"q:\" << std::endl;\n\tfor (int i=0; i<jointStateConsPtr.name.size(); i++)\n\t{\n\t\tfor(int j=0; j< joint_size_baxter; j++)\n\t\t{\n\t\t\tif (!jointStateConsPtr.name[i].compare(joint_names_baxter[j]) )\n\t\t\t{\n\t\t\t\tq_baxter[j]=jointStateConsPtr.position[i];\t\t\n\t\t\t\t// std::cout << q[j] << std::endl;\t\t\n\t\t\t\tq_vel_baxter[j]=jointStateConsPtr.velocity[i];\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid ManipulatorModDQ::mapJointName2JointCmds()\n{\n\tcmd_right.names.clear();\n\tcmd_left.names.clear();\n\n\tcmd_right.names.push_back(\"right_s0\");\n\tcmd_right.names.push_back(\"right_s1\");\n\tcmd_right.names.push_back(\"right_e0\");\n\tcmd_right.names.push_back(\"right_e1\");\n\tcmd_right.names.push_back(\"right_w0\");\n\tcmd_right.names.push_back(\"right_w1\");\n\tcmd_right.names.push_back(\"right_w2\");\n\n\tcmd_left.names.push_back(\"left_s0\");\n\tcmd_left.names.push_back(\"left_s1\");\n\tcmd_left.names.push_back(\"left_e0\");\n\tcmd_left.names.push_back(\"left_e1\");\n\tcmd_left.names.push_back(\"left_w0\");\n\tcmd_left.names.push_back(\"left_w1\");\n\tcmd_left.names.push_back(\"left_w2\");\n\n\tcmd_right.command.resize(cmd_right.names.size());\n\tcmd_left.command.resize(cmd_left.names.size()); \n}\n\nbool ManipulatorModDQ::getRobotParams_baxter()\n{\n\tjoint_size_baxter = 14;\n\t\n\tstd::string paramName=\"tip_name_left\";\n\t\n\tif(!ros::param::get(paramName, tip_name_left))\n\t{\n\t\tstd::cout << \"tip_name_left param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\tparamName=\"tip_name_right\";\n\tif(!ros::param::get(paramName, tip_name_right))\n\t{\n\t\tstd::cout << \"tip_name_right param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"root_name\";\n\tif(!ros::param::get(paramName, root_name))\n\t{\n\t\tstd::cout << \"root_name param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"joint_type\" ;\n\tjoint_type_baxter.resize(joint_size_baxter);\n\tif(!ros::param::get(paramName, joint_type_baxter))\n\t{\n\t\tstd::cout << \"joint_type param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"fraction_jointLimit\";\n\tif(!ros::param::get(paramName, fraction_jointLimit))\n\t{\n\t\tstd::cout << \"fraction_jointLimit param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\n\tRowVector3d u_i, p_i;\n\tp_baxter.clear();\n\tu_baxter.clear();\n\n\tstd::string pName=\"p\";\n\tstd::string uName=\"u\";\n\tstd::vector<double> value;\t\n\tvalue.clear();\n\tvalue.resize(3);\n\n\tfor(int i=0;i<joint_size_baxter;i++)\n\t{\n\t\tparamName=pName + std::to_string(i);\n\t\tvalue.clear();\n\t\tvalue.resize(3);\n\t\tif(ros::param::get(paramName, value))\n\t\t{\n\t\t\tp_i << value[0], value[1], value[2] ;\n\t\t\tp_baxter.push_back(p_i);\n\t\t}\t\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"p_%d param not found \" << i << std::endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tparamName=uName + std::to_string(i);\n\t\tvalue.clear();\n\t\tvalue.resize(3);\n\t\tif(ros::param::get(paramName, value))\n\t\t{\n\t\t\tu_i << value[0], value[1], value[2] ;\n\t\t\tu_baxter.push_back(u_i);\n\t\t}\t\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"u_%d param not found \" << i << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\n\tparamName=\"joint_names\";\n\tjoint_names_baxter.resize(joint_size_baxter);\n\tif(!ros::param::get(paramName, joint_names_baxter))\n\t{\n\t\tstd::cout << \"joint_names param not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"pe_init_left\";\n\tvalue.clear();\n\tvalue.resize(8);\n\tif(ros::param::get(paramName, value))\n\t{\n\t\t\tpe_init_left <<value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7]; \n\t}\n\telse\n\t{\n\t\tstd::cout << \"pe_init_left param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\t\n\tparamName=\"pe_init_right\";\n\tvalue.clear();\n\tvalue.resize(8);\n\tif(ros::param::get(paramName, value))\n\t{\n\t\t\tpe_init_right <<value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7]; \n\t}\n\telse\n\t{\n\t\tstd::cout << \"pe_init_right param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tif (u_baxter.size()!=joint_size_baxter || p_baxter.size()!=joint_size_baxter)\n\t{\n\t\tstd::cerr << \"Size mismatch error for u and p.\" << std::endl;\n\t\tstd::cerr << \"u_size\"<< u.size()<< std::endl;\n\t\tstd::cerr << \"p_size\"<< p.size()<< std::endl;\n\t\tstd::cerr << \"joint_size_baxter\"<< joint_size_baxter<< std::endl;\n\t\treturn 0;\n\t}\n\tROS_INFO(\"Manipulators parameter loaded\");\n\treturn 1;\n}\n\nbool ManipulatorModDQ::loadModel_baxter()\n{\n urdf::Model robot_model;\n\tstd::vector<std::string> joint_names_new; joint_names_new.clear();\n\tstd::string urdf_xml, full_urdf_xml;\n\n\tvelocity_limit.clear();\n\tvelocity_limit_ordered_baxter.clear();\n\tjoint_low_limit.clear();\n\tjoint_high_limit.clear();\n\tjoint_low_limit_ordered_baxter.clear();\n\tjoint_high_limit_ordered_baxter.clear();\n\tjoint_mid_point_baxter.clear();\n\tmax_safe_baxter.resize(joint_size_baxter);\n\tmin_safe_baxter.resize(joint_size_baxter);\n\tjoint_mid_point_baxter.resize(joint_size_baxter);\n \n // fraction_jointLimit=0.1;\n\n rh.param(\"urdf_xml\",urdf_xml,std::string(\"robot_description\"));\n rh.searchParam(urdf_xml,full_urdf_xml);\n\t\n if (!rh.getParam(full_urdf_xml, xml)) {\n std::cout << \"Could not load the xml from parameter server:\" << urdf_xml << std::endl;\n return false;\n }\n if (!robot_model.initString(xml)) {\n ROS_WARN(\"Could not initialize robot model\");\n return -1;\n }\n\n if (!ManipulatorModDQ::readJoints_baxter(tip_name_left, joint_names_new, robot_model)) {\n ROS_WARN(\"Could not read information about the joints\");\n return false;\n }\n if (!ManipulatorModDQ::readJoints_baxter(tip_name_right, joint_names_new, robot_model)) {\n ROS_WARN(\"Could not read information about the joints\");\n return false;\n }\n\n\tfor (int i=0; i<joint_names_baxter.size(); i++)\n\t{\n\t\t// std::cout<< \"joint_name[\" << i << \"]:\"<< joint_names[i] << std::endl;\n\t\tfor(int j=0; j< joint_names_new.size(); j++)\n\t\t{\n\t\t\tif(joint_names_baxter[i].compare(joint_names_new[j]) == 0)\n\t\t\t{\n\t\t\t\tvelocity_limit_ordered_baxter.push_back(velocity_limit[j]);\n\t\t\t\tjoint_low_limit_ordered_baxter.push_back(joint_low_limit[j]);\n\t\t\t\tjoint_high_limit_ordered_baxter.push_back(joint_high_limit[j]);\n\t\t\t\tstd::cout << \"joint limit for \" << joint_names_baxter[i] << \": upper: \" << joint_high_limit_ordered_baxter[i] << \": lower: \" << joint_low_limit_ordered_baxter[i] << std::endl;\n\t\t\t\tstd::cout << \"velocity limit for \" << joint_names_baxter[i] << \": \" << velocity_limit_ordered_baxter[i] << std::endl;\n\t\t\t}\n\t\t}\t\n\t}\n\tfor(int i=0; i <joint_size_baxter; i++)\n\t{\n\t\tmax_safe_baxter[i]=joint_high_limit_ordered_baxter[i]- (joint_high_limit_ordered_baxter[i]- joint_low_limit_ordered_baxter[i])*(fraction_jointLimit);\n\t\tmin_safe_baxter[i]=joint_low_limit_ordered_baxter[i] + (joint_high_limit_ordered_baxter[i]- joint_low_limit_ordered_baxter[i])*(fraction_jointLimit);\n\t\tjoint_mid_point_baxter[i]=(max_safe_baxter[i]+min_safe_baxter[i])/2;\n\t\tstd::cout << \"joint_\" << i << \" ::max_safe: \" << max_safe_baxter[i] << \"::min_safe: \" << min_safe_baxter[i] << \"::joint_mid_point: \" << joint_mid_point_baxter[i] << std::endl;\n\t} \n return true;\n}\n\n\nbool ManipulatorModDQ::readJoints_baxter(std::string tip_name, std::vector<std::string> &joint_names_new, urdf::Model &robot_model) \n{\n\tboost::shared_ptr<const urdf::Link> link = robot_model.getLink(tip_name);\n\tboost::shared_ptr<const urdf::Joint> joint;\n\tint num_joints=0;\n\tint joint_index=0;\n\n\twhile (link && link->name != root_name) \n\t{\n\t\tjoint = robot_model.getJoint(link->parent_joint->name);\n\t\tif (!joint) \n\t\t{\n\t\t\tstd::cout << \"Could not find joint: \" << link->parent_joint->name << std::endl;\n\t\t\treturn false;\n\t\t}\n\t\tif (joint->type != urdf::Joint::UNKNOWN && joint->type != urdf::Joint::FIXED) \n\t\t{\n\t\t\tnum_joints++;\n\t\t}\n\t\tlink = robot_model.getLink(link->getParent()->name);\n\t}\n\tlink = robot_model.getLink(tip_name);\n\n\twhile (link && (joint_index < num_joints)) \n\t{\n\t\tjoint = robot_model.getJoint(link->parent_joint->name);\n\t\tif (joint->type != urdf::Joint::UNKNOWN && joint->type != urdf::Joint::FIXED) \n\t\t{\n\t\t\t// ROS_INFO( \"adding joint: [%s]\", joint->name.c_str() );\n\t\t\tjoint_names_new.push_back(joint->name);\n\t\t\tfloat lower, upper;\n\t\t\tint hasLimits;\n\t\t\tif ( joint->type != urdf::Joint::CONTINUOUS ) \n\t\t\t{\n\t\t\t\tvelocity_limit.push_back(joint->limits->velocity);\n\t\t\t\tlower = joint->limits->lower;\n\t\t\t\tupper = joint->limits->upper;\n\t\t\t\tjoint_low_limit.push_back(lower);\n\t\t\t\tjoint_high_limit.push_back(upper);\n\t\t\t\thasLimits = 1;\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\tlower = -M_PI;\n\t\t\t\tupper = M_PI;\n\t\t\t\thasLimits = 0;\n\t\t\t}\n\t\t\tjoint_index++;\n\t\t}\n\t\tlink = robot_model.getLink(link->getParent()->name);\n\t}\n\n\treturn true;\n}\n\nvoid ManipulatorModDQ::getCurrentJointState_baxter()\n{\n\t// std::cout << \"spinning for joint_state_callback\" << std::endl;\n\t// ros::WallTime waitForJointState_time_start = ros::WallTime::now();\n\t// ros::Rate r(100);\n\t// r.sleep();\n\tros::spinOnce();\n\t// r.sleep();\n\t// ros::Rate r(100);\n\t// std::cout << \"Here 13\" << std::endl;\n\n\t// const sensor_msgs::JointStateConstPtr jointState = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/robot/joint_states\");\n\t// current_time=jointState->header.stamp;\n\t// ros::WallTime waitForJointState_time_end = ros::WallTime::now();\n\t// ros::WallDuration waitForJointState_time_dur = waitForJointState_time_end - waitForJointState_time_start;\n\t// std::cout << \"waitForJointState duration_server: \" << waitForJointState_time_dur.toSec() << std::endl; \n\t// std::cout << \"joint_size_baxter: \" << joint_size_baxter << std::endl;\n\t// q_baxter= RowVectorXd::Zero(joint_size_baxter);\n\t// q_vel_baxter= RowVectorXd::Zero(joint_size_baxter);\n\t// // std::cout << \"q:\" << std::endl;\n\t// for (int i=0; i<jointState->name.size(); i++)\n\t// {\n\t// \tfor(int j=0; j< joint_size_baxter; j++)\n\t// \t{\n\t// \t\tif (!jointState->name[i].compare(joint_names_baxter[j]) )\n\t// \t\t{\n\t// \t\t\tq_baxter[j]=jointState->position[i];\t\t\n\t// \t\t\t// std::cout << q[j] << std::endl;\t\t\n\t// \t\t\tq_vel_baxter[j]=jointState->velocity[i];\t\t\t\t\n\t// \t\t}\n\t// \t}\n\t// }\n}\n\nvoid ManipulatorModDQ::currentRobotState(ros::Time &current_time_, RowVectorXd &q_, RowVectorXd &q_vel_)\n{\n\tcurrent_time_= this->current_time;\n\tq_=this->q_baxter;\n\tq_vel_=this->q_vel_baxter;\n}\n\nvoid ManipulatorModDQ::robotParams(std::vector<RowVector3d> &u_, std::vector<RowVector3d> &p_, Matrix<double,8,1> &pe_init_left_, Matrix<double,8,1> &pe_init_right_, std::vector<double> &joint_high_limit_, std::vector<double> &joint_low_limit_, std::vector<double> &velocity_limit_, std::vector<double> &max_safe_, std::vector<double> &min_safe_, std::vector<std::string> &joint_names_, std::vector<int> &joint_type_)\n{\t\n\tu_=this->u_baxter;\n\tp_=this->p_baxter;\n\tpe_init_left_= this->pe_init_left;\n\tpe_init_right_= this->pe_init_right;\n\tjoint_high_limit_=this->joint_high_limit_ordered_baxter;\n\tjoint_low_limit_=this->joint_low_limit_ordered_baxter;\n\tvelocity_limit_=this->velocity_limit_ordered_baxter;\n\tmax_safe_=this->max_safe_baxter;\n\tmin_safe_=this->min_safe_baxter;\n\tjoint_names_=this->joint_names_baxter;\n\tjoint_type_=this->joint_type_baxter;\n}\n\nvoid ManipulatorModDQ::sendJointCommandBaxter(std::vector<double> jointCmds_, int mode, double sleepTimeout_, bool velocity_control)\n{\n\tsleepTimeout=sleepTimeout_;\n\t// ROS_INFO(\"Hi sendCmd 1\");\n\tcmd_right.command.clear();\n\tcmd_left.command.clear();\n\n\tfor(int i = 0; i < 7; i++)\n\t{\n\t\t// ROS_INFO(\"Hi sendCmd 2, i=%d\", i);\n\t\tcmd_right.command.push_back(jointCmds_[i]);\n\t\tcmd_left.command.push_back(jointCmds_[7+i]);\n\t}\n\t// std::cout << \"jointCmds: \" << std::endl;\n\t// std::cout << \"jointCmds_for_mode_\" << mode << \": \"<< std::endl;\n\t// for(int i = 0; i < 14; i++)\n\t// {\n\t// \tstd::cout << jointCmds_[i] << \", \";\n\t// \t// std::cout << \"cmd_left.command[\" << i << \"]: \" << cmd_left.command[i] << std::endl;\n\t// }\n\tstd::cout << std::endl;\t \t\n\tif (left_cmd_pub.getNumSubscribers() && right_cmd_pub.getNumSubscribers())\t\n\t{\n\t\tif(!velocity_control)\n\t\t{\n\t\t\tcmd_left.mode = baxter_core_msgs::JointCommand::RAW_POSITION_MODE;\n\t\t\tcmd_right.mode = baxter_core_msgs::JointCommand::RAW_POSITION_MODE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcmd_left.mode = baxter_core_msgs::JointCommand::VELOCITY_MODE;\n\t\t\tcmd_right.mode = baxter_core_msgs::JointCommand::VELOCITY_MODE;\t\n\t\t}\n\t\tif (mode==1 || mode==3 || mode==4|| mode==5)\n\t\t right_cmd_pub.publish(cmd_right);\n\t\tif (mode==2 || mode==3 || mode==4|| mode==5)\t \n\t\t left_cmd_pub.publish(cmd_left);\n\t // ROS_INFO(\"Hi sendCmd 3\");\n\t ros::Duration(sleepTimeout).sleep();\t\t\n\t // ROS_INFO(\"Cmd Sent\");\n\t} \n\telse\n\t{\n\t\tROS_INFO(\"subscriber not found\");\n\t} \n}\n\n\n// void ManipulatorModDQ::fkmDual()\n// {\n// \tq_dual=RowVectorXd::Zero(joint_size*2);\n// \tfor (int j=0; j< joint_size; j++)\n// \t{\n// \t\tif(joint_type[j]==0)\n// \t\t\tq_dual(2*j)=q(j);\n// \t\telse\n// \t\t\tq_dual(2*j+1)=q(j);\n// \t}\n\t\t\n// \tfkm_current.clear();\n// \tfkm_current.resize(joint_size);\n\n// \tfor (int i=0;i<joint_size; i++)\n// \t{\n// \t\tdouble theta_i=q_dual[2*i];\n// \t\tRowVector3d u_i=u[i];\n// \t\tRowVector3d p_i=p[i];\n// \t\tdouble d_i=q_dual[2*i+1];\n// \t\tMatrix<double,8,1> screwDispalcementArray_i;\n// \t\tscrewDispalcementArray_i= DQoperations::screw2DQ(theta_i, u_i, d_i, p_i.cross(u_i));\n// \t\tif (i==0)\n// \t\t\tfkm_current[i]=screwDispalcementArray_i;\n// \t\telse\n// \t\t\tfkm_current[i]=DQoperations::mulDQ(fkm_current[i-1],screwDispalcementArray_i);\n// \t}\n\n// \tpe_now=fkm_current[joint_size-1];\n// pe_now=DQoperations::mulDQ(pe_now, pe_init);\n// }\n\n// void ManipulatorModDQ::jacobianDual()\n// {\n// \tjacobian=MatrixXd::Zero(6,joint_size);\n\t\n\n// \tMatrix<double,8,1> screwDispalcementArray_i, screw_axis_i, pose_i;\n\t\n// \tscrewDispalcementArray_i= fkm_current[joint_size-1];/*The numbering in C++ starts at 0*/\n\t\n// \tscrewDispalcementArray_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pe_init), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\n// \tRowVector3d pose_ee_now;\n\n// \tpose_ee_now << screwDispalcementArray_i(5), screwDispalcementArray_i(6), screwDispalcementArray_i(7); \n\n// \tif(joint_type[0]==0)\n// \t{\n// \t\tjacobian.col(0)<< (p[0].cross(u[0])).transpose(), u[0].transpose();/*writing Jacobian seperately for first joint for faster operation*/\n// \t}\n// \telse\n// \t{\n// \t\tjacobian.col(0)<< u[0].transpose(), 0, 0, 0;\n\t\t\n// \t}\n\n// \tfor(int i=1; i<joint_size; i++)\n// \t{\n\n// \t\tscrewDispalcementArray_i=fkm_current[i-1];\n\t\n// \t\tscrew_axis_i<< 0, u[i].transpose(), 0, (p[i].cross(u[i])).transpose();\n\t\n// \t\tscrew_axis_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, screw_axis_i), DQoperations::classicConjDQ(screwDispalcementArray_i));\t\n\t\n// \t\tRowVector3d u_i, p_i;\n// \t\tu_i << screw_axis_i(1), screw_axis_i(2), screw_axis_i(3);\n// \t\tpose_i << 1, 0, 0, 0, 0, p[i].transpose();\n// \t\tpose_i= DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_i), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n// \t\tp_i << pose_i(5), pose_i(6), pose_i(7);\n// \t\tif(joint_type[i]==0)\n// \t\t{\n// \t\t\tjacobian.col(i) << (p_i.cross(u_i)).transpose(), u_i.transpose(); \n// \t\t}\n// \t\telse\n// \t\t\tjacobian.col(i) << u_i.transpose(), 0, 0, 0;\n// \t}\n// \tManipulatorModDQ::jacobianDual_8d();\n// }\n\n// void ManipulatorModDQ::jacobianDual_8d()\n// {\n// \tjacobian_8d=MatrixXd::Zero(8,joint_size);\n// jacobian_8d.row(1)=jacobian.row(0);\n// \tjacobian_8d.row(2)=jacobian.row(1);\n// \tjacobian_8d.row(3)=jacobian.row(2);\n// \tjacobian_8d.row(5)=jacobian.row(3);\n// \tjacobian_8d.row(6)=jacobian.row(4);\n// \tjacobian_8d.row(7)=jacobian.row(5);\n// }\n\n\n// void ManipulatorModDQ::getDQderivative()\n// {\n// \tRowVector4d rot_q_from_dq, dual_part_dq, trans_q_from_dq, dq_dot_dual, rot_q_dot, v, w;\n// \tRowVectorXd velocity;\n\n// \tvelocity=jacobian*q_vel.transpose();\n\n// \tv << 0, velocity(0), velocity(1), velocity(2);\n// \tw << 0, velocity(3), velocity(4), velocity(5);\n\n// \trot_q_from_dq << pe_now(0), pe_now(1), pe_now(2), pe_now(3);\n// \tdual_part_dq << pe_now(4), pe_now(5), pe_now(6), pe_now(7);\n\n// \ttrans_q_from_dq = 2*DQoperations::multQuat(dual_part_dq, DQoperations::conjQuat(rot_q_from_dq));\n\n// \trot_q_dot=0.5*(DQoperations::multQuat(w, rot_q_from_dq));\n\n// \tdq_dot_dual=0.5*(DQoperations::multQuat(v, rot_q_from_dq) + DQoperations::multQuat(trans_q_from_dq, rot_q_dot));\n\n// \tpe_now_dot_dq << rot_q_dot(0), rot_q_dot(1), rot_q_dot(2), rot_q_dot(3), dq_dot_dual(0), dq_dot_dual(1), dq_dot_dual(2), dq_dot_dual(3);\n// }\n\n// void ManipulatorModDQ::initialize_leftArm()\n// {\n// \tp_left.clear();\n// \tu_left.clear();\n// \tjoint_type_left.clear();\n// \tjoint_names_left.clear();\n// \tvelocity_limit_ordered_left.clear();\n// \tjoint_size_left=7;\n// \tjoint_low_limit_ordered_left.clear();\n// \tjoint_high_limit_ordered_left.clear();\n// \tmax_safe_left.clear();\n// \tmin_safe_left.clear();\n// \tjoint_mid_point_left.clear();\n\n// \tfor (int i=0; i<joint_size_left; i++ )\n// \t{\n// \t\tp_left.push_back(p_baxter[7+i]);\n// \t\tu_left.push_back(u_baxter[7+i]);\n// \t\tjoint_type_left.push_back(joint_type_baxter[7+i]);\t\t\n// \t\tjoint_names_left.push_back(joint_names_baxter[7+i]);\t\t\n// \t\tvelocity_limit_ordered_left.push_back(velocity_limit_ordered_baxter[7+i]);\n// \t\tjoint_low_limit_ordered_left.push_back(joint_low_limit_ordered_baxter[7+i]);\n// \t\tjoint_high_limit_ordered_left.push_back(joint_high_limit_ordered_baxter[7+i]);\n// \t\tmax_safe_left.push_back(max_safe_baxter[7+i]);\n// \t\tmin_safe_left.push_back(min_safe_baxter[7+i]);\n// \t\tjoint_mid_point_left.push_back(joint_mid_point_baxter[7+i]);\n// \t}\n// }\n\n// void ManipulatorModDQ::initialize_rightArm()\n// {\n// \tp_right.clear();\n// \tu_right.clear();\n// \tjoint_type_right.clear();\n// \tjoint_names_right.clear();\n// \tvelocity_limit_ordered_right.clear();\n// \tjoint_size_right=7;\n// \tjoint_low_limit_ordered_right.clear();\n// \tjoint_high_limit_ordered_right.clear();\n// \tmax_safe_right.clear();\n// \tmin_safe_right.clear();\n// \tjoint_mid_point_right.clear();\n\n// \tfor (int i=0; i<joint_size_right; i++ )\n// \t{\n// \t\tp_right.push_back(p_baxter[i]);\n// \t\tu_right.push_back(u_baxter[i]);\n// \t\tjoint_type_right.push_back(joint_type_baxter[i]);\t\t\n// \t\tjoint_names_right.push_back(joint_names_baxter[i]);\t\t\n// \t\tvelocity_limit_ordered_right.push_back(velocity_limit_ordered_baxter[i]);\n// \t\tjoint_low_limit_ordered_right.push_back(joint_low_limit_ordered_baxter[i]);\n// \t\tjoint_high_limit_ordered_right.push_back(joint_high_limit_ordered_baxter[i]);\n// \t\tmax_safe_right.push_back(max_safe_baxter[i]);\n// \t\tmin_safe_right.push_back(min_safe_baxter[i]);\n// \t\tjoint_mid_point_right.push_back(joint_mid_point_baxter[i]);\n// \t}\n\n// }\n\n// void ManipulatorModDQ::robot_state_right()\n// {\n// \tu=u_right;\n// \tp=p_right;\n// \tjoint_type=joint_type_right;\n// \tjoint_names=joint_names_right;\n// \tvelocity_limit_ordered=velocity_limit_ordered_right;\n// \tjoint_size=joint_size_right;\n// \tjoint_low_limit_ordered=joint_low_limit_ordered_right;\n// \tjoint_high_limit_ordered=joint_high_limit_ordered_right;\n// \tmax_safe=max_safe_right;\n// \tmin_safe=min_safe_right;\n// \tjoint_mid_point=joint_mid_point_right;\t\n// \tq= q_baxter.head(joint_size_left);\n// \tq_vel= q_vel_baxter.head(joint_size_left);\n// }\n\n// void ManipulatorModDQ::robot_state_left()\n// {\n// \tu=u_left;\n// \tp=p_left;\n// \tjoint_type=joint_type_left;\n// \tjoint_names=joint_names_left;\n// \tvelocity_limit_ordered=velocity_limit_ordered_left;\n// \tjoint_size=joint_size_left;\n// \tjoint_low_limit_ordered=joint_low_limit_ordered_left;\n// \tjoint_high_limit_ordered=joint_high_limit_ordered_left;\n// \tmax_safe=max_safe_left;\n// \tmin_safe=min_safe_left;\n// \tjoint_mid_point=joint_mid_point_left;\t\n// \tq= q_baxter.tail(joint_size_left);\n// \tq_vel= q_vel_baxter.tail(joint_size_left);\n// }" }, { "alpha_fraction": 0.6586744785308838, "alphanum_fraction": 0.6619883179664612, "avg_line_length": 55.38461685180664, "blob_id": "214def846aaa0eee6a43f207d2bb4f0b949dd046", "content_id": "6ff570f8838f11f246f55dcfe0bcf98c76fde03b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5130, "license_type": "no_license", "max_line_length": 789, "num_lines": 91, "path": "/dq_robotics/src/resolvedAccControl/result_analyzer_ResolcedAccControl.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <dq_robotics/DQoperations.h>\n#include <dq_robotics/ResolveAccControlPrfmnc.h>\n#include <ros/package.h>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <stdexcept> //for range_error\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/TwistStamped.h>\nstd::ofstream result_file;\ngeometry_msgs::PoseStamped desiredPose_gMsgPose, currentPose_gMsgPose;\ngeometry_msgs::TwistStamped desiredVel_gMsgTwist, currentVel_gMsgTwist; \n// void ManipulatorModDQ::joint_state_callback(const sensor_msgs::JointState& jointStateConsPtr)\ndouble timeStamp, x_current, y_current, z_current, qw_current, qx_current, qy_current, qz_current, x_desired, y_desired, z_desired, qw_desired, qx_desired, qy_desired, qz_desired, x_curr_transVel, y_curr_transVel, z_curr_transVel, x_curr_rotVel, y_curr_rotVel, z_curr_rotVel, x_des_transVel, y_des_transVel, z_des_transVel, x_des_rotVel, y_des_rotVel, z_des_rotVel, normError, timeKDLJacDot, timeDQJacDot;\n\nint controllerMode;\n// geometry_msgs/PoseStamped desiredPose # this can be relative desire pose\n// geometry_msgs/PoseStamped currentPose # this can be relative desire pose\n// geometry_msgs/TwistStamped desiredVel # this can be relative desire pose\n// geometry_msgs/TwistStamped currentVel # this can be relative desire pose\n// float64 timeStamp\n// int32 controlMode\n// float64 norm_error \n\nvoid chatterCallback(const dq_robotics::ResolveAccControlPrfmnc& msg)\n{\n\ttimeStamp = msg.timeStamp;\n\n\tx_current = msg.currentPose.pose.position.x;\n\ty_current = msg.currentPose.pose.position.y;\n\tz_current = msg.currentPose.pose.position.z;\n\tqw_current = msg.currentPose.pose.orientation.w;\n\tqx_current = msg.currentPose.pose.orientation.x;\n\tqy_current = msg.currentPose.pose.orientation.y;\n\tqz_current = msg.currentPose.pose.orientation.z;\n\n\tx_desired = msg.desiredPose.pose.position.x;\n\ty_desired = msg.desiredPose.pose.position.y;\n\tz_desired = msg.desiredPose.pose.position.z;\n\tqw_desired = msg.desiredPose.pose.orientation.w;\n\tqx_desired = msg.desiredPose.pose.orientation.x;\n\tqy_desired = msg.desiredPose.pose.orientation.y;\n\tqz_desired = msg.desiredPose.pose.orientation.z;\n\n\tx_curr_transVel = msg.currentVel.twist.linear.x;\n\ty_curr_transVel = msg.currentVel.twist.linear.y;\n\tz_curr_transVel = msg.currentVel.twist.linear.z;\n\tx_curr_rotVel = msg.currentVel.twist.angular.x;\n\ty_curr_rotVel = msg.currentVel.twist.angular.y;\n\tz_curr_rotVel = msg.currentVel.twist.angular.z;\n\n\tx_des_transVel = msg.desiredVel.twist.linear.x;\n\ty_des_transVel = msg.desiredVel.twist.linear.y;\n\tz_des_transVel = msg.desiredVel.twist.linear.z;\n\tx_des_rotVel = msg.desiredVel.twist.angular.x;\n\ty_des_rotVel = msg.desiredVel.twist.angular.y;\n\tz_des_rotVel = msg.desiredVel.twist.angular.z;\n\tnormError = msg.norm_error;\n\tcontrollerMode = msg.controlMode;\n\ttimeKDLJacDot = msg.timeKDLJacDot;\n\ttimeDQJacDot = msg.timeDQJacDot;\n\n\tresult_file << timeStamp << \",\" << x_current << \",\" << y_current << \",\" << z_current << \",\" << qw_current << \",\" << qx_current << \",\" << qy_current << \",\" << qz_current << \",\" << x_desired << \",\" << y_desired << \",\" << z_desired << \",\" << qw_desired << \",\" << qx_desired << \",\" << qy_desired << \",\" << qz_desired << \",\" << x_curr_transVel << \",\" << y_curr_transVel << \",\" << z_curr_transVel << \",\" << x_curr_rotVel << \",\" << y_curr_rotVel << \",\" << z_curr_rotVel << \",\" << x_des_transVel << \",\" << y_des_transVel << \",\" << z_des_transVel << \",\" << x_des_rotVel << \",\" << y_des_rotVel << \",\" << z_des_rotVel << \",\" << normError << \",\" << controllerMode << \",\" << timeKDLJacDot << \",\" << timeDQJacDot << \", \\n\";\t\n\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"resultAnalyzer\");\n\tros::NodeHandle node_;\n\tros::Subscriber sub = node_.subscribe(\"/dq_robotics/trajCntrlResults\", 1000, chatterCallback);\n\n\t// <dq_robotics::ResolveAccControlPrfmnc>(\"/dq_robotics/trajCntrlResults\n\tstd::string result_file_name, result_file_path;\n\tresult_file_name = \"quatBest_270_8_20secs.csv\";\n\tresult_file_path = ros::package::getPath(\"dq_robotics\");\n\tresult_file_path.append(\"/src/resolvedAccControl/result/\");\n\tresult_file_path.append(result_file_name);\n\tstd::cout << \"result_file_name: \" << result_file_path << std::endl;\n\t\n\tresult_file.open(result_file_path);\n\tif(result_file.is_open())\n\t{\n\t\tstd::cout << \"file is open\" << std::endl;\n\t}\n\tresult_file << \"time\" << \",\" << \"x_current\" << \",\" << \"y_current\" << \",\" << \"z_current\" << \",\" << \"qw_current\" << \",\" << \"qx_current\" << \",\" << \"qy_current\" << \",\" << \"qz_current\" << \",\" << \"x_desired\" << \",\" << \"y_desired\" << \",\" << \"z_desired\" << \",\" << \"qw_desired\" << \",\" << \"qx_desired\" << \",\" << \"qy_desired\" << \",\" << \"qz_desired\" << \",\" << \"x_curr_transVel\" << \",\" << \"y_curr_transVel\" << \",\" << \"z_curr_transVel\" << \",\" << \"x_curr_rotVel\" << \",\" << \"y_curr_rotVel\" << \",\" << \"z_curr_rotVel\" << \",\" << \"x_des_transVel\" << \",\" << \"y_des_transVel\" << \",\" << \"z_des_transVel\" << \",\" << \"x_des_rotVel\" << \",\" << \"y_des_rotVel\" << \",\" << \"z_des_rotVel\" << \",\" << \"normError\" << \",\" << \"controllerMode\" << \",\" << \"timeKDLJacDot\" << \",\" << \"timeDQJacDot\" << \", \\n\";\n\n\tros::spin();\n\treturn 0;\n}" }, { "alpha_fraction": 0.640600323677063, "alphanum_fraction": 0.6527119278907776, "avg_line_length": 55.70149230957031, "blob_id": "0fe09c7db77d98a870cafe32df6a463ad5e01759", "content_id": "d110b11ed4c113bcc2b55b49ee506b0a50946dac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3798, "license_type": "no_license", "max_line_length": 869, "num_lines": 67, "path": "/dq_robotics/src/test/controllerPerformancePlot.py", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport rospy\nfrom dq_robotics.msg import ControllerPerformance\nimport numpy as np\nimport time\nimport matplotlib\nmatplotlib.use('GTKAgg')\nfrom matplotlib import pyplot as plt\n\ndef quaternion_multiply(quaternion1, quaternion0):\n w0, x0, y0, z0 = quaternion0\n w1, x1, y1, z1 = quaternion1\n return np.array([-x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,\n x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,\n -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,\n x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0], dtype=np.float64)\ndef xyzRollPitchYaw_from_dq(x) \n \ndef callback(data):\n global time, time_array, abs_des_x, abs_des_y, abs_des_z, abs_des_roll, abs_des_pitch, abs_des_yaw, rel_des_x, rel_des_y, rel_des_z, rel_des_roll, rel_des_pitch, rel_des_yaw, abs_curr_x, abs_curr_y, abs_curr_z, abs_curr_roll, abs_curr_pitch, abs_curr_yaw, rel_curr_x, rel_curr_y, rel_curr_z, rel_curr_roll, rel_curr_pitch, rel_curr_yaw, abs_des_array_x, abs_des_array_y, abs_des_array_z, abs_des_array_roll, abs_des_array_pitch, abs_des_array_yaw, rel_des_array_x, rel_des_array_y, rel_des_array_z, rel_des_array_roll, rel_des_array_pitch, rel_des_array_yaw, abs_curr_array_x, abs_curr_array_y, abs_curr_array_z, abs_curr_array_roll, abs_curr_array_pitch, abs_curr_array_yaw, rel_curr_array_x, rel_curr_array_y, rel_curr_array_z, rel_curr_array_roll, rel_curr_array_pitch, rel_curr_array_yaw, normError_abs, normError_rel, normError_array_abs, normError_array_rel \n time = data.timeStamp\n time_array.append(time)\n\n # rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n \ndef listener():\n\n # In ROS, nodes are uniquely named. If two nodes with the same \n # node are launched, the previous one is kicked off. The\n # anonymous=True flag means that rospy will choose a unique\n # name for our 'listener' node so that multiple listeners can\n # run simultaneously.\n rospy.init_node('listener', anonymous=True)\n global time, time_array, abs_des_x, abs_des_y, abs_des_z, abs_des_roll, abs_des_pitch, abs_des_yaw, rel_des_x, rel_des_y, rel_des_z, rel_des_roll, rel_des_pitch, rel_des_yaw, abs_curr_x, abs_curr_y, abs_curr_z, abs_curr_roll, abs_curr_pitch, abs_curr_yaw, rel_curr_x, rel_curr_y, rel_curr_z, rel_curr_roll, rel_curr_pitch, rel_curr_yaw, abs_des_array_x, abs_des_array_y, abs_des_array_z, abs_des_array_roll, abs_des_array_pitch, abs_des_array_yaw, rel_des_array_x, rel_des_array_y, rel_des_array_z, rel_des_array_roll, rel_des_array_pitch, rel_des_array_yaw, abs_curr_array_x, abs_curr_array_y, abs_curr_array_z, abs_curr_array_roll, abs_curr_array_pitch, abs_curr_array_yaw, rel_curr_array_x, rel_curr_array_y, rel_curr_array_z, rel_curr_array_roll, rel_curr_array_pitch, rel_curr_array_yaw, normError_abs, normError_rel, normError_array_abs, normError_array_rel \n rospy.Subscriber(\"/dq_robotics/results\", ControllerPerformance, callback)\n time_array = []\n abs_des_array_x = []\n abs_des_array_y = []\n abs_des_array_z = []\n abs_des_array_roll = []\n abs_des_array_pitch = []\n abs_des_array_yaw = []\n abs_curr_array_x = []\n abs_curr_array_y = []\n abs_curr_array_z = []\n abs_curr_array_roll = []\n abs_curr_array_pitch = []\n abs_curr_array_yaw = []\n rel_des_array_x = []\n rel_des_array_y = []\n rel_des_array_z = []\n rel_des_array_roll = []\n rel_des_array_pitch = []\n rel_des_array_yaw = []\n rel_curr_array_x = []\n rel_curr_array_y = []\n rel_curr_array_z = []\n rel_curr_array_roll = []\n rel_curr_array_pitch = []\n rel_curr_array_yaw = []\n normError_array_abs = [] \n normError_array_rel = [] \n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n\nif __name__ == '__main__':\n listener()" }, { "alpha_fraction": 0.7255411148071289, "alphanum_fraction": 0.7632900476455688, "avg_line_length": 54.53845977783203, "blob_id": "85c9e5fcb291282859e6425d61e4baf0a43a4010", "content_id": "b9aee15164b58de8202ea1dfb90b5b05ec3af87c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5775, "license_type": "no_license", "max_line_length": 249, "num_lines": 104, "path": "/dq_robotics/include/dq_robotics/DQoperations.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#ifndef DQ_OPERATIONS_H\n#define DQ_OPERATIONS_H\n\n #define _USE_MATH_DEFINES\n#include <iostream>\n#include <math.h>\n#include <stdexcept> //for range_error\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n#include <complex>\n#include <cmath>\n#include <vector>\n#include <cstddef>\n#include <Eigen/SVD>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <geometry_msgs/Quaternion.h>\n#include <time.h> \nusing namespace Eigen;\n\n\nclass DQoperations\n{\nprivate:\n\t// int joint_size;\n\n\npublic:\n\t// const double PI =3.141592653589793238463;\n\tstatic Matrix3d crossProductOp_3d(Vector3d vector);\n\tstatic MatrixXd crossProductOp_6d(VectorXd vector);\n\tstatic RowVector4d multQuat(RowVector4d p, RowVector4d q);\n\tstatic Matrix<double,8,1> mulDQ(Matrix<double,8,1> p, Matrix<double,8,1> q);\n\tstatic RowVector4d conjQuat(RowVector4d p);\n\tstatic Matrix<double,8,1> classicConjDQ(Matrix<double,8,1> dq);\n\tstatic Matrix<double,8,1> dualConjDQ(Matrix<double,8,1> dq);\n\tstatic Matrix<double,8,1> combinedConjDQ(Matrix<double,8,1> dq);\n\tstatic Matrix<double,8,1> screw2DQ(double theta, RowVector3d axis, double d, RowVector3d moment);\n\tstatic void dq2screw(Matrix<double,8,1> dq, double &theta_e, double &d_e, RowVector3d &l_e, RowVector3d &m_e); /*The screwResult DQ contains the screw parameter as [theta d l m] */\n\tstatic Matrix4d dq2HTM(Matrix<double,8,1> dq);\n\tstatic void dq2rotAndTransQuat(Matrix<double,8,1> dq, RowVector4d &rot, RowVector4d &trans);\n\tstatic Matrix<double,8,1> htm2DQ(Matrix4d htm);\n\tstatic std::vector<Matrix<double,8,1> > fkm_dual(RowVectorXd q, std::vector<RowVector3d> u, std::vector<RowVector3d> p);\n\tstatic std::vector<Matrix<double,8,1> > fkm_revolute_only(RowVectorXd q, std::vector<RowVector3d> u, std::vector<RowVector3d> p);\n\tstatic MatrixXd jacobian_revolute_only(RowVectorXd q /*q is defined as [q1 q2 ...]*/, std::vector<RowVector3d> u, std::vector<RowVector3d> p , Matrix<double,8,1> pose_ee_init);\n\t// static double get_error_screw_param(RowVectorXd q /*q is defined as [q1 q2 ...]*/, std::vector<RowVector3d> u, std::vector<RowVector3d> p , Matrix<double,8,1> pose_ee_init, Matrix<double,8,1> pose_ee_desired, RowVector3d &v_e, RowVector3d &w_e);\n\tstatic double get_error_screw_param(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_ee_desired, RowVector3d &v_e, RowVector3d &w_e);\n\tstatic MatrixXd jacobian_dual_vm(RowVectorXd q /*q is defined as [q1 q2 ...]*/, RowVectorXd joint_type, std::vector<RowVector3d> u, std::vector<RowVector3d> p , Matrix<double,8,1> pose_ee_init);\n\tstatic void dqEigenToDQdouble(RowVectorXd dq_eigen, std::vector<double> &dq_double);\n\tstatic void doubleToDQ(Matrix<double,8,1> &dq_eigen, std::vector<double> dq_double);\n\tstatic std::vector<double> dqEigenToDQdouble(RowVectorXd dq_eigen);\n\tstatic Matrix<double,8,1> returnDoubleToDQ(std::vector<double> & dq_double)\n\t{\n\t\tMatrix<double,8,1> dq_eigen;\n\t\tfor (int i=0; i< dq_double.size(); i++)\n\t\t{\n\t\t\tdq_eigen(i)=dq_double[i];\n\t\t}\n\t\treturn dq_eigen;\n\t};\n\n\tstatic std::vector<double> DQToDouble(Matrix<double,8,1> dq_eigen);\n\tstatic Matrix<double,8,1> inverseDQ(Matrix<double,8,1> dq); \n\tstatic Matrix<double,8,1> transformLine(Matrix<double,8,1> line, Matrix<double,8,1> transform);\n\tstatic RowVectorXd transformLineVector(RowVectorXd lineVector, Matrix<double,8,1> transform);\n\tstatic RowVectorXd transformLine6dVector(RowVectorXd lineVector, Matrix<double,8,1> transform);\n\tstatic RowVector3d transformPoint(RowVector3d point, Matrix<double,8,1> transform);\n\tstatic double normalizeAngle(double theta);\n\tstatic RowVectorXd doubleVector2Rowvector(std::vector<double> doubleVector)\n\t{\n\t\tRowVectorXd eigenDouble=RowVectorXd::Zero(doubleVector.size());\n\t\tfor (int i=0; i< doubleVector.size(); i++)\n\t\t{\n\t\t\teigenDouble(i)=doubleVector[i];\n\t\t}\n\t\treturn eigenDouble;\n\t};\n\tstatic std::vector<double> RowVectorToDouble(RowVectorXd eigenVector);\n\tstatic Matrix<double,8,1> sclerp(Matrix<double,8,1> pose_now, Matrix<double,8,1> &pose_intermediate, Matrix<double,8,1> pose_desired, double tau);\n\tstatic Matrix<double,8,1> preGraspFromGraspPose(Matrix<double,8,1> grasp_location, double distance, RowVector3d approach_direction);\n\tstatic geometry_msgs::Pose DQ2geometry_msgsPose(Matrix<double,8,1> pose_now);\n\tstatic geometry_msgs::Twist Rowvector2geometry_msgsTwist(RowVectorXd vel);\n\tstatic RowVectorXd Matrix8d2RowVector8d(Matrix<double,8,1> matrix8d);\n\tstatic RowVectorXd Matrix8d2RowVector6d(Matrix<double,8,1> matrix8d);\n\tstatic Matrix4d htmFromGeometryMsgPose(geometry_msgs::Pose pose);\n\tstatic Matrix<double,8,1> dqFromGeometryMsgPose(geometry_msgs::Pose pose);\n\tstatic Matrix<double,8,1> dq2twist(Matrix<double,8,1> dq) ;\n\tstatic Matrix<double,8,1> twist2dq(Matrix<double,8,1> dq_twist);\n\tstatic Matrix<double,8,1> rotTrans2dq(RowVector4d rot, RowVector4d trans);\n\tstatic MatrixXd transformJacobian(MatrixXd jacobian_8d, Matrix<double,8,1> dq);\n\tstatic MatrixXd invDamped_8d(MatrixXd jacobian_8d, double mu);\n\tstatic RowVectorXd twistEigen2DQEigen(RowVectorXd twist);\n\tstatic RowVectorXd DQEigen2twistEigen(RowVectorXd DQtwist);\n\tstatic RowVectorXd spatial2CartVel(RowVectorXd screwVel, RowVector3d ee_pose);\n\tstatic RowVectorXd spatial2CartAcc(RowVectorXd screwAcc, RowVectorXd screwVel, RowVector3d ee_pose);\n\tstatic double get_error_screw(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_ee_desired, RowVector3d &v_e, RowVector3d &w_e);\n\tstatic RowVectorXd spatial2CartPoseError(Matrix<double,8,1> desired_pose, Matrix<double,8,1> current_pose);\n\tstatic RowVectorXd spatial2CartPoseError_quatVec(Matrix<double,8,1> desired_pose, Matrix<double,8,1> current_pose);\t\n\tstatic Matrix<double,8,1> RowVector6d2Matrix8d(RowVectorXd rowVector6d);\n\tDQoperations();\n\t~DQoperations();\n};\n#endif" }, { "alpha_fraction": 0.7394043803215027, "alphanum_fraction": 0.7508590817451477, "avg_line_length": 36.17021179199219, "blob_id": "71a78e36e96f9c104b30dfde659c7c7c6c8d1f11", "content_id": "949d5bacc11f4c8de98b968d356765e02ffb12ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 172, "num_lines": 47, "path": "/dq_robotics/src/baxter_poseControl_server_2.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server_2.h>\n\nBaxterPoseControlServer_2::BaxterPoseControlServer_2()\n{}\n\nbool BaxterPoseControlServer_2::initialize_handArmController()\n{\n\tif(initializeController())\n\t\tROS_INFO(\"Baxter arms and controller initialized\");\n\tBaxterPoseControlServer_2::init_AR10Kinematics();\n\tBaxterPoseControlServer_2::init_fingers();\n}\n\nvoid BaxterPoseControlServer_2::update_handArm()\n{\n\t\tBaxterPoseControlServer_2::update_manipulator();\n\t\tBaxterPoseControlServer_2::update_right();\n\t\tBaxterPoseControlServer_2::update_left();\n\t\tBaxterPoseControlServer_2::Ar10KinematicsLoop();\n}\n\nvoid BaxterPoseControlServer_2::jacobian_right_armHand()\n{\n\tindex_jacobian_right=MatrixXd::Zero(8,2);\t\n\tfinger_params\tindex_ik, thumb_ik;\n\tindex_ik = index_finger; \n\tthumb_ik = thumb;\n\n\tgetJacobianCoupled(index_ik);\n\tindex_jacobian_right = index_ik.finger_jacobian_coupled;\n\tstd::cout << \"index_jacobian_right: \" << std::endl;\n\tstd::cout << index_jacobian_right << std::endl;\t\n\n\n\tthumb_ik.finger_jacobian_simple= DQController::jacobianDual(thumb_ik.u, thumb_ik.p, thumb_ik.finger_ee_init, thumb_ik.finger_joint_type, thumb_ik.screwDispalcementArray);\t\n\tthumb_ik.finger_jacobian_simple= DQController::jacobianDual_8d(thumb_ik.p.size(), thumb_ik.finger_jacobian_simple);\t\n\tthumb_jacobian_right = thumb_ik.finger_jacobian_simple;\n\tstd::cout << \"thumb_jacobian_right: \" << std::endl;\n\tstd::cout << thumb_jacobian_right << std::endl;\t\n\n\n\n\tarm_jacobian_right= DQController::jacobianDual(u_right, p_right, pose_now_right, joint_type_right, fkm_matrix_right);\t\n\tarm_jacobian_right= DQController::jacobianDual_8d(joint_size_right, arm_jacobian_right);\n\tstd::cout << \"arm_jacobian_right: \" << std::endl;\n\tstd::cout << arm_jacobian_right << std::endl;\t\n}" }, { "alpha_fraction": 0.6298961043357849, "alphanum_fraction": 0.6557385325431824, "avg_line_length": 38.11893081665039, "blob_id": "0af75b08171c02060477806373ff3276fac11087", "content_id": "20b4f7522b5dde39e1c23d6ef79453459a23376d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 39470, "license_type": "no_license", "max_line_length": 265, "num_lines": 1009, "path": "/dq_robotics/src/resolvedAccControl/new_traj_resolved_acc_control.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/DQoperations.h>\n#include <dq_robotics/baxter_dq.h>\n#include <dq_robotics/dq_controller.h>\n#include <dq_robotics/DualArmPlotData.h>\n#include <dq_robotics/baxter_poseControl_server.h>\n#include <sensor_msgs/JointState.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <math.h>\n#include \"baxter_core_msgs/JointCommand.h\"\n#include \"dq_robotics/BaxterControl.h\"\n#include <kdl/frames.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chainidsolver_recursive_newton_euler.hpp>\n#include <kdl/frames.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chainidsolver_recursive_newton_euler.hpp>\n#include <dynamic_reconfigure/server.h>\n#include <dq_robotics/kdl_controllerConfig.h>\n#include <dq_robotics/jacDotSolver.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include \"baxter_core_msgs/JointCommand.h\"\n#include <dq_robotics/ResolveAccControlPrfmnc.h>\n#include <dq_robotics/pseudo_inversion.h>\n// ros::NodeHandle node_;\n\t// \n\nbool start_controller, reset_robot, regulation_control, traj_control, redundancy_resol_active;\nKDL::ChainJntToJacDotSolver *jacDotKDL;\nKDL::ChainJntToJacSolver *jacKDL;\nKDL::Jacobian jac, jdot;\nKDL::ChainIdSolver_RNE *idsolver;\nKDL::Tree tree;\nKDL::Chain chain;\nKDL::Vector g;\nKDL::Rotation rot_correction;\n\ndouble K_JntLmt, mu, K_p, K_d, K_i, K_pP, K_pO, K_dP, K_dO, total_time, time_now_total, theta_init, theta_final, norm_error, traj_pitch, reg_x, reg_theta_x, reg_y, reg_theta_y, reg_z, reg_theta_z, time_now, theta, theta_d, theta_dd, time_dq_jacDot, time_kdl_jacDot;\nros::WallTime start_, end_, start_kdl, end_kdl, start_dq, end_dq, start_total, end_total;\nstd::string robot_desc_string;\t\n\nMatrix4d crclCntr_dsrdTraj, startPose_dsrdTraj;\nMatrix<double,8,1> pe_init_right, pe_now_right, crclCntr_dsrdTraj_dq, startPose_dsrdTraj_dq, lineTraj_dq_cc, pose_desired_right, vel_desired_right, acc_desired_right, acc_cmd_right;\nRowVectorXd q_right, q_vel_right, qdd_cmd, vel_now, vel_cart_now, vel_cart_desired, joint_high_limit, joint_low_limit, joint_max_safe_limit, joint_min_safe_limit, joint_limit_task;\nMatrixXd jacobian_6d_right, jacobian_6d_dot_right, jacKDL_eigen, jacDotKDL_eigen, K_p_mat, K_d_mat;\nBaxterPoseControlServer* baxter_controller;\n\nRowVector3d v_e, w_e;\nKDL::JntArray q_kdl;\nKDL::JntArray dq_kdl;\nKDL::JntArray v_kdl;\nKDL::JntArray torque_kdl;\nKDL::Wrenches fext;\nros::Publisher right_cmd_pub, pose_publisher, result_topic, crclCntr_pose_publisher;\nbaxter_core_msgs::JointCommand cmd;\ngeometry_msgs::PoseStamped desired_pose, crclCntr_dsrdTrajPose;\nint joint_size, controller_type, machineStates_past, machineStates_now, count;\ndq_robotics::ResolveAccControlPrfmnc resultMsg;\ngeometry_msgs::PoseStamped desiredPose_gMsgPose, currentPose_gMsgPose;\ngeometry_msgs::TwistStamped desiredVel_gMsgTwist, currentVel_gMsgTwist; \nMatrix<double,8,1> pose_error, ad_e_star_acc_desired , ad_e_star_vel_desired ,cross_wc_adEVelDesired;\nvoid initializeTraj();\nvoid resetRobot();\nvoid dynReconfgr_callback(dq_robotics::kdl_controllerConfig &config, uint32_t level) ;\nbool initializeAccController(ros::NodeHandle &node_);\nvoid getCubicTheta();\nvoid updateManipulatorState();\n\nvoid getJointLimitTask()\n{\n\tjoint_limit_task=RowVectorXd::Zero(joint_size);\n\tfor (int i=0; i <joint_size; i++)\n\t{\n\t\t// joint_limit_task(i) = (q_right(i)-joint_max_safe_limit(i))/(joint_high_limit(i)- joint_low_limit(i));\n\t\tif(q_right(i)>=joint_max_safe_limit(i))\n\t\t\tjoint_limit_task(i) = (q_right(i)-joint_max_safe_limit(i))/(joint_high_limit(i)- joint_low_limit(i));\n\t\t\t// joint_limit_task(i)=(q_right(i)-joint_max_safe_limit(i))*(2*joint_high_limit(i)-joint_max_safe_limit(i)-q_right(i))/((joint_high_limit(i)-q_right(i))*(joint_high_limit(i)-q_right(i)));\n\t\telse if(q_right(i)<joint_min_safe_limit(i))\n\t\t\tjoint_limit_task(i) = (q_right(i) - joint_min_safe_limit(i))/(joint_high_limit(i)- joint_low_limit(i));\n\t\t\t// joint_limit_task(i)=(joint_min_safe_limit(i)-q_right(i))*(2*joint_low_limit(i)- q_right(i) -joint_min_safe_limit(i))/((q_right(i) - joint_low_limit(i))*(q_right(i) - joint_low_limit(i)));\n\t\telse\n\t\t\tjoint_limit_task(i)=0;\t\t\n\t}\n\tjoint_limit_task = -K_JntLmt*joint_limit_task;\n\tstd::cout << \"q_right: \" << q_right << std::endl; \n\tstd::cout << \"joint_high_limit: \" << joint_high_limit << std::endl; \n\tstd::cout << \"joint_low_limit: \" << joint_low_limit << std::endl; \n\tstd::cout << \"joint_max_safe_limit: \" << joint_max_safe_limit << std::endl; \n\tstd::cout << \"joint_min_safe_limit: \" << joint_min_safe_limit << std::endl; \n\n}\n\n// void getJointLimitFunction()\n// {\t\n// \tjointLimit_repulsive_function.resize(1, joint_size);\n// \tfor(int i=0; i <joint_size; i++)\n// \t{\n// \t\tif(q(i)>=max_safe[i])\n// \t\t\tjointLimit_repulsive_function(0,i)=((q(i) - max_safe[i])*(q(i) - max_safe[i]))/(joint_high_limit_ordered[i]-q(i));\n// \t\telse if(q(i)<min_safe[i])\n// \t\t\tjointLimit_repulsive_function(0,i)=((min_safe[i] - q(i))*(min_safe[i] - q(i)))/(q(i) - joint_low_limit_ordered[i]);\n// \t\telse\n// \t\t\tjointLimit_repulsive_function(0,i)=0;\n// \t\t// std::cout << \"jointLimit_repulsive_function_\" << i << \":\" << jointLimit_repulsive_function(0,i)<< std::endl;\n// \t}\n// }\n\nvoid initializeTraj()\n{\n\treg_x = 0;\n\treg_theta_x = 0;\n\treg_y = 0;\n\treg_theta_y = 0;\n\treg_z = 0;\n\treg_theta_z = 0;\n\tlineTraj_dq_cc << 0, 0, 0, -1, 0, 0, 0, 0;\n\t// crclCntr_dsrdTraj << 1, 0, 0, 0.6,\n\t// \t\t\t\t\t 0, 1, 0, -0.2,\n\t// \t\t\t\t\t 0, 0, 1, 0.2,\n\t// \t\t\t\t\t 0, 0, 0, 1;\n \tcrclCntr_dsrdTraj << 0, 0, 1, 0.45,\n\t\t\t\t\t\t 1, 0, 0, -0.8,\n\t\t\t\t\t\t 0, 1, 0, 0.3,\n\t\t\t\t\t\t 0, 0, 0, 1;\n\tcrclCntr_dsrdTraj_dq = DQoperations::htm2DQ(crclCntr_dsrdTraj);\n\t// startPose_dsrdTraj << -1, 0, 0, 0,\n\t// \t\t\t\t\t 0, 1, 0, -0.2,\n\t// \t\t\t\t\t 0, 0, -1, 0,\n\t// \t\t\t\t\t 0, 0, 0, 1;\n\tstartPose_dsrdTraj << 1, 0, 0, 0,\n\t\t\t\t\t\t 0, 1, 0, 0,\n\t\t\t\t\t\t 0, 0, 1, 0,\n\t\t\t\t\t\t 0, 0, 0, 1;\t\t\t\t\t\t \n\tstartPose_dsrdTraj = crclCntr_dsrdTraj*startPose_dsrdTraj;\n\tstartPose_dsrdTraj_dq = DQoperations::htm2DQ(startPose_dsrdTraj);\n}\n// name: ['right_e0', 'right_e1', 'right_s0', 'right_s1', 'right_w0', 'right_w1', 'right_w2']\n// position: [0.21629129109184334, 1.6912138186436687, -0.6833884410029518, -0.7938350577307016, 1.5980244857796297, 1.368310862793789, -1.0638156763985345]\n\n// 'right_s0', 'right_s1', 'right_e0', 'right_e1', 'right_w0', 'right_w1', 'right_w2', 'left_s0', 'left_s1', 'left_e0', 'left_e1', 'left_w0', 'left_w1', 'left_w2'\nvoid resetRobot()\n{\n\tcmd.mode = baxter_core_msgs::JointCommand::TORQUE_MODE;\n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tcmd.command[i] = 0;\n\t}\t\t\n\tif (right_cmd_pub.getNumSubscribers())\t\n\t{\n\t\tright_cmd_pub.publish(cmd); \n\t}\n ros::Duration(2.0).sleep();\n cmd.mode = baxter_core_msgs::JointCommand::POSITION_MODE;\n cmd.command[0] = -0.6833884410029518;\n cmd.command[1] = -0.7938350577307016;\n cmd.command[2] = 0.21629129109184334;\n cmd.command[3] = 1.6912138186436687;\n cmd.command[4] = 1.5980244857796297;\n cmd.command[5] = 1.368310862793789;\n cmd.command[6] = -1.0638156763985345;\n int count_temp =0; \n while(reset_robot)\t\n\t{\n\t\tif (right_cmd_pub.getNumSubscribers())\t\n\t\t{\n\t\t\tright_cmd_pub.publish(cmd); \n\t\t}\n\t\tros::spinOnce();\n\t}\n\tros::Duration(2.0).sleep();\n\tcmd.mode = baxter_core_msgs::JointCommand::TORQUE_MODE;\n}\n\nvoid dynReconfgr_callback(dq_robotics::kdl_controllerConfig &config, uint32_t level) \n{\n\tROS_INFO(\"2\");\n\tif (config.start_controller)\n\t\tstart_controller = true;\n\telse \n\t\tstart_controller = false;\n\tif (config.reset_robot)\n\t\treset_robot = true;\t\n\telse\n\t\treset_robot = false;\n\tif (config.regulation_control)\n\t\tregulation_control = true;\n\telse\t\n\t\tregulation_control = false;\n\tif (config.traj_control)\n\t\ttraj_control = true;\n\telse\t\n\t\ttraj_control = false;\n\tif (config.redundancy_resol_active)\n\t\tredundancy_resol_active = true;\n\telse\t\n\t\tredundancy_resol_active = false;\n\n\n\tK_pP = config.accCntrl_K_pP;\n\tK_pO = config.accCntrl_K_pO;\n\tK_dP = config.accCntrl_K_dP;\n\tK_dO = config.accCntrl_K_dO;\n\tK_JntLmt = config.accCntrl_K_JntLmt;\n\n\ttraj_pitch = config.accCntrl_traj_pitch;\n\ttotal_time = config.accCntrl_total_time;\n\ttheta_init = config.accCntrl_theta_init;\n\ttheta_final = config.accCntrl_theta_final;\n\tcontroller_type = config.controller_type;\n\treg_x = config.reg_x;\n\treg_theta_x = config.reg_theta_x;\n\treg_y = config.reg_y;\n\treg_theta_y = config.reg_theta_y;\n\treg_z = config.reg_z;\n\treg_theta_z = config.reg_theta_z;\n\tif(controller_type ==0 )\n\t\tstd::cout << \"DQ based controller selected\" << std::endl;\n\telse if(controller_type ==1)\n\t\tstd::cout << \"KDL quaternion error based controller selected\" << std::endl;\n\telse if (controller_type ==2)\t\n\t\tstd::cout << \"KDL quaternion VECTOR error based controller selected\" << std::endl;\t\n \t// ROS_INFO(\"Reconfigure Request: K_p: %f, K_d: %f, K_i: %f, total_time: %f\", \n // K_p, \n // K_d, \n // K_dP, \n // total_time);\n\t// machineStates_past\n\t// machineStates_now \t\n}\n\nbool initializeAccController(ros::NodeHandle &node_)\n{\t\n\tmu = 0.001;\n\tpose_error = MatrixXd::Zero(8, 1);\n\tad_e_star_acc_desired = MatrixXd::Zero(8, 1);\n\tad_e_star_vel_desired = MatrixXd::Zero(8, 1);\n\tcross_wc_adEVelDesired = MatrixXd::Zero(8, 1);\n\tK_d_mat = MatrixXd::Identity(8,8);\n\tK_p_mat = MatrixXd::Identity(8,8);\n\tresult_topic = node_.advertise<dq_robotics::ResolveAccControlPrfmnc>(\"/dq_robotics/trajCntrlResults\", 1000);\n\tpose_publisher = node_.advertise<geometry_msgs::PoseStamped>(\"dq_robotics/desired_pose\", 1000);\n\tcrclCntr_pose_publisher = node_.advertise<geometry_msgs::PoseStamped>(\"dq_robotics/crclCntr_dsrdTraj\", 1000);\n\tright_cmd_pub = node_.advertise<baxter_core_msgs::JointCommand>(\"/robot/limb/right/joint_command\", 1);\n\n\tbaxter_controller = new BaxterPoseControlServer();\n\n\tmachineStates_past = 0;\n\tmachineStates_now = 0;\n\treset_robot = false;\n\ttraj_control = false;\n\tregulation_control = false;\n\tstart_controller = false;\t\n\tredundancy_resol_active = false;\n\ttime_dq_jacDot =0;\n\ttime_kdl_jacDot =0;\n\tcontroller_type = 0;\n\n\t// rot_correction = rot_correction.SetInverse();\n\tstart_ = ros::WallTime::now();\n\tend_ = ros::WallTime::now();\n\tstart_kdl = ros::WallTime::now();\n\tend_kdl = ros::WallTime::now();\n\tstart_dq = ros::WallTime::now();\n\tend_dq = ros::WallTime::now();\n\ttime_now = 0;\t\n\tros::Duration(1.0).sleep();\n\n\tdesired_pose.header.frame_id = \"base\";\n\tdesired_pose.header.stamp = ros::Time::now();\n\tcrclCntr_dsrdTrajPose.header.frame_id = \"base\";\n\tcrclCntr_dsrdTrajPose.header.stamp = ros::Time::now();\n\tcmd.mode = baxter_core_msgs::JointCommand::TORQUE_MODE;\n\tcmd.names.push_back(\"right_s0\");\n\tcmd.names.push_back(\"right_s1\");\n\tcmd.names.push_back(\"right_e0\");\n\tcmd.names.push_back(\"right_e1\");\n\tcmd.names.push_back(\"right_w0\");\n\tcmd.names.push_back(\"right_w1\");\n\tcmd.names.push_back(\"right_w2\");\n\tcmd.command.resize(cmd.names.size());\n\n\tif(!node_.getParam(\"/robot_description\",robot_desc_string))\n\t {\n\t\t\tROS_ERROR(\"Could not find '/robot_description'.\");\n\t\t\treturn false;\n\t}\n\tif (!kdl_parser::treeFromString(robot_desc_string,tree))\n\t{\n\t\tROS_ERROR(\"Failed to construct KDL tree.\");\n\t\treturn false;\n\t}\n\n\n\tif (!tree.getChain(\"base\",\"right_hand\",chain)) \n\t{\n\t\tROS_ERROR(\"Failed to get chain from KDL tree.\");\n\t\treturn false;\n\t}\n\tnode_.param(\"/gazebo/gravity_x\",g[0],0.0);\n\tnode_.param(\"/gazebo/gravity_y\",g[1],0.0);\n\t// node_.param(\"/gazebo/gravity_z\",g[2],-9.8); // put it to zero to use baxter gravity comps. Try both\n\tnode_.param(\"/gazebo/gravity_z\",g[2], 0.0); // put it to zero to use baxter gravity comps. Try both\n\tstd::cout << \"chain.getNrOfJoints(): \" << chain.getNrOfJoints() << std::endl; \n\tstd::cout << \"chain.getNrOfSegments(): \" << chain.getNrOfSegments() << std::endl; \n\tfext.resize(chain.getNrOfSegments());\n\tfor(unsigned int i=0;i < fext.size();i++) fext[i].Zero();\n\tjoint_size = chain.getNrOfJoints(); \n\tq_kdl.resize(joint_size);\n\tdq_kdl.resize(joint_size);\n\tv_kdl.resize(joint_size);\t\n\tjac.resize(joint_size);\n\tjdot.resize(joint_size);\n\ttorque_kdl.resize(joint_size);\n\tjoint_high_limit = RowVectorXd::Zero(joint_size);\n\tjoint_low_limit = RowVectorXd::Zero(joint_size);\n\tjoint_max_safe_limit = RowVectorXd::Zero(joint_size);\n\tjoint_min_safe_limit = RowVectorXd::Zero(joint_size);\t\n\t// jacKDL=new KDL::ChainJntToJacSolver (chain);\t\n\tif((jacKDL=new KDL::ChainJntToJacSolver (chain)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainJntToJacSolver.\");\n\t\treturn false;\n\t}\n\tif((jacDotKDL=new KDL::ChainJntToJacDotSolver (chain)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainJntToJacDotSolver.\");\n\t\treturn false;\n\t}\t\n\tjacDotKDL->setRepresentation(0);\n\tif (!baxter_controller->BaxterPoseControlServer::initializeController())\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\t\n\tstd::string arm =\"right\";\n\tif (!baxter_controller->BaxterPoseControlServer::importJointLimits(arm, joint_high_limit, joint_low_limit, joint_max_safe_limit, joint_min_safe_limit))\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\n\tstd::cout << \"joint_high_limit: \" << joint_high_limit << std::endl; \n\tstd::cout << \"joint_low_limit: \" << joint_low_limit << std::endl; \n\tstd::cout << \"joint_max_safe_limit: \" << joint_max_safe_limit << std::endl; \n\tstd::cout << \"joint_min_safe_limit: \" << joint_min_safe_limit << std::endl; \n\n\tif((idsolver=new KDL::ChainIdSolver_RNE(chain,g)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainIDSolver_RNE.\");\n\t\treturn false;\n\t}\t\n\tinitializeTraj();\n\tupdateManipulatorState();\t\n\treturn 1;\n}\n\n\nvoid getCubicTheta()\n{\n\ttheta = (theta_init - 3.0 * (time_now * time_now) * (theta_init - theta_final)\n\t / (total_time * total_time)) + 2.0 * pow(time_now, 3.0) *\n\t(theta_init - theta_final) / pow(total_time, 3.0);\n\tstd::cout << \"time_now: \" << time_now << \"theta: \" << theta << std::endl;\n\t/* theta_d = -(6*time_now*(theta_init - theta_final))/total_time^2 - (6*time_now^2*(theta_init - theta_final))/total_time^3; */\n\ttheta_d = 6.0 * (time_now * time_now) * (theta_init - theta_final) /\n\tpow(total_time, 3.0) - 6.0 * time_now * (theta_init - theta_final) /\n\t(total_time * total_time);\n\n\t/* theta_dd = -(6*(theta_init - theta_final))/total_time^2 - (12*time_now*(theta_init - theta_final))/total_time^3; */\n\ttheta_dd = 12.0 * time_now * (theta_init - theta_final) / pow(total_time, 3.0) - 6.0 * (theta_init - theta_final) / (total_time*total_time);\n}\n\nvoid updateManipulatorState()\n{\n\t// ROS_INFO(\"updateManipulatorState\");\n\tstd::string arm =\"right\";\n\tbaxter_controller->BaxterPoseControlServer::update_manipulator();\n\tstart_dq = ros::WallTime::now();\n\tif(!baxter_controller->BaxterPoseControlServer::importManipulatorState_accControl(arm, pe_init_right, pe_now_right, q_right, q_vel_right, jacobian_6d_right, jacobian_6d_dot_right))\n\t\tstd::cout << arm << \" arm can not be updated\" << std::endl;\n\tend_dq = ros::WallTime::now();\n\ttime_dq_jacDot = (end_dq - start_dq).toSec();\n}\n\n\nvoid getDesiredTraj()\n{\n\t// ROS_INFO(\"getDesiredTraj\");\n\tgetCubicTheta();\n\tMatrix<double,8,1> cc_startinPose_dq, l_startingPose, l_baseFrame; \t\n\tcc_startinPose_dq = DQoperations::classicConjDQ( DQoperations::mulDQ(DQoperations::classicConjDQ(crclCntr_dsrdTraj_dq), startPose_dsrdTraj_dq));\n\tl_startingPose = DQoperations::mulDQ(cc_startinPose_dq , DQoperations::mulDQ(lineTraj_dq_cc, DQoperations::classicConjDQ(cc_startinPose_dq )));\n\tl_baseFrame = DQoperations::mulDQ(startPose_dsrdTraj_dq, DQoperations::mulDQ(l_startingPose, DQoperations::classicConjDQ(startPose_dsrdTraj_dq)));\n \tRowVector3d axis, moment;\n \taxis << l_startingPose(1), l_startingPose(2), l_startingPose(3);\n \tmoment << l_startingPose(5), l_startingPose(6), l_startingPose(7);\n \tdouble d_traj = traj_pitch*theta;\n \t// double d_traj = 0;\n\tpose_desired_right = DQoperations::screw2DQ(theta, axis, d_traj, moment);\n\tpose_desired_right = DQoperations::mulDQ(startPose_dsrdTraj_dq, pose_desired_right);\n\tvel_desired_right = l_baseFrame*theta_d;\n\tacc_desired_right = l_baseFrame*theta_dd;\n\t// desired_pose.pose = DQoperations::DQ2geometry_msgsPose(pose_desired_right);\n\t// desired_pose.header.stamp = ros::Time::now();\n\t// pose_publisher.publish(desired_pose);\n}\n\nMatrix<double,8,1> getAd_e_star(Matrix<double,8,1> pose_error, Matrix<double,8,1> dq)\n{\t\n\tpose_error = DQoperations::mulDQ(DQoperations::classicConjDQ(pose_error), DQoperations::mulDQ(dq, pose_error));\n\treturn pose_error;\n}\n\nMatrix<double,8,1> getCross_wc_adEVelDesired(RowVectorXd vel , Matrix<double,8,1> adEStarVelDesired)\n{\n\tVectorXd adEStarVelDesired_6Vec;\n\tRowVectorXd adEStarVelDesired_6d = DQoperations::Matrix8d2RowVector6d(adEStarVelDesired);\n\tadEStarVelDesired_6Vec = DQoperations::crossProductOp_6d(vel)*adEStarVelDesired_6d.transpose();\n\tadEStarVelDesired = DQoperations::RowVector6d2Matrix8d(adEStarVelDesired_6Vec);\n\treturn adEStarVelDesired;\n}\n\nvoid doJointLimitRR(MatrixXd jacobian)\n{\n\tgetJointLimitTask();\n\tEigen::MatrixXd pinv;\n\tpseudo_inverse(jacobian, pinv, true);\n\tstd::cout << \"pinv: \" << std::endl;\n\tstd::cout << pinv << std::endl;\t\n\tstd::cout << \"joint_limit_task: \" << std::endl;\n\tstd::cout << joint_limit_task << std::endl;\t\t\n\t\n\tVectorXd qdd_cmd_jntLimit = (MatrixXd::Identity(7,7) - pinv*jacobian)*joint_limit_task.transpose();\n\tstd::cout << \"qdd_cmd_jntLimit.transpose(): \" << std::endl;\n\tstd::cout << qdd_cmd_jntLimit.transpose() << std::endl;\n\tqdd_cmd = qdd_cmd + qdd_cmd_jntLimit.transpose();\n}\n\nvoid getNewControlLaw()\n{\n\tRowVector3d ee_position_now, ee_position_desired;\n\tMatrix4d htm_desired, htm_current;\n\tK_d_mat = MatrixXd::Identity(8,8);\n\tK_p_mat = MatrixXd::Identity(8,8);\t\n\tK_p_mat(1,1) = K_pO;\n\tK_p_mat(2,2) = K_pO;\n\tK_p_mat(3,3) = K_pO;\n\tK_p_mat(5,5) = K_pP;\n\tK_p_mat(6,6) = K_pP;\n\tK_p_mat(7,7) = K_pP;\t\n\t// ROS_INFO(\"5\");\n\tK_d_mat(1,1) = K_dO;\n\tK_d_mat(2,2) = K_dO;\n\tK_d_mat(3,3) = K_dO;\n\tK_d_mat(5,5) = K_dP;\n\tK_d_mat(6,6) = K_dP;\n\tK_d_mat(7,7) = K_dP;\t\t\n\t// ROS_INFO(\"NEW CONTROL LAW\");\n\t// ROS_INFO(\"NEW CONTROL LAW\");\n\t// std::cout << \"jacobian_6d_dot_right\" << std::endl;\n\t// std::cout << jacobian_6d_dot_right << std::endl;\n\thtm_current = DQoperations::dq2HTM(pe_now_right);\n\thtm_desired = DQoperations::dq2HTM(pose_desired_right);\n\t// ROS_INFO(\"1\");\n\tee_position_now << htm_current(0,3), htm_current(1,3), htm_current(2,3);\n\n\tee_position_desired << htm_desired(0,3), htm_desired(1,3), htm_desired(2,3);\n\n\tpose_error=DQoperations::mulDQ(pose_desired_right, DQoperations::classicConjDQ(pe_now_right));\t\n\t// ROS_INFO(\"getControlLaw\");\n\t// get cmd acc for kdl\n\tMatrix<double,8,1> error_dq, vel_now_8d;\n\terror_dq << 0, 0, 0, 0, 0, 0, 0, 0;\n\tnorm_error = DQoperations::get_error_screw(pe_now_right, pose_desired_right, v_e, w_e);\n\terror_dq << 0, w_e(0), w_e(1), w_e(2), 0, v_e(0), v_e(1), v_e(2);\n\t// ROS_INFO(\"getControlLaw_1\");\n\t// Notice negative sign in K_p term, because the twist error is from curr to des in base frame\n\tstd::cout << \"error_dq: \" << error_dq.transpose() << std::endl;\n\t\t// ROS_INFO(\"2\");\n\tvel_now = jacobian_6d_right*q_vel_right.transpose();\n\t\t// ROS_INFO(\"3\");\n\tvel_cart_now = vel_now;\n\tvel_cart_now = DQoperations::spatial2CartVel(vel_cart_now, ee_position_now);\n\t\t\t// ROS_INFO(\"4\");\n\tvel_cart_desired = DQoperations::Matrix8d2RowVector6d(vel_desired_right);\n\t\t\t// ROS_INFO(\"5\");\n\tvel_cart_desired = DQoperations::spatial2CartVel(vel_cart_desired, ee_position_desired);\n\tvel_now_8d << 0, vel_now(0), vel_now(1), vel_now(2), 0, vel_now(3), vel_now(4), vel_now(5); \n\t// std::cout << \"vel_now_8d: \" << vel_now_8d.transpose() << std::endl;\n\tad_e_star_acc_desired = getAd_e_star(pose_error, acc_desired_right);\n\tad_e_star_vel_desired = getAd_e_star(pose_error, vel_desired_right);\n\tcross_wc_adEVelDesired = getCross_wc_adEVelDesired(vel_now ,ad_e_star_vel_desired);\n\t// std::cout << \"K_d_mat\" << std::endl;\n\t// std::cout << K_d_mat << std::endl;\n\t// std::cout << \"K_p_mat\" << std::endl;\n\t// std::cout << K_p_mat << std::endl;\n\t// std::cout << \"K_p_mat*(error_dq)\" << std::endl;\n\t// std::cout << K_p_mat*(error_dq) << std::endl;\n\t// std::cout << \"vel_now_8d\" << std::endl;\n\t// std::cout << vel_now_8d << std::endl;\n\t// std::cout << \"ad_e_star_vel_desired\" << std::endl;\n\t// std::cout << ad_e_star_vel_desired << std::endl;\n\n\n\tacc_cmd_right = acc_desired_right + K_d_mat*(ad_e_star_vel_desired - vel_now_8d) + K_p_mat*(error_dq) + cross_wc_adEVelDesired + ad_e_star_acc_desired;\n\t// acc_cmd_right = K_d*(vel_desired_right - vel_now_8d) - K_p*(error_dq);\n\t// std::cout << \"acc_cmd_right: \" << acc_cmd_right.transpose() << std::endl;\n\t// ROS_INFO(\"getControlLaw_2, acc_cmd_right.rows(): %d, acc_cmd_right.cols(): %d \", acc_cmd_right.rows(), acc_cmd_right.cols());\n\tRowVectorXd acc_cmd_6d = RowVectorXd::Zero(6);\n\t\n\tacc_cmd_6d << acc_cmd_right(1,0), acc_cmd_right(2,0), acc_cmd_right(3,0), acc_cmd_right(5,0), acc_cmd_right(6,0), acc_cmd_right(7,0);\n\t// std::cout << \"acc_cmd_6d : \" << acc_cmd_6d << std::endl;\n\t// ROS_INFO(\"getControlLaw_3\");\n\tMatrixXd jacobian_8d = MatrixXd::Zero(8, jacobian_6d_right.cols());\n\t// ROS_INFO(\"getControlLaw_4\");\n\tjacobian_8d.block(1, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(0, 0, 3, jacobian_8d.cols());\n\tjacobian_8d.block(5, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(3, 0, 3, jacobian_8d.cols());\t\n\t// ROS_INFO(\"getControlLaw_5\");\n\t\n\tMatrixXd jac_inv_damped = DQoperations::invDamped_8d(jacobian_8d, mu);\n\t// std::cout << \"acc_cart1: \" << std::endl;\n\t// std::cout << acc_cmd_6d.transpose() << std::endl;\n\t// std::cout << \"acc_cart2: \" << std::endl;\n\t// std::cout << - jacobian_6d_dot_right*q_vel_right.transpose() << std::endl;\t\n\t// ROS_INFO(\"getControlLaw_7\");\n\tRowVectorXd acc_term_8d= RowVectorXd::Zero(8);\n\tacc_term_8d = DQoperations::twistEigen2DQEigen(acc_cmd_6d.transpose() - jacobian_6d_dot_right*q_vel_right.transpose()); \n\t// std::cout << \"jdotQdot: \" << std::endl;\n\t// std::cout << (jacobian_6d_dot_right*q_vel_right.transpose()).transpose() << std::endl;\n\tqdd_cmd = jac_inv_damped*acc_term_8d.transpose();\n\tif(redundancy_resol_active)\n\t{\n\t\tROS_INFO(\"redundancy_resol_active\");\t\n\t\tdoJointLimitRR(jacobian_6d_right);\t\n\t}\t\t\n\t// std::cout << \"qdd_cmd: \" << qdd_cmd << std::endl;\n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tq_kdl(i) = q_right(i);\n\t\tdq_kdl(i) = q_vel_right(i);\n\t\tv_kdl(i) = qdd_cmd(i);\n\t}\n}\n\n\n\n// void getControlLaw()\n// {\n// \t// ROS_INFO(\"getControlLaw\");\n// \t// get cmd acc for kdl\n// \tMatrix<double,8,1> error_dq, vel_now_8d;\n// \tnorm_error = DQoperations::get_error_screw(pe_now_right, pose_desired_right, v_e, w_e);\n// \terror_dq << 0, w_e(0), w_e(1), w_e(2), 0, v_e(0), v_e(1), v_e(2);\n// \t// ROS_INFO(\"getControlLaw_1\");\n// \t// Notice negative sign in K_p term, because the twist error is from curr to des in base frame\n// \t// std::cout << \"vel_now: \" << jacobian_6d_right*q_vel_right.transpose() << std::endl;\n// \tvel_now = jacobian_6d_right*q_vel_right.transpose();\n// \tvel_now_8d << 0, vel_now(0), vel_now(1), vel_now(2), 0, vel_now(3), vel_now(4), vel_now(5); \n// \tstd::cout << \"vel_now_8d: \" << vel_now_8d.transpose() << std::endl;\n// \tacc_cmd_right = acc_desired_right + K_d*(vel_desired_right - vel_now_8d) + K_p*(error_dq);\n// \t// acc_cmd_right = K_d*(vel_desired_right - vel_now_8d) - K_p*(error_dq);\n// \tstd::cout << \"acc_cmd_right: \" << acc_cmd_right.transpose() << std::endl;\n// \t// ROS_INFO(\"getControlLaw_2, acc_cmd_right.rows(): %d, acc_cmd_right.cols(): %d \", acc_cmd_right.rows(), acc_cmd_right.cols());\n// \tRowVectorXd acc_cmd_6d = RowVectorXd::Zero(6);\n\t\n// \tacc_cmd_6d << acc_cmd_right(1,0), acc_cmd_right(2,0), acc_cmd_right(3,0), acc_cmd_right(5,0), acc_cmd_right(6,0), acc_cmd_right(7,0);\n// \tstd::cout << \"acc_cmd_6d : \" << acc_cmd_6d << std::endl;\n// \t// ROS_INFO(\"getControlLaw_3\");\n// \tMatrixXd jacobian_8d = MatrixXd::Zero(8, jacobian_6d_right.cols());\n// \t// ROS_INFO(\"getControlLaw_4\");\n// \tjacobian_8d.block(1, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(0, 0, 3, jacobian_8d.cols());\n// \tjacobian_8d.block(5, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(3, 0, 3, jacobian_8d.cols());\t\n// \t// ROS_INFO(\"getControlLaw_5\");\n// \tdouble mu = 0.0001;\n// \tMatrixXd jac_inv_damped = DQoperations::invDamped_8d(jacobian_8d, mu);\n// \t// std::cout << \"acc_cart1: \" << std::endl;\n// \t// std::cout << acc_cmd_6d.transpose() << std::endl;\n// \t// std::cout << \"acc_cart2: \" << std::endl;\n// \t// std::cout << - jacobian_6d_dot_right*q_vel_right.transpose() << std::endl;\t\n// \t// ROS_INFO(\"getControlLaw_7\");\n// \tRowVectorXd acc_term_8d= RowVectorXd::Zero(8);\n// \tacc_term_8d = DQoperations::twistEigen2DQEigen(acc_cmd_6d.transpose() - jacobian_6d_dot_right*q_vel_right.transpose()); \n// \tstd::cout << \"jdotQdot: \" << std::endl;\n// \tstd::cout << (jacobian_6d_dot_right*q_vel_right.transpose()).transpose() << std::endl;\n// \tqdd_cmd = jac_inv_damped*acc_term_8d.transpose();\n// \tstd::cout << \"qdd_cmd: \" << qdd_cmd << std::endl;\n// \tfor(unsigned int i=0;i < joint_size;i++)\n// \t{\n// \t\tq_kdl(i) = q_right(i);\n// \t\tdq_kdl(i) = q_vel_right(i);\n// \t\tv_kdl(i) = qdd_cmd(i);\n// \t}\n// }\n\nvoid getKDLjacDot()\n{\n\tstart_kdl = ros::WallTime::now();\n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tq_kdl(i) = q_right(i);\n\t\tdq_kdl(i) = q_vel_right(i);\n\t}\t\t\n\tif(jacDotKDL->JntToJacDot (KDL::JntArrayVel(q_kdl, dq_kdl), jdot) < 0)\t\t\t\t\n\t\t\t\t\tROS_ERROR(\"KDL jacobian dot solver failed.\");\t\t\t\n\tjacDotKDL_eigen = jdot.data;\n\tstd::cout << \"jacDot\" << std::endl;\n\tstd::cout << jacDotKDL_eigen << std::endl;\n\tend_kdl = ros::WallTime::now();\n\ttime_kdl_jacDot = (end_kdl - start_kdl).toSec();\t\n}\n\nvoid getCartControlLaw()\n{\n\tROS_INFO(\"1\");\n\tK_d_mat = MatrixXd::Identity(6,6);\n\tK_p_mat = MatrixXd::Identity(6,6);\t\n\tK_p_mat(0,0) = K_pO;\n\tK_p_mat(1,1) = K_pO;\n\tK_p_mat(2,2) = K_pO;\n\tK_p_mat(3,3) = K_pP;\n\tK_p_mat(4,4) = K_pP;\n\tK_p_mat(5,5) = K_pP;\n\n\n\tROS_INFO(\"5\");\n\tK_d_mat(0,0) = K_dO;\n\tK_d_mat(1,1) = K_dO;\n\tK_d_mat(2,2) = K_dO;\n\tK_d_mat(4,4) = K_dP;\n\tK_d_mat(3,3) = K_dP;\n\tK_d_mat(5,5) = K_dP;\n\t\t\t\n\tRowVector3d ee_position_now, ee_position_desired;\n\tMatrix4d htm_desired, htm_current;\n\thtm_current = DQoperations::dq2HTM(pe_now_right);\n\thtm_desired = DQoperations::dq2HTM(pose_desired_right);\n\tee_position_now << htm_current(0,3), htm_current(1,3), htm_current(2,3);\n\tee_position_desired << htm_desired(0,3), htm_desired(1,3), htm_desired(2,3);\n\tnorm_error = DQoperations::get_error_screw(pe_now_right, pose_desired_right, v_e, w_e);\n\tMatrix<double,8,1> error_dq; \n\terror_dq << 0, w_e(0), w_e(1), w_e(2), 0, v_e(0), v_e(1), v_e(2);\n\tstd::cout << \"error_dq: \" << error_dq.transpose() << std::endl;\n\tRowVectorXd kdl_error_pose;\n\tif (controller_type==1)\n\t\tkdl_error_pose = DQoperations::spatial2CartPoseError(pose_desired_right, pe_now_right);\n\telse if (controller_type==2)\n\t\tkdl_error_pose = DQoperations::spatial2CartPoseError_quatVec(pose_desired_right, pe_now_right);\n\t// std::cout << \"kdl_error_pose: \" << kdl_error_pose << std::endl;\n\tvel_now = jacobian_6d_right*q_vel_right.transpose();\n\tvel_cart_now = vel_now;\n\t\n\t// ROS_INFO(\"2\");\n\t// vel_cart_now = DQoperations::Matrix8d2RowVector6d(vel_cart_now);\n\t// ROS_INFO(\"3\");\t\n\tvel_cart_now = DQoperations::spatial2CartVel(vel_cart_now, ee_position_now);\t\t\n\t// std::cout << \"vel_cart_now: \" << vel_cart_now << std::endl;\n\tvel_cart_desired = DQoperations::Matrix8d2RowVector6d(vel_desired_right);\n\tvel_cart_desired = DQoperations::spatial2CartVel(vel_cart_desired, ee_position_desired);\n\t// std::cout << \"vel_cart_desired: \" << vel_cart_desired << std::endl;\t\t\n\tRowVectorXd kdl_error_vel = vel_cart_desired - vel_cart_now;\n\t// std::cout << \"acc_desired_right: \" << acc_desired_right.transpose() << std::endl;\t\n\tRowVectorXd kdl_acc_desired = DQoperations::Matrix8d2RowVector6d(acc_desired_right);\n\t// std::cout << \"kdl_acc_desired1: \" << kdl_acc_desired << std::endl;\t\n\tkdl_acc_desired = DQoperations::spatial2CartAcc(acc_desired_right, DQoperations::Matrix8d2RowVector6d(vel_desired_right), ee_position_desired);\n\t// std::cout << \"K_d_mat.block<6,6>(1,1): \" << std::endl;\t\t\t\n\t// std::cout << K_d_mat.block<6,6>(1,1) << std::endl;\t\t\t\n\t// std::cout << \"K_p_mat.block<6,6>(1,1): \" << std::endl;\t\t\t\n\t// std::cout << K_p_mat.block<6,6>(1,1) << std::endl;\t\t\t\n\tRowVectorXd kdl_acc_cmd = kdl_acc_desired + (vel_cart_desired - vel_cart_now)*K_d_mat + (kdl_error_pose)*K_p_mat;\n\t// RowVectorXd kdl_acc_cmd = K_d*(vel_cart_desired - vel_cart_now) + K_p*(kdl_error_pose);\n\t// RowVectorXd kdl_acc_cmd = K_p*(kdl_error_pose);\n\t// kdl_acc_cmd << kdl_acc_cmd(3), kdl_acc_cmd(4), kdl_acc_cmd(5), kdl_acc_cmd(0), kdl_acc_cmd(1), kdl_acc_cmd(2);\n\t// std::cout << \"kdl_acc_cmd: \" << std::endl;\t\t\n\tstd::cout << kdl_acc_cmd << std::endl;\n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tq_kdl(i) = q_right(i);\n\t\tdq_kdl(i) = q_vel_right(i);\n\t}\t\t\n\tif(jacKDL->JntToJac (q_kdl, jac) < 0)\n\t\t\tROS_ERROR(\"KDL jacobian solver failed.\");\n\t// jac.changeBase (rot_correction);\n\t// std::cout << \"jacobianKDL: \" << std::endl;\t\n\t// std::cout << jac.data << std::endl;\n\tstart_kdl = ros::WallTime::now();\n\tif(jacDotKDL->JntToJacDot (KDL::JntArrayVel(q_kdl, dq_kdl), jdot) < 0)\t\t\t\t\n\t\t\t\t\tROS_ERROR(\"KDL jacobian dot solver failed.\");\t\t\t\n\tjacKDL_eigen = jac.data;\n\tend_kdl = ros::WallTime::now();\n\ttime_kdl_jacDot = (end_kdl - start_kdl).toSec();\t\t\n\n\tMatrixXd jac_temp = jacKDL_eigen;\n\tjacKDL_eigen.block(3, 0, 3, joint_size) = jac_temp.block(0, 0, 3, joint_size); \n\tjacKDL_eigen.block(0, 0, 3, joint_size) = jac_temp.block(3, 0, 3, joint_size); \n\t\n\tjacDotKDL_eigen = jdot.data;\n\tjac_temp = jacDotKDL_eigen;\n\tjacDotKDL_eigen.block(3, 0, 3, joint_size) = jac_temp.block(0, 0, 3, joint_size); \n\tjacDotKDL_eigen.block(0, 0, 3, joint_size) = jac_temp.block(3, 0, 3, joint_size); \t\n\t// std::cout << \"jacDotKDL_eigen: \" << std::endl;\t\n\t// std::cout << jacDotKDL_eigen << std::endl;\t\t\n\t// double mu = 0.0001;\n\t// ROS_INFO(\"8\");\t\n\t// MatrixXd jacobian_8d = MatrixXd::Zero(8, jacobian_6d_right.cols());\n\t// // ROS_INFO(\"getControlLaw_4\");\n\t// jacobian_8d.block(1, 0, 3, jacobian_8d.cols()) = jacKDL_eigen.block(0, 0, 3, jacobian_8d.cols());\n\t// jacobian_8d.block(5, 0, 3, jacobian_8d.cols()) = jacKDL_eigen.block(3, 0, 3, jacobian_8d.cols());\t\t\n\t// jacobian_8d = DQoperations::invDamped_8d(jacobian_8d, mu);\n\t// std::cout << \"jacobian_8d_damped: \" << std::endl;\t\n\t// std::cout << jacobian_8d << std::endl;\n\n\tMatrixXd jac_inv_damped = DQoperations::invDamped_8d(jacKDL_eigen, mu);\n\t// std::cout << \"jacobian_6d_damped: \" << std::endl;\t\n\t// std::cout << jac_inv_damped << std::endl;\n\n\tVectorXd acc_term= RowVectorXd::Zero(6);\n\tacc_term = (kdl_acc_cmd.transpose() - jacDotKDL_eigen*q_vel_right.transpose()); \n\t// acc_term = (kdl_acc_cmd.transpose() ); \n\t// std::cout << \"acc_term: \" << acc_term.transpose() << std::endl;\n\t// std::cout << \"jac_inv_damped: \" << jac_inv_damped << std::endl;\n\tacc_term = jac_inv_damped*acc_term;\n\t// ROS_INFO(\"10\");\n\tqdd_cmd = acc_term.transpose();\n\tif(redundancy_resol_active)\n\t{\n\t\tdoJointLimitRR(jacKDL_eigen);\t\n\t}\t\n\t// std::cout << \"qdd_cmd: \" << qdd_cmd << std::endl;\t\n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tv_kdl(i) = qdd_cmd(i);\n\t}\n}\n\nvoid compileResults()\n{\n\tresultMsg.desiredPose.header.stamp = ros::Time::now();\t\n\tresultMsg.desiredPose.pose = DQoperations::DQ2geometry_msgsPose(pose_desired_right);\n\tresultMsg.currentPose.header.stamp = ros::Time::now();\t\n\tresultMsg.currentPose.pose = DQoperations::DQ2geometry_msgsPose(pe_now_right);\t\n\tresultMsg.desiredVel.header.stamp = ros::Time::now();\n\tresultMsg.currentVel.header.stamp = ros::Time::now();\n\t// if(controller_type != 0)\n\t// {\t\n\t\tresultMsg.currentVel.twist = DQoperations::Rowvector2geometry_msgsTwist(vel_cart_now);\n\t\tresultMsg.desiredVel.twist = DQoperations::Rowvector2geometry_msgsTwist(vel_cart_desired);\n\t// }\n\t// else\n\t// {\n\t// \tresultMsg.currentVel.twist = DQoperations::Rowvector2geometry_msgsTwist(vel_now);\n\t// \tresultMsg.desiredVel.twist = DQoperations::Rowvector2geometry_msgsTwist(vel_desired_right);\n\t// }\t\n\t// resultMsg.desiredPose = DQoperations::DQToDouble(pose_desired_right);\n\t// resultMsg.currentPose = DQoperations::DQToDouble(pe_now_right);\n\t// resultMsg.desiredVel = DQoperations::RowVectorToDouble(vel_desired_right);\n\t// resultMsg.currentVel = DQoperations::RowVectorToDouble(vel_now);\n\n\t// resultMsg.timeStamp = time_now_total;\n\tresultMsg.timeStamp = time_now;\n\tresultMsg.timeKDLJacDot = time_kdl_jacDot;\n\tresultMsg.timeDQJacDot = time_dq_jacDot;\n\tresultMsg.norm_error = norm_error;\n\tresultMsg.controlMode = controller_type;\n// \tfloat64 timeKDLJacDot\n// float64 timeDQJacDot\n\t// std::vector<double> DQoperations::DQToDouble(Matrix<double,8,1> dq_eigen)\n\t// Matrix<double,8,1> DQoperations::returnDoubleToDQ(std::vector<double> dq_double)\n\t// RowVectorXd DQoperations::doubleVector2Rowvector(std::vector<double> doubleVector)\n}\n\nvoid updateTime()\n{\n\ttime_now = 0;\n\tstart_ = ros::WallTime::now();\n\tend_ = ros::WallTime::now();\n\t// start_controller =false;\n}\n\nvoid doTrajControl()\n{\n\t// getKDLjacDot();\n\t// if (time_now < total_time)\n\t// {\n\t// \tgetDesiredTraj();\n\t\n\t// }\t// getCartControlLaw();\n\tif(controller_type ==0 )\n\t\tgetNewControlLaw();\n\telse if(controller_type ==1 || controller_type ==2)\n\t\tgetCartControlLaw();\n\tif(idsolver->CartToJnt(q_kdl,dq_kdl,v_kdl,fext,torque_kdl) < 0)\n\t\tROS_ERROR(\"KDL inverse dynamics solver failed.\");\t\t\n\tstd::cout << \"computed_torque: \" ; \n\tfor(unsigned int i=0;i < joint_size;i++)\n\t{\n\t\tstd::cout << torque_kdl(i) << \", \";\n\t\tcmd.command[i] = torque_kdl(i);\n\t}\t\t\n\tstd::cout << std::endl;\n right_cmd_pub.publish(cmd);\n\n // loop_rate.sleep();\t\t\n\tend_ = ros::WallTime::now();\n\tdouble time_last= time_now;\n\ttime_now = (end_ - start_).toSec();\n\tcount = count +1;\n\tROS_INFO(\"count: %d\", count);\n\tROS_INFO(\"time_now: %f\", time_now);\n\tROS_INFO(\"time_iteration: %f\", (time_now - time_last));\n\tcompileResults();\n\tresult_topic.publish(resultMsg);\n\tend_total = ros::WallTime::now();\n\ttime_now_total = (end_total - start_total).toSec();\n}\n\nvoid getMachineStates()\n{\n\t// machineStates = 0; // no operation, keep overall controller inactive\n\t// machineStates = 1; // start overall controller\n\t// machineStates = 2; // reset robot; \n\t// machineStates = 3; // do regulation; \n\t// machineStates = 4; // do traj control; \n\tif (!start_controller)\n\t\tmachineStates_now = 0;\n\telse \n\t{\n\t\tmachineStates_now = 1;\n\t\tif (reset_robot)\n\t\t\tmachineStates_now = 2;\n\t\telse if(regulation_control && !reset_robot && !traj_control)\n\t\t\tmachineStates_now = 3;\n\t\telse if(traj_control && !regulation_control && !reset_robot)\n\t\t\tmachineStates_now = 4;\t\t\n\t}\n}\n\n\t// reg_x = config.reg_x;\n\t// reg_theta_x = config.reg_theta_x;\n\t// reg_y = config.reg_y;\n\t// reg_theta_y = config.reg_theta_y;\n\t// reg_z = config.reg_z;\n\t// reg_theta_z = config.reg_theta_z;\n\nMatrix<double,8,1> getNewPose(Matrix<double,8,1> pose_past)\n{\n\tMatrix<double,8,1> pose_diff;\n\tQuaterniond q;\n\tq = AngleAxisd(reg_theta_x, Vector3d::UnitX())\n * AngleAxisd(reg_theta_y, Vector3d::UnitY())\n * AngleAxisd(reg_theta_z, Vector3d::UnitZ());\n RowVector4d rot, trans;\n rot << q.w(), q.x(), q.y(), q.z();\n trans << 0, reg_x, reg_y, reg_z;\n\tpose_diff = DQoperations::rotTrans2dq(rot, trans);\n\treturn DQoperations::mulDQ(pose_past, pose_diff); \n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"resolveAccControl\");\n\tros::NodeHandle node_;\n\n\tif (!initializeAccController(node_))\n\t{\n\t\tROS_ERROR(\"The acc controller can not be initialized.\");\t\n\t\treturn 0;\n\t}\n\tupdateManipulatorState();\n\tdynamic_reconfigure::Server<dq_robotics::kdl_controllerConfig> server;\n\tdynamic_reconfigure::Server<dq_robotics::kdl_controllerConfig>::CallbackType f;\n\tf = boost::bind(&dynReconfgr_callback, _1, _2);\n\tserver.setCallback(f);\t\t\n\tstart_controller =false;\n\twhile (!start_controller)\n\t{\n\t\tros::Duration(1.0).sleep();\n\t\tROS_INFO(\"waiting for controller to start...\");\n\t\tros::spinOnce();\n\t}\n\n\tint count = 0;\n\tROS_INFO(\"starting acceleration control\");\n\t// getDesiredTraj();\n\tif(controller_type ==0 )\n\t\tstd::cout << \"DQ based controller selected\" << std::endl;\n\telse if(controller_type ==1)\n\t\tstd::cout << \"KDL quaternion error based controller selected\" << std::endl;\n\telse if (controller_type ==2)\t\n\t\tstd::cout << \"KDL quaternion VECTOR error based controller selected\" << std::endl;\n\t\n\ttime_now_total = 0;\n\tstart_total = ros::WallTime::now();\n\tend_total = ros::WallTime::now();\n\tupdateTime();\n\t// getDesiredTraj();\t\n\tros::Rate r(200); // 10 hz\n\twhile (ros::ok())\n\t{\n\t\tros::spinOnce();\n\t\tgetMachineStates();\n\t\tstd::cout << \"machineStates_now: \" << machineStates_now << std::endl; \n\t\tif (machineStates_now != 0)\n\t\t{\n\t\t\tcrclCntr_dsrdTrajPose.pose = DQoperations::DQ2geometry_msgsPose(crclCntr_dsrdTraj_dq);\t\t\t\t\n\t\t\tcrclCntr_dsrdTrajPose.header.stamp = ros::Time::now();\n\t\t\tcrclCntr_pose_publisher.publish(crclCntr_dsrdTrajPose);\n\t\t\tupdateManipulatorState();\n\t\t\tif (machineStates_now == 2)\t\t\n\t\t\t{\n\t\t\t\tresetRobot();\n\t\t\t\tupdateTime();\t\t\t\t\n\t\t\t}\n\t\t\telse if (machineStates_now == 3)\n\t\t\t{\n\n\t\t\t\tacc_desired_right = MatrixXd::Zero(8, 1);\n\t\t\t\tvel_desired_right = MatrixXd::Zero(8, 1);\n\t\t\t\tMatrix<double,8,1> pose_init ;\n\t\t\t\tif (machineStates_past != 3 )\n\t\t\t\t{\n\t\t\t\t\tpose_init = pe_now_right;\n\t\t\t\t\tupdateTime();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpose_desired_right = getNewPose(pose_init);\n\t\t\t\tdesired_pose.pose = DQoperations::DQ2geometry_msgsPose(pose_desired_right);\n\t\t\t\tdesired_pose.header.stamp = ros::Time::now();\n\t\t\t\tpose_publisher.publish(desired_pose);\n\n\t\t\t\tdoTrajControl();\t\t\t\t\n\t\t\t}\n\t\t\telse if(machineStates_now == 4 && (time_now < total_time))\n\t\t\t{\n\t\t\t\tif (machineStates_past != 4 )\n\t\t\t\t{\n\t\t\t\t\tupdateTime();\n\t\t\t\t}\n\t\t\t\tgetDesiredTraj();\n\t\t\t\tdoTrajControl();\n\t\t\t\tdesired_pose.pose = DQoperations::DQ2geometry_msgsPose(pose_desired_right);\n\t\t\t\tdesired_pose.header.stamp = ros::Time::now();\n\t\t\t\tpose_publisher.publish(desired_pose);\t\t\t\t\n\t\t\t\tend_ = ros::WallTime::now();\n\t\t\t\ttime_now = (end_ - start_).toSec();\t\t\t\t\n\t\t\t}\t\n\t\t}\t\t\n\t\telse {updateTime();} \n\t\t// std::cout << \"reset_robot: \" << reset_robot << \"reset_controller: \" << reset_controller << std::endl;\t\n\t\t// reset_controller =false;\t\n\t\tros::spinOnce();\n\t\tmachineStates_past = machineStates_now;\n\t\tr.sleep();\n\t}\n\n\n\t// ROS_INFO(\"starting regulation now.\");\n\t// start_ = ros::WallTime::now();\n\t// end_ = ros::WallTime::now();\n\t// time_now = 0;\n\t// while (ros::ok())\n\t// {\n\t// \tupdateManipulatorState();\n\t// \t// getControlLaw_regulation();\n\t// \tgetControlLaw();\n\t// \tfor(unsigned int i=0;i < joint_size;i++)\n\t// \t{\n\t// \t\tq_kdl(i) = q_right(i);\n\t// \t\tdq_kdl(i) = q_vel_right(i);\n\t// \t\tv_kdl(i) = qdd_cmd(i);\n\t// \t}\n\t// \t// std::cout << \"q_kdl: \" < q_kdl.data << std::endl;\n\t// \tif(idsolver->CartToJnt(q_kdl,dq_kdl,v_kdl,fext,torque_kdl) < 0)\n\t// \t\tROS_ERROR(\"KDL inverse dynamics solver failed.\");\t\t\n\t// \tstd::cout << \"computed_torque: \" ; \n\t// \tfor(unsigned int i=0;i < joint_size;i++)\n\t// \t{\n\t// \t\tstd::cout << torque_kdl(i) << \", \";\n\t// \t\tcmd.command[i] = torque_kdl(i);\n\t// \t}\t\t\n\t// \tstd::cout << std::endl;\n\t// right_cmd_pub.publish(cmd);\n\t// ros::spinOnce();\n\t// // loop_rate.sleep();\t\t\n\t// \tend_ = ros::WallTime::now();\n\t// \ttime_now = (end_ - start_).toSec();\n\t// \tROS_INFO(\"time_now: %f\", time_now);\t\t\n\t// }\n\t// \tros::Duration(1.0).sleep();\n\t// \tros::Duration(1.0).sleep();\n\t// \tend_ = ros::WallTime::now();\n\n\t// // print results\n\t// \tdouble execution_time = (end_ - start_).toNSec() * 1e-6;\n\t// \tROS_INFO_STREAM(\"Exectution time (ms): \" << execution_time);\n\treturn 0;\n}\n\n\t// get current joint position and velocity\n\t// make your control law\n\t// \tget kp, kv and kd from dynamic reconfigure: done\n\t// \tget desired acc, vel and position..generate circular trajectory\n\t// \tget current position and velocity from the update_accControl thing you made\n\t// \tcompute control law like this\n\t// \t\tv.data=ddqr.data+Kp*(qr.data-q.data)+Kd*(dqr.data-dq.data);\n\t// \tget torque from kdl like this\n\t// \t\tif(idsolver->CartToJnt(q,dq,v,fext,torque) < 0)\n\t// \t ROS_ERROR(\"KDL inverse dynamics solver failed.\");\n\t// \tsend torque cmd. \n\t// repeat" }, { "alpha_fraction": 0.8025362491607666, "alphanum_fraction": 0.8103864789009094, "avg_line_length": 50.59375, "blob_id": "a98a70c29e47ded41bc50d84d2a5208462b3699e", "content_id": "942c266f1ab483d82db128c03a40b4116788e7fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1656, "license_type": "no_license", "max_line_length": 251, "num_lines": 32, "path": "/dq_robotics/README.md", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "# IFAC WC 2020\nAdd the package dq_robots in your catkin workspace and catkin_make your workspace. The package requires KDL and Eigen libraries and works with ROS INDIGO. The package was designed to work with Baxter robot in simulation as well as with the real robot.\n\nSteps to repeat the experiments :\n\n1. For real robot: Connect to the robot, and execute the commands from step 2 in the Baxter SDK environment. \n\nFor simulation: \n\nroslaunch baxter_gazebo baxter_world.launch\n\n2. Launch the robot parameters and controller parameters, rviz and dynamic reconfigure for gain adjustments.\n\nroslaunch dq_robotics baxterposeControlServer.launch\n\n3. Launch the controller node.\n\nrosrun dq_robotics resolved_acc_control\n\n4. Change the controller types from the drop-down menu at the bottom of the window of dynamic reconfigure. For decoupled controller select dq_controller, and for coupled select kdl_controller_quatVec.\n\n5. Adjust the gains and then click on reset_robot. Then click on start_controller. The right arm will move to the starting position.\n\n6. Click on traj_control and uncheck the reset_robot to start trajectory tracking.\n\n7. For data collection for performance computation of the controllers in terms of accuracy and time, subscribe to /dq_robotics/trajCntrlResults topic.\n\n8. The recorded data for /dq_robotics/trajCntrlResults topic can be converted to csv file using following command via rosbag or directly:\n\nrosrun dq_robotics result_analyzer_ResolcedAccControl\n\nThe csv file is store in dq_robotics/src/resolvedAccControl/result/ with the name specified in the cpp file src/resolvedAccControl/result_analyzer_ResolcedAccControl.cpp.\n\n\n\n\n\n" }, { "alpha_fraction": 0.7339075207710266, "alphanum_fraction": 0.7495467066764832, "avg_line_length": 36.70085525512695, "blob_id": "70b85476c3d2cd368bef709eb386276e2b2e0afd", "content_id": "c838fe8870d0a075eadc4526c772a409d7e4a54a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4412, "license_type": "no_license", "max_line_length": 225, "num_lines": 117, "path": "/dq_robotics/include/dq_robotics/ar10_kinematics.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#ifndef AR10_KINEMATICS_H\n#define AR10_KINEMATICS_H\n\n#define _USE_MATH_DEFINES\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <stdexcept> //for range_error\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n#include <complex>\n#include <cmath>\n#include <vector>\n#include <cstddef>\n#include <Eigen/SVD>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/dq_controller.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <cstdio>\n#include <tf2/LinearMath/Quaternion.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_msgs/MultiArrayDimension.h>\n#include <dq_robotics/IkHand.h>\n#include <ros/package.h>\n\nusing namespace Eigen;\n\nstruct slider_params\n{\n\tdouble b, c, init_displacement, total_displacement, total_sliderCmd, init_sliderCmd, current_sliderCmd, alpha, alpha_cal;\n};\t\n\nstruct four_bar_params\n{\n\tdouble p, qq, g, h, theta, alpha, psi, theta_init;\n};\n\nstruct finger_params\n{\n\tslider_params proximal_phalanx, middle_phalanx;\n\tfour_bar_params distal_phalanx;\n\tstd::vector<std::string> finger_joint_names, finger_frame_names;\n\tstd::vector<int> sliderOrderInjointState;\n\tstd::vector<double> slider_position_input, slider_position_output;\n\tstd::vector<RowVector3d> u, p;\n\tRowVectorXd q, q_init;\n\tMatrix<double,8,1> finger_ee_init, finger_ee_current, frame_planarBaseToBase, frame_rot0ToBase_init, frame_rot1ToBase_init, frame_rot2ToBase_init, frame_rot0ToBase_current, frame_rot1ToBase_current, frame_rot2ToBase_current;\n\tstd::vector<int> finger_joint_type;\n\tstd::vector<Matrix<double,8,1>> dq_frames_stack_init, dq_frames_stack_current;\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\tMatrixXd finger_jacobian_simple, finger_jacobian_coupled;\n\tstd::vector<int> joint_type;\n\tint joint_size;\n\tbool is_thumb;\n};\n\nclass AR10Kinematics\n{\n\tprivate:\n\t\tros::NodeHandle n;\n\t\tMatrix<double,8,1> frame_0, frame_1, frame_2, frame_3, frame_hand_base;\n\t\tfinger_params index_finger, thumb;\n\t\tros::Publisher right_ar10Hand_pub, left_ar10Hand_pub;\n\t\tros::Subscriber jointCmds_subscriber, fkm_subscriber;\n\t\tsensor_msgs::JointState right_hand_cmds, left_hand_cmds;\n\t\tfloat durationSleep;\n\t\tstd::string base_frame, result_file_name, path;\n\t tf2_ros::StaticTransformBroadcaster static_broadcaster;\n\t ros::ServiceServer finger_ik_service;\n\t double slider_cmd_tolerance, dt, Kp, mu;\n\t std::vector<geometry_msgs::TransformStamped> static_transformStamped_array;\n \tgeometry_msgs::TransformStamped hand_base_static_transformStamped;\n \tint joint_size_coupled;\n\t\tstd::vector<RowVectorXd> u_relative, p_relative;\n\t\tMatrix<double,8,1> ee_relative;\n\t\tRowVectorXd q_relative, q_init_relative;\n\n\t // std::ofstream result_file;\n \t\n\t\t//double b_1, c_1, s_1, b_2, c_2, s_2, a_3, b_3, g_3, h_3, theta_1_diff, theta_2_diff, theta_3_diff; \n\n\tpublic:\n\t\tAR10Kinematics();\n\t\t~AR10Kinematics();\t\t\n\t\tvoid init_AR10Kinematics();\n\t\tstatic void getThetaFromSlider(slider_params &sp);\n\t\tstatic void getAlphaFromTheta4Bar(four_bar_params &four_bar);\n\t\tstatic double getSliderFromTheta(slider_params sp);\n\t\tstd::vector<int> getSlidersList(std::vector<std::string> joint_names);\n\t\tbool get_index_param();\n\t\tbool getControllerParms();\n\t\tvoid init_fingers();\n\t\tvoid init_thumb();\n\t\tbool get_thumb_param();\n\t\tvoid init_index_finger();\n\t\tvoid init_index_finger_2();\n\t\tvoid getSliderPosition(finger_params &finger);\n\t\tvoid computeJointRotation(finger_params &finger);\n\t\tvoid fkmFinger(finger_params &finger);\n\t\tvoid Ar10KinematicsLoop();\n\t\tvoid Ar10KinematicsLoop_finger(finger_params &finger);\n\t\tvoid publishFramesAsTf(finger_params &finger, std::vector<geometry_msgs::TransformStamped> &static_transformStamped_array);\n\t\t// void fkmCallback(const sensor_msgs::JointState& msg);\n\t\tbool computeHandIKCallback(dq_robotics::IkHand::Request& hand_ik_req, \n\t\t\t\t\t\t\t\t\tdq_robotics::IkHand::Response& hand_ik_res);\n\t\tvoid getJacobianCoupled(finger_params &finger);\n\t\tvoid update_relative();\n\t\tbool ik_relative(dq_robotics::IkHand::Request hand_ik_req, dq_robotics::IkHand::Response &hand_ik_res);\n\t\tbool importHandState(std::string finger_name, Matrix<double,8,1>& pe_init, Matrix<double,8,1>& pe_now, MatrixXd& jacobian, RowVectorXd& q, RowVectorXd& q_init);\n\t\tbool updateFingerVariables(std::string finger_name);\n\t\tvoid init_AR10IKService();\n\t\tbool sendJointCmds_AR10(std::vector<double> jointCmds, std::string fingerName);\n\t// int joint_size;\n};\n#endif\n\n" }, { "alpha_fraction": 0.6076254844665527, "alphanum_fraction": 0.6336872577667236, "avg_line_length": 41.306121826171875, "blob_id": "2503a43734b0bc1a28821c9fd028688209c08b63", "content_id": "84b81a20f62a8021b6cf314e633f9bef9a272e82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2072, "license_type": "no_license", "max_line_length": 814, "num_lines": 49, "path": "/dq_robotics/src/test/bag2csv_BaxterControl.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n#include <dq_robotics/Grasp.h>\n#include <dq_robotics/BaxterControl.h>\n#include <dq_robotics/ControllerPerformance.h>\n \nstd::string path;\n\nfloat64[] desiredRelPose # this can be relative desire pose\nfloat64[] desiredAbsPose # this can be relative desire pose\nfloat64[] currentRelPose # this can be relative desire pose\nfloat64[] currentAbsPose # this can be relative desire pose\nfloat64[] joint_state_left # this can be relative desire pose\nfloat64[] joint_state_right # this can be relative desire pose\nfloat64[] del_q # this can be relative desire pose\nfloat64 norm_error_abs\nfloat64 norm_error_rel\nfloat64 timeStamp\nint32 controlMode\n\nvoid chatterCallback(const dq_robotics::ControllerPerformance::ConstPtr& msg)\n{\n if(result_file.is_open())\n {\n std::cout << \"file is open\" << std::endl;\n }\n\n result_file << \"time\" << \",\" << \"desiredRelPose_0\" << \",\" << \"desiredRelPose_1\" << \",\" << \"desiredRelPose_2\" << \",\" << \"desiredRelPose_3\" << \",\" << \"desiredRelPose_4\" << \",\" << \"desiredRelPose_5\" << \",\" << \"desiredRelPose_6\" << \",\" << \"desiredRelPose_7\" << \",\" << \"currentRelPose_0\" << \",\" << \"currentRelPose_1\" << \",\" << \"currentRelPose_2\" << \",\" << \"currentRelPose_3\" << \",\" << \"currentRelPose_4\" << \",\" << \"currentRelPose_5\" << \",\" << \"currentRelPose_6\" << \",\" << \"currentRelPose_7\" << \",\" << \"desiredAbsPose_0\" << \",\" << \"desiredAbsPose_1\" << \",\" << \"desiredAbsPose_2\" << \",\" << \"desiredAbsPose_3\" << \",\" << \"desiredAbsPose_4\" << \",\" << \"desiredAbsPose_5\" << \",\" << \"desiredAbsPose_6\" << \",\" << \"desiredAbsPose_7\" << \",\" << \"norm_error_rel\" << \",\" << \"norm_error_abs\" << \", \\n\";\n}\n\nint main(int argc, char **argv)\n{\n\n ros::init(argc, argv, \"listener\");\n\n\n ros::NodeHandle n;\n\n std::string path = ros::package::getPath(\"dq_robotics\");\n path.append(\"/results/\");\n path.append(\"1.csv\");\n std::ofstream result_file(path, std::ios::app);\n ros::Subscriber sub = n.subscribe(\"chatter\", 1000, chatterCallback);\n\n\n ros::spin();\n\n return 0;\n}" }, { "alpha_fraction": 0.6749435663223267, "alphanum_fraction": 0.690744936466217, "avg_line_length": 23.66666603088379, "blob_id": "759fa0e894556c473692eb9415c35aedf40b9c18", "content_id": "c586f367a3e655474899b4b84bd5216d98cca686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 443, "license_type": "no_license", "max_line_length": 123, "num_lines": 18, "path": "/dq_robotics/src/resolvedAccControl/disable_gravity_baxSDK.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include <std_msgs/Empty.h>\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"disble_gravityFromBaxSDK\");\n\tros::NodeHandle n;\n\tstd_msgs::Empty myMsg;\n\tros::Rate loop_rate(10);\n\tros::Publisher disble_gravity_pub = n.advertise<std_msgs::Empty>(\"/robot/limb/right/suppress_gravity_compensation\", 1000);\n\twhile(ros::ok())\n\t{\n\t\tdisble_gravity_pub.publish(myMsg);\n\t\tloop_rate.sleep();\n\t\tros::spinOnce();\n\t}\n\treturn 0;\n}" }, { "alpha_fraction": 0.7564972043037415, "alphanum_fraction": 0.7774011492729187, "avg_line_length": 58.03333282470703, "blob_id": "c18c0f0769c39ce38aebe808af2dea82d84e6702", "content_id": "6bb14b240b546ce8e501ee97258f553f5ffe5ea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1770, "license_type": "no_license", "max_line_length": 350, "num_lines": 30, "path": "/dq_robotics/include/dq_robotics/dq_controller.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#ifndef DQController_H\n#define DQController_H\n\n#include <dq_robotics/DQoperations.h>\n#include <dq_robotics/baxter_dq.h>\n#include <sensor_msgs/JointState.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <math.h>\n\nclass DQController\n{\n\npublic:\n\tstatic std::vector<Matrix<double,8,1> > fkmDual(std::vector<RowVector3d> u,std::vector<RowVector3d> p, RowVectorXd q, std::vector<int> joint_type);\n\tstatic MatrixXd jacobianDual(std::vector<RowVector3d> u, std::vector<RowVector3d> p, Matrix<double,8,1> pe_init, std::vector<int> joint_type, std::vector<Matrix<double,8,1> > fkm_current);\n\tstatic MatrixXd jacobianDual_8d(int joint_size, MatrixXd jacobian);\n\t// void getDQderivative();\n\tstatic RowVectorXd getScrewError_8d(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_desired);\n\tstatic RowVectorXd calculateControlVel(double Kp, double mu, RowVectorXd screwError_8d, MatrixXd jacobian_8d, int joint_size);\n\tstatic RowVectorXd calculateControlVel_velcityFF(double Kp, double mu, RowVectorXd screwError_8d, MatrixXd jacobian_8d, int joint_size, Matrix<double,8,1> cart_velocity_desired);\n\tstatic RowVectorXd normalizeControlVelocity( RowVectorXd q_dot, std::vector<double> joint_velocity_limit);\n\tstatic RowVectorXd jointVelocity4velocityControl(double Kp, double mu, std::vector<RowVector3d> u, std::vector<RowVector3d> p, Matrix<double,8,1> pose_now, Matrix<double,8,1> pe_init, std::vector<int> joint_type, Matrix<double,8,1> pose_desired, Matrix<double,8,1> cart_vel_desired, std::vector<Matrix<double,8,1> > fkm_matrix, double& norm_error);\n\tstatic MatrixXd linkVelocites(MatrixXd jacobian_6d, RowVectorXd joint_velocities);\n\tstatic MatrixXd getJacobianDot(MatrixXd link_velocity, MatrixXd jacobain_6d);\n\tDQController();\n\t~DQController();\n};\n#endif" }, { "alpha_fraction": 0.6213496923446655, "alphanum_fraction": 0.6425442695617676, "avg_line_length": 48.085105895996094, "blob_id": "f96e8af3edead957208e43d5866b74caf0bf88d8", "content_id": "89d9df77e0baf9329dcac97e14a52c3c02547ea5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 43832, "license_type": "no_license", "max_line_length": 245, "num_lines": 893, "path": "/dq_robotics/src/baxter_AbsRelative_Control.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n#include <dq_robotics/Grasp.h>\n#include <dq_robotics/BaxterControl.h>\n#include <dq_robotics/ControllerPerformance.h>\n// #include <baxter_trajectory_interface/baxter_poseControl_server.h>\n#define PI 3.14159265\n\ndouble mu, Kp, K_jl, Kp_position, K_jl_position, sleepTimeout, dt, timeStep, norm_error_const, time_start;\nMatrix<double,8,1> pe_init_baxterRight, pe_now_baxterRight, pe_init_baxterLeft, pe_now_baxterLeft, pe_init_thumbRight, pe_init_indexRight, pe_now_thumbRight, pe_now_indexRight, pe_desired_thumb, pe_desired_index, tf_rightHand2handBase, p_abs_2;\nMatrixXd jacobian_baxterRight, jacobian_baxterLeft, jacobian_thumbRight, jacobian_indexRight;\nRowVectorXd q_baxterRight, q_baxterLeft, q_thumbRight, q_indexRight, q_init_thumbRight, q_init_indexRight;\nstd::vector<double> joint_velocity_limit_baxterRight, joint_velocity_limit_baxterLeft, joint_velocity_limit_baxter;\nBaxterPoseControlServer* baxter_controller;\nAR10Kinematics* ar10;\nMatrix<double,8,1> tfRight_baxterBase2handBase;\nMatrix<double,8,1> p_right_stick, p_left_stick, p_rel_stick;\nros::Publisher result_topics;\ndq_robotics::ControllerPerformance resultMsg;\nbool getControllerParams()\n{\n\tp_abs_2 << 1, 0, 0, 0, 0, 0, 0, 0 ;\n\tstd::string paramName=\"Kp\";\n\tif(!ros::param::get(paramName, Kp))\n\t{\n\t\tstd::cout << \"controller param Kp not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"Kp_position\";\n\tif(!ros::param::get(paramName, Kp_position))\n\t{\n\t\tstd::cout << \"controller param Kp_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"timeStep\";\n\tif(!ros::param::get(paramName, timeStep))\n\t{\n\t\tstd::cout << \"controller param timeStep not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl\";\n\tif(!ros::param::get(paramName, K_jl))\n\t{\n\t\tstd::cout << \"controller param K_jl not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl_position\";\n\tif(!ros::param::get(paramName, K_jl_position))\n\t{\n\t\tstd::cout << \"controller param K_jl_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"mu\";\n\tif(!ros::param::get(paramName, mu))\n\t{\n\t\tstd::cout << \"controller param mu not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"sleepTimeout\";\n\tif(!ros::param::get(paramName, sleepTimeout))\n\t{\n\t\tstd::cout << \"controller param sleepTimeout not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"norm_error_const\";\n\tif(!ros::param::get(paramName, norm_error_const))\n\t{\n\t\tstd::cout << \"controller param norm_error_const not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tROS_INFO(\"Controller parameters loaded\");\n\treturn 1;\n}\n\n\nMatrixXd getJointLimitJacobian(RowVectorXd q, std::vector<double> upper_limit_ordered, std::vector<double> low_limit_ordered, double fraction)\n{\n\tint noOfJoints=q.size();\n\tMatrixXd joint_limit_jacobian=MatrixXd::Zero(noOfJoints, noOfJoints);\n\t// joint_limit_jacobian.resize(noOfJoints);\n\tdouble max_safe, min_safe;\n\tfor (int i=0; i <noOfJoints; i++)\n\t{\n\t\tmax_safe=upper_limit_ordered[i]- (upper_limit_ordered[i]- low_limit_ordered[i])*fraction;\n\t\tmin_safe=low_limit_ordered[i] + (upper_limit_ordered[i]- low_limit_ordered[i])*fraction;\n\t\tif(q(i)>=max_safe)\n\t\t\tjoint_limit_jacobian(i,i)=(q(i)-max_safe)*(2*upper_limit_ordered[i]-max_safe-q(i))/((upper_limit_ordered[i]-q(i))*(upper_limit_ordered[i]-q(i)));\n\t\telse if(q(i)<min_safe)\n\t\t\tjoint_limit_jacobian(i,i)=(min_safe-q(i))*(2*low_limit_ordered[i]- q(i) -min_safe)/((q(i) - low_limit_ordered[i])*(q(i) - low_limit_ordered[i]));\n\t\telse\n\t\t\tjoint_limit_jacobian(i,i)=0;\t\t\n\t}\n\treturn joint_limit_jacobian;\n\n}\n\n\nbool update_baxter()\n{\n\t// ros::WallTime updateRIght_time_start = ros::WallTime::now();\n\tif(baxter_controller->BaxterPoseControlServer::updateManipulatorVariables(\"all\"))\n\t{\n\t\tif(baxter_controller->BaxterPoseControlServer::importManipulatorState(\"right\", pe_init_baxterRight, pe_now_baxterRight, jacobian_baxterRight, q_baxterRight, joint_velocity_limit_baxterRight))\n\t\t{\n\t\t\tif(baxter_controller->BaxterPoseControlServer::importManipulatorState(\"left\", pe_init_baxterLeft, pe_now_baxterLeft, jacobian_baxterLeft, q_baxterLeft, joint_velocity_limit_baxterLeft))\n\t\t\t{\n\t\t\t\t// ros::WallTime updateRIght_time_end = ros::WallTime::now();\n\t\t\t\t// ros::WallDuration updateRIght_time_dur = updateRIght_time_end - updateRIght_time_start;\n\t\t\t\t// std::cout << \"updateRIght duration_server: \" << updateRIght_time_dur.toSec() << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\t\t// std::cout << \"Here 4\" << std::endl;\n\n\t// \tif(baxter_controller->BaxterPoseControlServer::importManipulatorState(\"right\", pe_init_baxterRight, pe_now_baxterRight, jacobian_baxterRight, q_baxterRight, joint_velocity_limit_baxterRight))\n\t// \t{\n\t// \t\tros::WallTime updateLeft_time_start = ros::WallTime::now();\n\t// \t\tif(baxter_controller->BaxterPoseControlServer::updateManipulatorVariables(\"left\"))\n\t// \t\t{\n\t// \t\t\tros::WallTime updateLeft_time_end = ros::WallTime::now();\n\t// \t\t\tros::WallDuration updateLeft_time_dur = updateLeft_time_end - updateLeft_time_start;\n\t// \t\t\tstd::cout << \"updateLeft duration_server: \" << updateLeft_time_dur.toSec() << std::endl;\t\t\n\t// \t\t\tif(baxter_controller->BaxterPoseControlServer::importManipulatorState(\"left\", pe_init_baxterLeft, pe_now_baxterLeft, jacobian_baxterLeft, q_baxterLeft, joint_velocity_limit_baxterLeft))\n\t// \t\t\t\treturn 1;\n\t// \t\t\telse\n\t// \t\t\t{\n\t// \t\t\t\tstd::cout << \"cannot get left arm state\" << std::endl;\n\t// \t\t\t\treturn 0;\n\t// \t\t\t}\n\t// \t\t}\n\t// \t\telse\n\t// \t\t{\n\t// \t\t\tstd::cout << \"cannot update left arm \" << std::endl;\n\t// \t\t\treturn 0;\n\t// \t\t}\t\t\t\t\n\t// \t}\n\t// \telse\n\t// \t{\n\t// \t\tstd::cout << \"cannot get right arm state\" << std::endl;\n\t// \t\treturn 0;\n\t// \t}\n\t// }\n\t// else\n\t// {\n\t// \tstd::cout << \"cannot update left arm\" << std::endl;\n\t// \treturn 0;\n\t// }\n}\n\nMatrixXd relativeJacobian_inAbsFrame(MatrixXd jacobian_ref, MatrixXd jacobian_tool, Matrix<double,8,1> absPose_baseFrame)\n{\n\t// ROS_INFO(\"here 23\");\n\tMatrixXd relJacobian, relJacobian_8d, jacobian_6d;\n\trelJacobian = MatrixXd::Zero(6, (jacobian_ref.cols() + jacobian_tool.cols()));\n\trelJacobian_8d = MatrixXd::Zero(8, (jacobian_ref.cols() + jacobian_tool.cols()));\n\tjacobian_6d = MatrixXd::Zero(6, jacobian_ref.cols());\n\tjacobian_6d.block(0, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(5, 0, 3, jacobian_ref.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(1, 0, 3, jacobian_ref.cols());\n\n\tMatrix<double,8,1> line_transform_tf = DQoperations::classicConjDQ(absPose_baseFrame);\n\tfor (int i = 0; i < (jacobian_ref.cols()); i++)\n\t{\n\t\t// std::cout << \"before transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\n\t\trelJacobian.col(i) << -DQoperations::transformLine6dVector(jacobian_6d.col(i).transpose(), line_transform_tf).transpose();\n\t\t// std::cout << relJacobian.col(i).transpose() << std::endl;\t\t\n\t\t// relJacobian.col(i + jacobian_ref.cols()) = DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref));\n\t}\n\t// ROS_INFO(\"here 25\");\n\tjacobian_6d.block(0, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(5, 0, 3, jacobian_tool.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(1, 0, 3, jacobian_tool.cols());\t\n\t// ROS_INFO(\"here 26\");\n\tfor (int i = 0; i < (jacobian_tool.cols()); i++)\n\t{\n\t\t// std::cout << \"before transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\t\t\n\t\trelJacobian.col(i+jacobian_ref.cols()) = DQoperations::transformLine6dVector(jacobian_6d.col(i).transpose(), line_transform_tf).transpose();\n\t\t// std::cout << \"after transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\n\t\t// std::cout << relJacobian.col(i+jacobian_ref.cols()).transpose() << std::endl;\t\t\n\t}\n\n\trelJacobian_8d = DQController::jacobianDual_8d((jacobian_ref.cols() + jacobian_tool.cols()), relJacobian);\n\trelJacobian = relJacobian_8d;\n\trelJacobian_8d.block(0, 0, 4, relJacobian.cols()) = relJacobian.block(4, 0, 4, relJacobian.cols());\n\trelJacobian_8d.block(4, 0, 4, relJacobian.cols()) = relJacobian.block(0, 0, 4, relJacobian.cols()) ; \n\t\t// std::cout << \"relJacobian_8d: \" << std::endl;\n\t\t// std::cout << relJacobian_8d << std::endl;\t\n\t// ROS_INFO(\"here 27\");\n\treturn relJacobian_8d;\n}\n\n\n\n\nMatrixXd relativeJacobian(MatrixXd jacobian_ref, MatrixXd jacobian_tool, Matrix<double,8,1> p_ee_ref, Matrix<double,8,1> p_ee_tool)\n{\n\t// ROS_INFO(\"here 23\");\n\tMatrixXd relJacobian, relJacobian_8d, jacobian_6d;\n\trelJacobian = MatrixXd::Zero(6, (jacobian_ref.cols() + jacobian_tool.cols()));\n\trelJacobian_8d = MatrixXd::Zero(8, (jacobian_ref.cols() + jacobian_tool.cols()));\n\tjacobian_6d = MatrixXd::Zero(6, jacobian_ref.cols());\n\tjacobian_6d.block(0, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(5, 0, 3, jacobian_ref.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(1, 0, 3, jacobian_ref.cols());\n\t// RowVector3d p_rel;\n\n\t// Matrix4d pose_ref = DQoperations::dq2HTM(p_ee_ref);\n\t// Matrix4d pose_tool = DQoperations::dq2HTM(p_ee_tool);\n\t// p_rel << (pose_ref(0,3) - pose_tool(0,3)), (pose_ref(1,3) - pose_tool(1,3)), (pose_ref(2,3) - pose_tool(2,3));\n\t// ROS_INFO(\"here 24\");\n\t\n\t// std::cout << \"relJacobian: \" << std::endl;\n\tfor (int i = 0; i < (jacobian_ref.cols()); i++)\n\t{\n\t\t// std::cout << \"before transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\n\t\trelJacobian.col(i) << -DQoperations::transformLine6dVector(jacobian_6d.col(i).transpose(), DQoperations::classicConjDQ(p_ee_ref)).transpose();\n\t\t// std::cout << relJacobian.col(i).transpose() << std::endl;\t\t\n\t\t// relJacobian.col(i + jacobian_ref.cols()) = DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref));\n\t}\n\t// ROS_INFO(\"here 25\");\n\tjacobian_6d.block(0, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(5, 0, 3, jacobian_tool.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(1, 0, 3, jacobian_tool.cols());\t\n\t// ROS_INFO(\"here 26\");\n\tfor (int i = 0; i < (jacobian_tool.cols()); i++)\n\t{\n\t\t// std::cout << \"before transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\t\t\n\t\trelJacobian.col(i+jacobian_ref.cols()) = DQoperations::transformLine6dVector(jacobian_6d.col(i).transpose(), DQoperations::classicConjDQ(p_ee_ref)).transpose();\n\t\t// std::cout << \"after transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\n\t\t// std::cout << relJacobian.col(i+jacobian_ref.cols()).transpose() << std::endl;\t\t\n\t}\n\n\trelJacobian_8d = DQController::jacobianDual_8d((jacobian_ref.cols() + jacobian_tool.cols()), relJacobian);\n\trelJacobian = relJacobian_8d;\n\trelJacobian_8d.block(0, 0, 4, relJacobian.cols()) = relJacobian.block(4, 0, 4, relJacobian.cols());\n\trelJacobian_8d.block(4, 0, 4, relJacobian.cols()) = relJacobian.block(0, 0, 4, relJacobian.cols()) ; \n\t\t// std::cout << \"relJacobian_8d: \" << std::endl;\n\t\t// std::cout << relJacobian_8d << std::endl;\t\n\t// ROS_INFO(\"here 27\");\n\treturn relJacobian_8d;\n}\n\nMatrixXd absoluteJacobian(MatrixXd jacobian_ref, MatrixXd jacobian_tool, Matrix<double,8,1> p_ee_ref, Matrix<double,8,1> p_ee_tool)\n{\n\tMatrixXd absJacobian, absJacobian_8d, jacobian_6d;\n\tabsJacobian = MatrixXd::Zero(6, (jacobian_ref.cols() + jacobian_tool.cols()));\n\tabsJacobian_8d = MatrixXd::Zero(8, (jacobian_ref.cols() + jacobian_tool.cols()));\n\tjacobian_6d = MatrixXd::Zero(6, jacobian_ref.cols());\n\t// ROS_INFO(\"here 8\");\n\tjacobian_6d.block(0, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(1, 0, 3, jacobian_ref.cols());\n\t// ROS_INFO(\"here 9\");\t\n\tjacobian_6d.block(3, 0, 3, jacobian_ref.cols()) = jacobian_ref.block(5, 0, 3, jacobian_ref.cols());\n\t\t// std::cout << \"jacobian_6d_ref: \" << std::endl;\n\t\t// std::cout << jacobian_6d << std::endl;\t\t\n\tRowVector3d p_rel;\n\n\tMatrix4d pose_ref = DQoperations::dq2HTM(p_ee_ref);\n\tMatrix4d pose_tool = DQoperations::dq2HTM(p_ee_tool);\n\tp_rel << (pose_ref(0,3) - pose_tool(0,3)), (pose_ref(1,3) - pose_tool(1,3)), (pose_ref(2,3) - pose_tool(2,3));\n\t// ROS_INFO(\"here 10\");\t\n\tfor (int i = 0; i < jacobian_ref.cols(); i++)\n\t{\n\t\tRowVector3d vec = ((jacobian_ref.col(i)).tail(3)).transpose();\n\t\tvec = vec.cross(p_rel);\n\t\tabsJacobian.col(i) << (((jacobian_6d.col(i)).head(3))/2 + vec.transpose()/4), ((jacobian_6d.col(i)).tail(3))/2;\n\t}\n\t// ROS_INFO(\"here 11\");\t\n\tjacobian_6d = MatrixXd::Zero(6, jacobian_tool.cols());\n\tjacobian_6d.block(0, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(1, 0, 3, jacobian_tool.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_tool.cols()) = jacobian_tool.block(5, 0, 3, jacobian_tool.cols());\t\n\t// std::cout << \"jacobian_6d_tool: \" << std::endl;\n\t// std::cout << jacobian_6d << std::endl;\t\t\n// ROS_INFO(\"here 12\");\t\n\tfor (int i = 0; i < jacobian_tool.cols(); i++)\n\t{\n\t\tRowVector3d vec= ((jacobian_tool.col(i)).tail(3)).transpose(); \n\t\tvec = vec.cross(-p_rel);\t\t\n\t\t// std::cout << \"vec: \" << (((jacobian_6d.col(i)).head(3)).transpose())/2 << std::endl;\n\t\t// std::cout << \"vec: \" << (((jacobian_6d.col(i)).tail(3))/2 + vec.transpose()/4).transpose() << std::endl;\n\t\tRowVectorXd tem_vec1, tem_vec2, tem_vec;\n\t\ttem_vec1 = (((jacobian_6d.col(i)).tail(3)).transpose())/2 ;\n\t\ttem_vec2 = (((jacobian_6d.col(i)).head(3))/2 + vec.transpose()/4).transpose();\n\t\t// std::cout << \"tem_vec1: \" << tem_vec1 << std::endl;\t\t\n\t\t// std::cout << \"tem_vec2: \" << tem_vec2 << std::endl;\t\t\n\t\t// tem_vec << (((jacobian_6d.col(i)).head(3)))/2, (((jacobian_6d.col(i)).tail(3))/2 + vec.transpose()/4).transpose();\n\t\ttem_vec = RowVectorXd::Zero(6);\n\t\ttem_vec << tem_vec2, tem_vec1;\n\t\t// std::cout << \"tem_vec: \" << tem_vec << std::endl;\t\t\n\t\tabsJacobian.col(i+jacobian_ref.cols()) << tem_vec.transpose();\n\t\t// std::cout << \"absJacobian.col(\" << (i+jacobian_ref.cols()) << \"):\" << std::endl;\n\t\t// std::cout << absJacobian.col(i+jacobian_ref.cols()) << std::endl;\n\t}\n\t// ROS_INFO(\"here 12\");\t\n\t// \tstd::cout << \"absJacobian: \" << std::endl;\n\t// \tstd::cout << absJacobian << std::endl;\t\n\tabsJacobian_8d = DQController::jacobianDual_8d(absJacobian.cols(), absJacobian);\n\t// ROS_INFO(\"here 13\");\t\t\n\t\t// std::cout << \"absJacobian_8d: \" << std::endl;\n\t\t// std::cout << absJacobian_8d << std::endl;\n\treturn absJacobian_8d;\n}\n\n// void getRelPosesFromAbsolute(Matrix<double,8,1> dq, Matrix<double,8,1> p_ee_r_1, Matrix<double,8,1> p_ee_t_1, Matrix<double,8,1> p_ee_r_2, Matrix<double,8,1> p_ee_t_2)\n// {\n// \tdouble theta_rel, d_rel;\n// \tRowVector3d l_rel, m_rel;\n// \tMatrix<double,8,1> p_ee_halfRot_1, p_ee_halfRot_2;\n// \tp_ee_halfRot << 1, 0, 0, 0, 0, 0, 0, 0 ;\n// \tRowVector4d q_abs_rot, q_abs_trans, q_abs_rot_2, q_abs_trans_2; \n// \tp_rel = dq;\n// \tRowVector4d trans, rot, trans_pos, trans_neg;\n// \tDQoperations::dq2rotAndTransQuat(dq, rot, trans);\n// \ttrans_pos = trans/2;\n// \ttrans_neg = -trans/2;\n// \tstd::cout << \"p_rel: \" << p_rel.transpose() << std::endl;\t\n\n\n// \tif (p_rel(0,0) < 0 )\n// \t{\n// \t\tp_rel = -p_rel;\n// \t}\n// \tif(p_rel(0,0) > 0.9995)\n// \t{\n// \t\tp_rel << 1, 0, 0, 0, p_rel(4,0), p_rel(5,0), p_rel(6,0), p_rel(7,0);\n// \t\tstd::cout << \"relative orientation is UNITY\" << std::endl;\n// \t\tstd::cout << \"p_rel: \" << p_rel.transpose() << std::endl;\n// \t}\n// \telse \t\n// \t{\n// \t\tDQoperations::dq2screw(p_rel, theta_rel, d_rel, l_rel, m_rel); \n// \t\tstd::cout << \"constructing abs rot::\" << std::endl;\n// \t\tp_ee_halfRot_1 = DQoperations::screw2DQ(theta_rel/2, l_rel, 0, m_rel);\n// \t\tp_ee_halfRot_2 = DQoperations::screw2DQ(theta_rel/2, -l_rel, 0, m_rel);\n// \t\tstd::cout << \"p_ee_halfRot_1: \" << p_ee_halfRot.transpose() << std::endl;\n// \t\tstd::cout << \"p_ee_halfRot_2: \" << p_abs_2.transpose() << std::endl;\n// \t\tstd::cout << \"theta_rel/2: \" << theta_rel/2 << std::endl;\n// \t\tstd::cout << \"l_rel: \" << l_rel << std::endl;\n// \t\tstd::cout << \"m_rel: \" << m_rel << std::endl;\n// \t\tstd::cout << \"d_rel: \" << d_rel << std::endl;\n// \t}\t\t\n// \tRowVector4d rot_temp;\n// \trot_temp << p_ee_halfRot_1(0,0), p_ee_halfRot_1(1,0), p_ee_halfRot_1(2,0), p_ee_halfRot_1(3,0);\n// \tstd::cout << \"rot_temp: \" << rot_temp << std::endl;\n// \tp_ee_r_1 = DQoperations::rotTrans2dq(rot_temp, trans);\n\n// }\n\nvoid getAbsoluteRelativePose(Matrix<double,8,1> p_ee_r, Matrix<double,8,1> p_ee_t, Matrix<double,8,1> &p_abs, Matrix<double,8,1> &p_rel)\n{\n\t// std::cout << \"getAbsoluteRelativePose coming through\" << std::endl;\n\t// std::cout << \"p_ee_r: \" << p_ee_r.transpose() << std::endl;\n\t// std::cout << \"p_ee_t: \" << p_ee_t.transpose() << std::endl;\n\tdouble theta_rel, d_rel;\n\tRowVector3d l_rel, m_rel;\n\tMatrix<double,8,1> p_ee_halfRot;\n\tp_ee_halfRot << 1, 0, 0, 0, 0, 0, 0, 0 ;\n\tRowVector4d q_abs_rot, q_abs_trans, q_abs_rot_2, q_abs_trans_2; \n\tp_rel = DQoperations::mulDQ(DQoperations::classicConjDQ(p_ee_r), p_ee_t);\n\n\t// std::cout << \"p_rel: \" << p_rel.transpose() << std::endl;\t\n\n\t// if (l_rel(0) < 0 && fabs(theta_rel/2) < 1.56 )\n\t// {\n\t// \tstd::cout << \"hacking here_1\" << std::endl;\n\t// \tl_rel = - l_rel;\n\t// \ttheta_rel = - theta_rel;\n\t// }\n\t// else \t\n\tif (p_rel(0,0) < 0 )\n\t{\n\t\tp_rel = -p_rel;\n\t}\n\tif(p_rel(0,0) > 0.9995)\n\t{\n\t\tp_rel << 1, 0, 0, 0, p_rel(4,0), p_rel(5,0), p_rel(6,0), p_rel(7,0);\n\t\t// std::cout << \"relative orientation is UNITY\" << std::endl;\n\t\t// std::cout << \"p_rel: \" << p_rel.transpose() << std::endl;\n\t}\n\telse \t\n\t{\n\t\tDQoperations::dq2screw(p_rel, theta_rel, d_rel, l_rel, m_rel); \n\t\t// if (l_rel(0) < 0)\n\t\t// {\n\t\t// \tstd::cout << \"hacking here_2\" << std::endl;\n\t\t// \tl_rel = - l_rel;\n\t\t// \ttheta_rel = - theta_rel;\n\t\t// }\n\t\t// if (fabs(theta_rel/2) > 1.55 && fabs(theta_rel/2) < 1.58 )\n\t\t// {\n\t\t// // if (theta_rel/2 < 0)\n\t\t// // \ttheta_rel = - M_PI;\n\t\t// // else\n\t\t// \ttheta_rel = M_PI;\n\t\t// }\n\t\tstd::cout << \"constructing abs rot::\" << std::endl;\n\t\tp_ee_halfRot = DQoperations::screw2DQ(theta_rel/2, l_rel, 0, m_rel);\n\t\tp_abs_2 = DQoperations::screw2DQ(theta_rel/2, -l_rel, 0, m_rel);\n\t\t// std::cout << \"p_ee_halfRot: \" << p_ee_halfRot.transpose() << std::endl;\n\t\t// std::cout << \"p_ee_halfRot_2: \" << p_abs_2.transpose() << std::endl;\n\t\t// std::cout << \"theta_rel/2: \" << theta_rel/2 << std::endl;\n\t\t// std::cout << \"l_rel: \" << l_rel << std::endl;\n\t\t// std::cout << \"m_rel: \" << m_rel << std::endl;\n\t\t// std::cout << \"d_rel: \" << d_rel << std::endl;\n\t}\t\t\n\n\n\t// if((theta_rel/2 > 1.56) && (theta_rel/2 < 1.58) && (l_rel(0) < 0))\n\t// {\n\t// \tstd::cout << \"hacking here\" << std::endl;\n\t// \t// theta_rel = - theta_rel;\n\t// \tl_rel = -l_rel;\n\t// \tstd::cout << \"theta_rel/2: \" << theta_rel/2 << std::endl;\n\t// \tstd::cout << \"l_rel: \" << l_rel << std::endl;\t\t\n\t// }\n\t// p_ee_halfRot = DQoperations::screw2DQ(theta_rel/2, l_rel, 0, m_rel);\n\n\t// std::cout << \"p_ee_r.head(4): \" << p_ee_r.head(4) << std::endl;\t\n\tq_abs_rot = DQoperations::multQuat( p_ee_r.head(4), p_ee_halfRot.head(4));\n\tq_abs_rot_2 = DQoperations::multQuat( p_ee_r.head(4), p_abs_2.head(4));\n\t\n\t// std::cout << \"q_abs_rot: \" << q_abs_rot << std::endl;\t\n\t// std::cout << \"q_abs_rot_2: \" << q_abs_rot_2 << std::endl;\t\n\t// std::cout << DQoperations::multQuat(DQoperations::conjQuat(p_ee_r.head(4)), q_abs_rot) << std::endl;\t\t\n\t// std::cout << \"q_abs_from_t: \" << std::endl;\t\n\t// std::cout << DQoperations::conjQuat(DQoperations::multQuat(DQoperations::conjQuat(p_ee_t.head(4)), q_abs_rot)) << std::endl;\t\t\t\n\n\tq_abs_trans = DQoperations::multQuat((DQoperations::multQuat(p_ee_r.tail(4), DQoperations::conjQuat(p_ee_r.head(4))) + DQoperations::multQuat(p_ee_t.tail(4), DQoperations::conjQuat(p_ee_t.head(4)))), q_abs_rot)/2;\n\tq_abs_trans_2 = DQoperations::multQuat((DQoperations::multQuat(p_ee_r.tail(4), DQoperations::conjQuat(p_ee_r.head(4))) + DQoperations::multQuat(p_ee_t.tail(4), DQoperations::conjQuat(p_ee_t.head(4)))), q_abs_rot_2)/2;\n\t// std::cout << \"q_abs_trans: \" << std::endl;\t\n\t// std::cout << q_abs_trans << std::endl;\t\n\t// std::cout << \"q_abs_rot: \" << std::endl;\t\n\t// std::cout << q_abs_rot << std::endl;\t\t\n\tp_abs << q_abs_rot(0), q_abs_rot(1), q_abs_rot(2), q_abs_rot(3), q_abs_trans(0), q_abs_trans(1), q_abs_trans(2), q_abs_trans(3);\n\tp_abs_2 << q_abs_rot_2(0), q_abs_rot_2(1), q_abs_rot_2(2), q_abs_rot_2(3), q_abs_trans_2(0), q_abs_trans_2(1), q_abs_trans_2(2), q_abs_trans_2(3);\n\t// std::cout << \"p_abs: \" << std::endl;\t\n\t// std::cout << p_abs.transpose() << std::endl;\t\n\t// std::cout << \"p_abs_2: \" << std::endl;\t\n\t// std::cout << p_abs_2.transpose() << std::endl;\t\t\n\tMatrix4d p_r_htm = DQoperations::dq2HTM(p_ee_r);\n\tMatrix4d p_t_htm = DQoperations::dq2HTM(p_ee_t);\n\tMatrix4d p_abs_htm = DQoperations::dq2HTM(p_abs);\n\tMatrix4d p_rel_htm = DQoperations::dq2HTM(p_rel);\n\t// std::cout << \"p_r_htm: \" << std::endl;\t\n\t// std::cout << p_r_htm << std::endl;\t\n\t// std::cout << \"p_t_htm: \" << std::endl;\t\n\t// std::cout << p_t_htm << std::endl;\t\n\t// std::cout << \"p_abs_htm: \" << std::endl;\t\n\t// std::cout << p_abs_htm << std::endl;\t\n\t// std::cout << \"p_abs_htm_2\" << std::endl;\t\n\t// std::cout << DQoperations::dq2HTM(p_abs_2) << std::endl;\t\n\t// std::cout << \"p_rel_htm: \" << std::endl;\t\n\t// std::cout << p_rel_htm << std::endl;\t\n\n}\n\nRowVectorXd getScrewError_8d_control(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_desired)\n{\n\t// if(pose_now(0,0)<0)\n\t// {\n\t// \tpose_now= -pose_now;\n\t// }\n\tRowVectorXd screw_error=RowVectorXd::Zero(8);\n\tRowVector3d v_e, w_e;\t\n\tMatrix<double,8,1> pose_error;\n\tpose_error=DQoperations::mulDQ(pose_now, DQoperations::classicConjDQ(pose_desired));\n\t// std::cout << \"pose_error: \" << pose_error.transpose() << std::endl;\n\t// std::cout << \"pose_now: \" << pose_now.transpose() << std::endl;\n\t// std::cout << \"pose_ee_desired: \" << pose_ee_desired.transpose() << std::endl;\n\t// std::cout << \"pose_error: \" << pose_error.transpose() << std::endl;\n\tRowVector3d l_e, m_e;\n\tdouble theta_e, d_e;\n\t// DQoperations::dq2screw(pose_error, theta_e, d_e, l_e, m_e);\n\tdouble eps_theta=0.05; /*0.1 degrees*/ \n\tdouble sr, sd, theta;\n\tRowVector3d vr, vd;\n\t// std::cout << \"dq(dq2screw): \" << dq.transpose() << std::endl;\n\t// std::cout << \"dq(0,0): \" << dq(0,0) << std::endl;\n\n\tMatrix<double,8,1> dq = pose_error;\n\t// if(dq(0,0)<0)\n\t// {\n\t// \tdq=-dq;\n\t// \tstd::cout << \"dq(dq2screw): \" << dq.transpose() << std::endl;\n\t// }\t\n\tsr=dq(0);\n\n\tif(sr > 1.0)\n\t\tsr =1.0 ;\n\telse if(sr < -1.0)\n\t\tsr=-1;\n\n\tvr << dq(1), dq(2), dq(3);\n\tsd=dq(4);\n\tvd << dq(5), dq(6), dq(7);\n\ttheta_e=2*acos(sr);\n\t// std::cout << \"sr: \" << sr << std::endl;\n\ttheta_e=DQoperations::normalizeAngle(theta_e);\n\t// if(theta_e > M_PI)\n\t// {\n\t// \ttheta_e = 2*M_PI - theta_e;\n\t\t\t\n\t// }\t\n\t// if(theta_e < -M_PI)\n\t// {\n\t// \ttheta_e = -(2*M_PI - theta_e);\n\t\t\t\n\t// }\t\t\n\tdouble absTheta=fabs(theta_e);\n\t// std::cout << \"abs(theta_e): \" << absTheta << std::endl;\n\tif (absTheta > eps_theta && absTheta < (2*M_PI -eps_theta))\n\t{\n\t\t// std::cout << \"check:: theta_e: \" << absTheta << \"eps_theta: \" << eps_theta << \"(2*M_PI -eps_theta): \" << (2*M_PI -eps_theta) << std::endl;\n\t\t// std::cout << \"definitly here, vr: \" << std::endl;\n\t\t// std::cout << \"vr: \" << vr << std::endl;\n\t\t// std::cout << \"vr.norm \" << vr.norm() << std::endl;\n\t\t// std::cout << \"vr/vr.norm \" << vr/vr.norm() << std::endl;\n\t\tl_e=vr/vr.norm();\n\t\td_e=-sd*(2/(vr.norm()));\n\t\tm_e=(vd-sr*0.5*d_e*l_e)/vr.norm();\n\t}\t\n\telse\n\t{\n\t\t// std::cout << \"why do you have to come here: \" << std::endl;\n\t\t// std::cout << \"check:: theta_e: \" << absTheta << \"eps_theta: \" << eps_theta << \"(2*M_PI -eps_theta): \" << (2*M_PI -eps_theta) << std::endl;\n\t\tRowVector4d qrr, qdd, tt;\n\t\tRowVector3d t;\n\t\tqrr << dq(0), dq(1), dq(2), dq(3);\t\n\t\tqdd << dq(4), dq(5), dq(6), dq(7);\n\t\ttt=2*DQoperations::multQuat(qdd, DQoperations::conjQuat(qrr));\n\t\tt << tt(1), tt(2), tt(3); \n\t\td_e=t.norm();\n\t\tl_e=t/d_e;\n\t\tm_e << 0,0,0;\t\t\t\n\t}\n\t// \tstd::cout << \"theta_e:\" << theta_e << std::endl;\n\t// std::cout << \"l_e:\" << l_e << std::endl;\n\t// std::cout << \"d_e:\" << d_e << std::endl;\n\t// std::cout << \"m_e:\" << m_e << std::endl;\t\n\t// DQoperations::dq2screw(pose_error, theta_e, d_e, l_e, m_e);\n\n\n\n\tv_e = theta_e*m_e + d_e*l_e;\n\tw_e = theta_e*l_e;\n\n \t// double norm_error_position=DQoperations::get_error_screw_param(pose_now, pose_desired, v_e, w_e);\n \tscrew_error << 0, v_e(0), v_e(1), v_e(2), 0, w_e(0), w_e(1), w_e(2);\n \t// std::cout << \"screwError(getScrewError_8d): \" << 0 << v_e(0) << v_e(1) << v_e(2) << 0 << w_e(0) << w_e(1) << w_e(2) << std::endl;\n \treturn screw_error;\n}\n\nbool coop_TaskSpaceControlCallback(dq_robotics::BaxterControl::Request& baxterControl_req, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dq_robotics::BaxterControl::Response& baxterControl_res)\n{\n\t// ROS_INFO(\"here 1\");\n\tros::WallTime start = ros::WallTime::now();\n\tRowVectorXd screw_error_abs, screw_error_abs_2, screw_error_rel, combined_screw_error, q_dot, q, jointCmds_baxterRight, jointCmds_baxterLeft;\n\t// MatrixXd rel_jacobian, abs_jacobian, combined_jacobian;\n\t// combined_jacobian = MatrixXd::Zero(16, (jacobian_baxterRight.cols() + jacobian_baxterLeft.cols()));\n\tMatrix<double,8,1> desiredAbsPose, tf_abs_wrt_ref, temp, desiredRelPose, p_abs_now, p_rel_now, pe_now_baxterRight_vs, pe_now_baxterLeft_vs, starting_abs_pose;\n\tdouble normError =1;\n\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose);\n\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose);\t\n\t// ROS_INFO(\"here 2\");\n\tif(baxterControl_req.virtualSticks)\n\t{\n\t\tstd::cout << \"******************this is the correct function**************************\" << std::endl;\n\t\t// ros::WallTime update_time = ros::WallTime::now();\n\t\tif(!update_baxter())\n\t\t{\n\t\t\tstd::cout << \"The arms could not be updated\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\t// ros::WallTime update_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration update_time_dur = update_time_end - update_time; \n\t\t// std::cout << \"update_time loop duration_server: \" << update_time_dur.toSec() << std::endl;\n\t\t\n\t\t// ros::WallTime vsConstruct_time_start = ros::WallTime::now();\n\t\t \n\t\tif (!baxterControl_req.newTask)\n\t\t{\n\t\t\tpe_now_baxterRight_vs = DQoperations::mulDQ(pe_now_baxterRight, p_right_stick);\n\t\t\tpe_now_baxterLeft_vs = DQoperations::mulDQ(pe_now_baxterLeft, p_left_stick);\n\t\t}\n\t\telse if (baxterControl_req.newTask)\n\t\t{\n\t\t\t// vsConstruct_time_start = ros::WallTime::now();\n\t\t\tstarting_abs_pose = DQoperations::returnDoubleToDQ(baxterControl_req.starting_abs_pose);\n\t\t\t// std::cout << \"starting_abs_pose: \" << starting_abs_pose.transpose() << std::endl;\n\t\t\t// std::cout << \"pe_now_baxterRight: \" << pe_now_baxterRight.transpose() << std::endl;\n\t\t\t// std::cout << \"pe_now_baxterLeft: \" << pe_now_baxterLeft.transpose() << std::endl;\n\t\t\tp_right_stick = DQoperations::mulDQ(DQoperations::classicConjDQ(pe_now_baxterRight), starting_abs_pose) ;\n\t\t\tp_left_stick = DQoperations::mulDQ(DQoperations::classicConjDQ(pe_now_baxterLeft), starting_abs_pose)\t;\n\t\t\t// std::cout << \"p_right_stick: \" << p_right_stick.transpose() << std::endl;\t\t\t\n\t\t\t// std::cout << \"p_left_stick: \" << p_left_stick.transpose() << std::endl;\t\t\t\n\t\t\tpe_now_baxterRight_vs = DQoperations::mulDQ(pe_now_baxterRight, p_right_stick);\n\t\t\tpe_now_baxterLeft_vs = DQoperations::mulDQ(pe_now_baxterLeft, p_left_stick);\n\t\t\t// getAbsoluteRelativePose(pe_now_baxterRight_vs, pe_now_baxterLeft_vs, p_abs_now, p_rel_stick);\n\t\t\t// std::cout << \"Is the relative pose of the stick ends Identity!! p_rel_stick_htm: \" << std::endl;\t\n\t\t\t// std::cout << DQoperations::dq2HTM(p_rel_stick) << std::endl;\n\t\t\t// ros::WallTime vsConstruct_time_end = ros::WallTime::now();\n\t\t\t// ros::WallDuration vsConstruct_time_dur = vsConstruct_time_end - vsConstruct_time_start;\n\t\t\t// std::cout << \"vsConstruct duration_server: \" << vsConstruct_time_dur.toSec() << std::endl; \n\t\t} \n\t\t// ros::WallTime absRelPoseCalc_time_start = ros::WallTime::now();\n\t\tgetAbsoluteRelativePose(pe_now_baxterRight_vs, pe_now_baxterLeft_vs, p_abs_now, p_rel_now);\n\t\t// ros::WallTime absRelPoseCalc_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration absRelPoseCalc_time_dur = absRelPoseCalc_time_end - absRelPoseCalc_time_start;\n\t\t// std::cout << \"absRelPoseCalc duration_server: \" << absRelPoseCalc_time_dur.toSec() << std::endl; \n\t\t// p_rel_now = DQoperations::mulDQ(DQoperations::classicConjDQ(pe_now_baxterRight_vs), pe_now_baxterLeft_vs);\n\t\t// getAbsoluteRelativePose(pe_now_baxterRight, pe_now_baxterLeft, p_abs_now, p_rel_now);\n\t\t// tf_abs_wrt_ref = DQoperations::mulDQ(DQoperations::classicConjDQ(pe_now_baxterRight_vs), desiredAbsPose) ;\n\t\t// std::cout << \"desiredRelPose_beforeTF: \" << desiredRelPose.transpose() << std::endl;\n\t\t// temp = DQoperations::dq2twist(desiredRelPose) ;\n\t\t// std::cout << \"temp: \" << temp.transpose() << std::endl;\n\t\t// // temp.block(0,0,4,1) = desiredRelPose.block(4,0,4,1);\n\t\t// // temp.block(4,0,4,1) = desiredRelPose.block(0,0,4,1);\n\t\t// temp = DQoperations::transformLine(temp, tf_abs_wrt_ref);\n\t\t// temp.block(0,0,4,1) = desiredRelPose.block(4,0,4,1);\n\t\t// temp.block(4,0,4,1) = desiredRelPose.block(0,0,4,1);\n\t\t// desiredRelPose = DQoperations::mulDQ(DQoperations::mulDQ(p_right_stick, DQoperations::twist2dq(temp)), DQoperations::classicConjDQ(p_left_stick)) ; \n\t\t// desiredRelPose = temp;\t\t\n\t\t// ros::WallTime screwErrCalc_time_start = ros::WallTime::now();\n\t\t// std::cout << \"It is the absolute \" << std::endl;\n\t\t// std::cout << \"p_abs_now: \" << p_abs_now.transpose() << std::endl;\n\t\t// std::cout << \"desiredRelPose: \" << desiredRelPose.transpose() << std::endl;\n\t\t// std::cout << \"desiredRelPose_htm: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(desiredRelPose) << std::endl;\n\t\tscrew_error_abs= getScrewError_8d_control(p_abs_now, desiredAbsPose);\n\t\tscrew_error_abs_2= getScrewError_8d_control(p_abs_2, desiredAbsPose);\n\t\tif(screw_error_abs.norm() > screw_error_abs_2.norm())\n\t\t{\n\t\t\tscrew_error_abs = screw_error_abs_2;\n\t\t\tp_abs_now = p_abs_2;\n\t\t}\n\t\tstd::cout << \"It is the relative \" << std::endl;\t\t\n\t\tscrew_error_rel= DQController::getScrewError_8d(p_rel_now, desiredRelPose);\n\t\t// std::cout << \"rowvector screw_error_rel_beforeTF: \" << screw_error_rel << std::endl;\n\t\t// Matrix<double,8,1> screwError_rel, tf_ref_wrt_abs;\n\t\t// screwError_rel << screw_error_rel.tail(4).transpose(), screw_error_rel.head(4).transpose();\n\t\t// std::cout << \"Matrix screwError_rel_beforeTF: \" << screwError_rel.transpose() << std::endl;\n\t\t// // screwError_rel << screw_error_rel;\n\t\t// tf_ref_wrt_abs = DQoperations::mulDQ(DQoperations::classicConjDQ(p_abs_now), pe_now_baxterRight);\n\t\t// screwError_rel = DQoperations::transformLine(screwError_rel, tf_ref_wrt_abs);\n\t\t// std::cout << \"Matrix screwError_rel: \" << screwError_rel.transpose() << std::endl;\n\t\t// screw_error_rel << screwError_rel(4, 0), screwError_rel(5, 0), screwError_rel(6, 0), screwError_rel(7, 0), screwError_rel(0, 0), screwError_rel(1, 0), screwError_rel(2, 0), screwError_rel(3, 0);\t\t\n\t\t// std::cout << \"screw_error_rel: \" << screw_error_rel << std::endl;\n\t\t// std::cout << \"screw_error_abs: \" << screw_error_abs << std::endl;\n\n\t\tcombined_screw_error = RowVectorXd::Zero(screw_error_abs.cols()+screw_error_rel.cols());\n\t\tcombined_screw_error << screw_error_abs.row(0), screw_error_rel.row(0);\n\n\t\t// std::cout << \"combined_screw_error: \" << combined_screw_error << std::endl;\n\t\t// ros::WallTime screwErrCalc_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration screwErrCalc_time_dur = screwErrCalc_time_end - screwErrCalc_time_start;\n\t\t// std::cout << \"screwErrCalc duration_server: \" << screwErrCalc_time_dur.toSec() << std::endl; \n\t\t// ros::WallTime jacCalc_time_start = ros::WallTime::now();\t\t\n\t\tMatrixXd abs_jacobian = absoluteJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight, pe_now_baxterLeft);\n\n\t\tMatrixXd rel_jacobian = relativeJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight_vs, pe_now_baxterLeft);\n\t\t// MatrixXd rel_jacobian = relativeJacobian_inAbsFrame(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight_vs);\n\t\tMatrixXd combined_jacobian = MatrixXd::Zero(16, (jacobian_baxterRight.cols() + jacobian_baxterLeft.cols()));\n\t\tcombined_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols()) = abs_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols());\n\t\tcombined_jacobian.block(abs_jacobian.rows(), 0, rel_jacobian.rows(), rel_jacobian.cols()) = rel_jacobian.block(0, 0, rel_jacobian.rows(), rel_jacobian.cols());\n\t\t// ros::WallTime jacCalc_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration jacCalc_time_dur = jacCalc_time_end - jacCalc_time_start;\n\t\t// std::cout << \"jacCalc duration_server: \" << jacCalc_time_dur.toSec() << std::endl; \n\n\t\t// ros::WallTime robotCmd_time_start = ros::WallTime::now();\t\t\n\t\tq_dot= DQController::calculateControlVel(Kp, mu, combined_screw_error, combined_jacobian, (combined_jacobian.cols()));\n\n\t\tstd::cout << \"q_dot: \" << std::endl;\t\n\t\tstd::cout << q_dot << std::endl;\t\n\n\t\tq.resize(q_dot.size());\n\t\tq << q_baxterRight, q_baxterLeft;\n\t\tq = q + q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::cout << \"q: \" << std::endl;\t\t\t\n\t\tstd::cout << q << std::endl;\t\t\t\n\t\tbaxter_controller->sendBaxterJointCmds(\"combined\", DQoperations::dqEigenToDQdouble(q), 0);\n\t\t// baxter_controller->sendBaxterVelocityCmds(\"combined\", DQoperations::dqEigenToDQdouble(q_dot));\n\t\tnormError = combined_screw_error.norm();\n\t\tbaxterControl_res.result = 1;\n\t\tbaxterControl_res.normError = normError;\n\t\ttime_start =ros::Time::now().toSec();\n\t\tresultMsg.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n\t\tresultMsg.currentAbsPose = DQoperations::DQToDouble(p_abs_now);\n\t\tresultMsg.desiredRelPose = DQoperations::DQToDouble(desiredRelPose);\n\t\tresultMsg.currentRelPose = DQoperations::DQToDouble(p_rel_now);\n\t\tresultMsg.del_q = DQoperations::dqEigenToDQdouble(q_dot);\n\t\tresultMsg.joint_state_left = DQoperations::dqEigenToDQdouble(q_baxterLeft);\n\t\tresultMsg.joint_state_right = DQoperations::dqEigenToDQdouble(q_baxterRight);\n\t\tresultMsg.norm_error_abs = screw_error_abs.norm();\n\t\tresultMsg.norm_error_rel = screw_error_rel.norm();\n\t\tresultMsg.timeStamp = time_start;\n\t\tresult_topics.publish(resultMsg);\n\n\t\t// ros::WallTime robotCmd_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration robotCmd_time_dur = robotCmd_time_end - robotCmd_time_start;\n\t\t// std::cout << \"robotCmd duration_server: \" << robotCmd_time_dur.toSec() << std::endl;\t\t\n\t\tros::WallTime end = ros::WallTime::now();\n\t\tros::WallDuration dur = end - start;\n\t\tstd::cout << \"master loop duration_server: \" << dur.toSec() << std::endl;\n\n\t\treturn true;\n\t}\n\n\tif(baxterControl_req.tracking && !baxterControl_req.virtualSticks)\n\t{\n\t\tif(!update_baxter())\n\t\t{\n\t\t\tstd::cout << \"The arms could not be updated\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\tgetAbsoluteRelativePose(pe_now_baxterRight, pe_now_baxterLeft, p_abs_now, p_rel_now);\n\t\tstd::cout << \"It is the absolute \" << std::endl;\n\t\tstd::cout << \"p_abs_now: \" << p_abs_now.transpose() << std::endl;\n\t\tscrew_error_abs= getScrewError_8d_control(p_abs_now, desiredAbsPose);\n\t\tscrew_error_abs_2= getScrewError_8d_control(p_abs_2, desiredAbsPose);\n\t\tif(screw_error_abs.norm() > screw_error_abs_2.norm())\n\t\t\tscrew_error_abs = screw_error_abs_2;\n\t\tstd::cout << \"It is the relative \" << std::endl;\t\t\n\t\tscrew_error_rel= DQController::getScrewError_8d(p_rel_now, desiredRelPose);\n\t\tstd::cout << \"screw_error_rel: \" << screw_error_rel << std::endl;\n\t\tstd::cout << \"screw_error_abs: \" << screw_error_abs << std::endl;\n\n\t\tcombined_screw_error = RowVectorXd::Zero(screw_error_abs.cols()+screw_error_rel.cols());\n\t\tcombined_screw_error << screw_error_abs.row(0), screw_error_rel.row(0);\n\n\t\tstd::cout << \"combined_screw_error: \" << combined_screw_error << std::endl;\n\n\t\tMatrixXd abs_jacobian = absoluteJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight, pe_now_baxterLeft);\n\n\t\tMatrixXd rel_jacobian = relativeJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight, pe_now_baxterLeft);\n\n\t\tMatrixXd combined_jacobian = MatrixXd::Zero(16, (jacobian_baxterRight.cols() + jacobian_baxterLeft.cols()));\n\t\tcombined_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols()) = abs_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols());\n\t\tcombined_jacobian.block(abs_jacobian.rows(), 0, rel_jacobian.rows(), rel_jacobian.cols()) = rel_jacobian.block(0, 0, rel_jacobian.rows(), rel_jacobian.cols());\n\t\tq_dot= DQController::calculateControlVel(Kp, mu, combined_screw_error, combined_jacobian, (combined_jacobian.cols()));\n\n\t\tstd::cout << \"q_dot: \" << std::endl;\t\n\t\tstd::cout << q_dot << std::endl;\t\n\n\t\tq.resize(q_dot.size());\n\t\tq << q_baxterRight, q_baxterLeft;\n\t\tq = q + q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::cout << \"q: \" << std::endl;\t\t\t\n\t\tstd::cout << q << std::endl;\t\t\t\n\t\tbaxter_controller->sendBaxterJointCmds(\"combined\", DQoperations::dqEigenToDQdouble(q), 0);\n\t\t// baxter_controller->sendBaxterVelocityCmds(\"combined\", DQoperations::dqEigenToDQdouble(q_dot));\n\t\tnormError = combined_screw_error.norm();\n\t\tbaxterControl_res.result = 1;\n\t\tbaxterControl_res.normError = normError;\n\t\treturn true;\n }\n\telse\n\t{\n\t while (normError > norm_error_const)\n\t {\n\t \tif(!update_baxter())\n\t\t\t{\n\t\t\t\tstd::cout << \"The arms could not be updated\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t// ROS_INFO(\"here 3\");\n\t\t\tgetAbsoluteRelativePose(pe_now_baxterRight, pe_now_baxterLeft, p_abs_now, p_rel_now);\n\t\t\t// ROS_INFO(\"here 4\");\t\t\n\t\t\tstd::cout << \"It is the absolute \" << std::endl;\n\t\t\tstd::cout << \"p_abs_now: \" << p_abs_now.transpose() << std::endl;\n\t\t\t// screw_error_abs= DQController::getScrewError_8d(p_abs_now, desiredAbsPose);\n\t\t\tscrew_error_abs= getScrewError_8d_control(p_abs_now, desiredAbsPose);\n\t\t\tscrew_error_abs_2= getScrewError_8d_control(p_abs_2, desiredAbsPose);\n\t\t\tif(screw_error_abs.norm() > screw_error_abs_2.norm())\n\t\t\t\tscrew_error_abs = screw_error_abs_2;\n\t\t\tstd::cout << \"It is the relative \" << std::endl;\t\t\n\t\t\tscrew_error_rel= DQController::getScrewError_8d(p_rel_now, desiredRelPose);\n\t\t\tstd::cout << \"screw_error_rel: \" << screw_error_rel << std::endl;\n\t\t\tstd::cout << \"screw_error_abs: \" << screw_error_abs << std::endl;\n\t\t\t// std::cout << \"screw_error_abs.rows(), cols: \" << screw_error_abs.rows() << screw_error_abs.cols() << std::endl;\n\t\t\t// std::cout << \"screw_error_rel.rows(), cols: \" << screw_error_rel.rows() << screw_error_rel.cols() << std::endl;\n\t\t\t\n\n\t\t\tcombined_screw_error = RowVectorXd::Zero(screw_error_abs.cols()+screw_error_rel.cols());\n\t\t\tcombined_screw_error << screw_error_abs.row(0), screw_error_rel.row(0);\n\t\t\t// std::cout << \"screw_error_abs: \" << screw_error_abs << std::endl;\t\t\n\t\t\t// std::cout << \"screw_error_rel: \" << screw_error_rel << std::endl;\n\t\t\tstd::cout << \"combined_screw_error: \" << combined_screw_error << std::endl;\n\t\t\t// abs_jacobian = MatrixXd::Zero(8, (jacobian_baxterRight.cols() + jacobian_baxterLeft.cols()));\n\t\t\tMatrixXd abs_jacobian = absoluteJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight, pe_now_baxterLeft);\n\t\t\t\t// ROS_INFO(\"here 6\");\n\t\t\tMatrixXd rel_jacobian = relativeJacobian(jacobian_baxterRight, jacobian_baxterLeft, pe_now_baxterRight, pe_now_baxterLeft);\n\n\t\t\t// std::cout << \"abs_jacobian: \" << std::endl;\n\t\t\t// std::cout << abs_jacobian << std::endl;\n\t\t\t// std::cout << \"rel_jacobian: \" << std::endl;\n\t\t\t// std::cout << rel_jacobian << std::endl;\n\n\t\t\t// std::cout << \"combined_jacobian.rows(): \" << combined_jacobian.rows() << \"::combined_jacobian.cols(): \" << combined_jacobian.cols() << std::endl;\n\t\t\t// std::cout << \"rel_jacobian.rows(): \" << rel_jacobian.rows() << \"::rel_jacobian.cols(): \" << rel_jacobian.cols() << std::endl;\n\t\t\t// std::cout << \"abs_jacobian.rows(): \" << abs_jacobian.rows() << \"::abs_jacobian.cols(): \" << abs_jacobian.cols() << std::endl;\n\n\t\t\t// ROS_INFO(\"here 7\");\n\t\t\tMatrixXd combined_jacobian = MatrixXd::Zero(16, (jacobian_baxterRight.cols() + jacobian_baxterLeft.cols()));\n\t\t\tcombined_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols()) = abs_jacobian.block(0, 0, abs_jacobian.rows(), abs_jacobian.cols());\n\t\t\t// ROS_INFO(\"here 17\");\n\t\t\tcombined_jacobian.block(abs_jacobian.rows(), 0, rel_jacobian.rows(), rel_jacobian.cols()) = rel_jacobian.block(0, 0, rel_jacobian.rows(), rel_jacobian.cols());\n\t// ROS_INFO(\"here 18\");\n\t\t\tq_dot= DQController::calculateControlVel(Kp, mu, combined_screw_error, combined_jacobian, (combined_jacobian.cols()));\n\t\t\t// q_dot= DQController::calculateControlVel(Kp, mu, screw_error_abs, abs_jacobian, (abs_jacobian.cols()));\n\t\t\t// q_dot= DQController::calculateControlVel(Kp, mu, screw_error_rel, rel_jacobian, (rel_jacobian.cols()));\n\t\t\tstd::cout << \"q_dot: \" << std::endl;\t\n\t\t\tstd::cout << q_dot << std::endl;\t\n\t\t\t// q_dot.head(7)=-q_dot.head(7);\n\t\t\t// RowVectorXd joint_vel_lim_right = DQoperations::doubleVector2Rowvector(joint_velocity_limit_baxterRight);\n\t\t\t// RowVectorXd joint_vel_lim_left = DQoperations::doubleVector2Rowvector(joint_velocity_limit_baxterLeft);\n\t\t\t// RowVectorXd joint_velocity_limit = RowVectorXd::Zero(joint_vel_lim_right.cols()+joint_vel_lim_left.cols());\n\t\t\t// std::cout << \"joint_vel_lim_right: \" << std::endl;\t\t\n\t\t\t// std::cout << joint_vel_lim_right << std::endl;\t\t\n\t\t\t// std::cout << \"joint_vel_lim_left: \" << std::endl;\t\t\n\t\t\t// std::cout << joint_vel_lim_left << std::endl;\t\t\n\t\t\t// std::cout << \"joint_velocity_limit: \" << std::endl;\t\t\n\t\t\t// std::cout << joint_velocity_limit << std::endl;\t\t\n\n\t\t\t// joint_velocity_limit << joint_vel_lim_right, joint_vel_lim_left;\t\t\t\n\t\t\t// std::cout << \"joint_velocity_limit: \" << std::endl;\t\t\n\t\t\t// std::cout << joint_velocity_limit << std::endl;\t\t\n\t\t\t// joint_velocity_limit_baxter = DQoperations::dqEigenToDQdouble(joint_velocity_limit);\n\t\t\t// // std::cout << \"q_dot(before normalization): \" << std::endl;\t\n\t\t\t// q_dot= DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_baxter);\n\t\t\t// std::cout << \"q_dot(after normalization): \" << std::endl;\t\t\n\t\t\t// std::cout << q_dot << std::endl;\t\t\n\t\t\tq.resize(q_dot.size());\n\t\t\tq << q_baxterRight, q_baxterLeft;\n\t\t\tq = q + q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\t\tstd::cout << \"q: \" << std::endl;\t\t\t\n\t\t\tstd::cout << q << std::endl;\t\t\t\n\t\t\tbaxter_controller->sendBaxterJointCmds(\"combined\", DQoperations::dqEigenToDQdouble(q), 0);\n\t\t\tnormError = combined_screw_error.norm();\n\t\t\t// normError = screw_error_abs.norm();\n\t\t\t// normError = screw_error_rel.norm();\n\t\t\t// std::cout << \"normError(abs, rel, combo): \" << screw_error_abs.norm() << screw_error_rel.norm() << combined_screw_error.norm() << std::endl;\n\t\t\t// std::cout << normError << std::endl;\n\t\t\t// std::cout << \"normError\" << normError << std::endl;\n\t }\n\t baxterControl_res.result = 1;\n\t baxterControl_res.normError = normError;\n\n\t return true;\n\t}\n}\n\n\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"baxter_ar10_kinematics\");\n\tros::NodeHandle n;\n\tresult_topics = n.advertise<dq_robotics::ControllerPerformance>(\"/dq_robotics/results\", 1000);\n\tdouble time_start =ros::Time::now().toSec();\n ros::Duration(0.5).sleep();\n time_start =ros::Time::now().toSec();\n\tMatrix4d htm_rightHand2handBase = Matrix4d::Identity();\n\thtm_rightHand2handBase << -0.0002037, 1.0000000, 0.0000000, 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t -1.0000000, -0.0002037, 0.0000000, 0, \n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.0000000, 0.0000000, 1.0000000, 0.01,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0,\t\t\t\t\t 0,\t\t\t\t\t 0, \t\t\t\t 1;\n\ttf_rightHand2handBase = DQoperations::htm2DQ(htm_rightHand2handBase);\n\n\tif (!getControllerParams())\n\t\tstd::cout << \"Controller params not found for COMBO controller.\" << std::endl;\n\n\n\tbaxter_controller = new BaxterPoseControlServer();\n\tif (!baxter_controller->BaxterPoseControlServer::initializeController())\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\n\tif(!update_baxter())\n\t{\n\t\tstd::cout << \"The arms could not be updated\" << std::endl;\n\t\treturn 0;\n\t}\n\tros::ServiceServer service = n.advertiseService(\"baxter/coopTaskSpaceControlCallback\", coop_TaskSpaceControlCallback);\n\tros::spin();\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.6491575837135315, "alphanum_fraction": 0.6541129946708679, "avg_line_length": 36.38888931274414, "blob_id": "f8de73942027782a136c6dde2ee3d63c8e8b7c7b", "content_id": "74080550af0358a7aa606097323b0d4d6ba09505", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2018, "license_type": "no_license", "max_line_length": 91, "num_lines": 54, "path": "/dq_robotics/src/test/test_jointPub.py", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nimport PyKDL\n\nimport rospy\n\nimport baxter_interface\nimport sensor_msgs.msg\n\nfrom baxter_kdl.kdl_parser import kdl_tree_from_urdf_model\nfrom urdf_parser_py.urdf import URDF\n\ndef main():\n pub = rospy.Publisher('baxter/joint_states', sensor_msgs.msg.JointState, queue_size=10)\n rospy.init_node('talker', anonymous=True) \n\n limb_interface_right = baxter_interface.Limb(\"right\")\n limb_interface_left = baxter_interface.Limb(\"left\")\n \n joint_names_right = limb_interface_right.joint_names()\n joint_names_left = limb_interface_left.joint_names()\n # rate = rospy.Rate(10000)\n while not rospy.is_shutdown():\n limb_interface_right = baxter_interface.Limb(\"right\")\n limb_interface_left = baxter_interface.Limb(\"left\")\n joint_names_right = limb_interface_right.joint_names()\n joint_names_left = limb_interface_left.joint_names() \n joint_angles_right = limb_interface_right.joint_angles()\n # print joint_angles_right\n joint_angles_left = limb_interface_left.joint_angles() \n # print joint_angles_left\n # print \"hello\"\n joint_angles_left_values = [\n joint_angles_left[joint_name] for joint_name in joint_names_left]\n # print \"hello222\" \n joint_angles_right_values = [\n joint_angles_right[joint_name] for joint_name in joint_names_right] \n \n baxter_joints_msg = sensor_msgs.msg.JointState()\n baxter_joints_msg.header.stamp = rospy.Time.now()\n baxter_joints_msg.name = joint_names_left\n baxter_joints_msg.name.extend(joint_names_right)\n baxter_joints_msg.position = joint_angles_left_values\n baxter_joints_msg.position.extend(joint_angles_right_values)\n # print(\"joint angles:\\n{}\".format(baxter_joints_msg))\n pub.publish(baxter_joints_msg)\n # rate.sleep()\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass" }, { "alpha_fraction": 0.62749183177948, "alphanum_fraction": 0.6631349921226501, "avg_line_length": 35.568870544433594, "blob_id": "ce949d0d3da574e4831847be9943493f7caefc3a", "content_id": "05ad3bf6bc1bce0f6d9ac9b95995be8a19043b16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 32657, "license_type": "no_license", "max_line_length": 241, "num_lines": 893, "path": "/dq_robotics/include/dq_robotics/DQoperations.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/DQoperations.h>\nusing namespace Eigen;\n\nDQoperations::DQoperations(){}\nDQoperations::~DQoperations(){}\n\n// inline Matrix3d VectorCrossMatrix (const Vector3d &vector) {\n// return Matrix3d (\n// 0., -vector[2], vector[1],\n// vector[2], 0., -vector[0],\n// -vector[1], vector[0], 0.\n// );\n// }\n\nRowVectorXd DQoperations::spatial2CartAcc(RowVectorXd screwAcc, RowVectorXd screwVel, RowVector3d ee_pose)\n{\n\tVectorXd cartAcc = RowVectorXd::Zero(6);\n\t // = screwAcc;\n\tVector3d angAcc, transAcc, angVel, transVel;\n\t\n\tangVel << screwVel(0), screwVel(1), screwVel(2);\n\ttransVel << screwVel(3), screwVel(4), screwVel(5);\n\n\tangAcc << screwAcc(0), screwAcc(1), screwAcc(2);\n\ttransAcc << screwAcc(3), screwAcc(4), screwAcc(5);\n// Getting linear accleration at origin (ref. featherstoneAccelerationVectorRigid2001, pp-843/3)\n\tstd::cout << \"angAcc\" << angAcc.transpose() << std::endl;\n\ttransAcc = transAcc + DQoperations::crossProductOp_3d(angVel)*transVel; \n// Getting linear accleration at end-effector(ref. featherstoneAccelerationVectorRigid2001, eq (5), pp-845/5 )\n\tstd::cout << \"transAcc1\" << transAcc.transpose() << std::endl;\n\ttransAcc = transAcc + DQoperations::crossProductOp_3d(angAcc)*ee_pose.transpose()+ DQoperations::crossProductOp_3d(angVel)*(DQoperations::crossProductOp_3d(angVel)*ee_pose.transpose()); \n\tstd::cout << \"transAcc2\" << transAcc.transpose() << std::endl;\n\tcartAcc << angAcc, transAcc;\n\tstd::cout << \"cartAcc\" << cartAcc.transpose() << std::endl;\t\n\treturn cartAcc.transpose();\n}\n\nRowVectorXd DQoperations::spatial2CartVel(RowVectorXd screwVel, RowVector3d ee_pose)\n{\n\tRowVectorXd cartVel = screwVel;\n\tVector3d angVel, transVel;\n\tangVel << screwVel(0), screwVel(1), screwVel(2);\n\ttransVel << screwVel(3), screwVel(4), screwVel(5);\n\ttransVel = transVel + DQoperations::crossProductOp_3d(angVel)*ee_pose.transpose();\n\tcartVel << angVel(0), angVel(1), angVel(2), transVel(0), transVel(1), transVel(2);\n\treturn cartVel;\n}\n\nRowVectorXd DQoperations::spatial2CartPoseError_quatVec(Matrix<double,8,1> desired_pose, Matrix<double,8,1> current_pose)\n{\n\tRowVectorXd pose_error = RowVectorXd::Zero(6);\n\t// This way of getting position error will not work because it is screw distance. It is the error screw twist in base frame \n\t// Matrix<double,8,1> pose_error_dq = DQoperations::mulDQ(desired_pose, DQoperations::classicConjDQ(current_pose));\n\t// Matrix4d htm_error = DQoperations::dq2HTM(pose_error_dq);\n\t// std::cout << \"dq_error = \" << htm_error(0,3) << htm_error(1,3) << htm_error(2,3) << std::endl; \n\tMatrix4d htm_error = DQoperations::dq2HTM(desired_pose) - DQoperations::dq2HTM(current_pose);\n\t// std::cout << \"htm_error = \" << htm_error(0,3) << htm_error(1,3) << htm_error(2,3) << std::endl;\n\t// std::cout << \"Are they equal!!\" << std::endl; \n\t// RowVector3d v_e, w_e;\n\t// double norm_error = DQoperations::get_error_screw(current_pose, desired_pose, v_e, w_e);\n\tdesired_pose=DQoperations::mulDQ(desired_pose, DQoperations::classicConjDQ(current_pose));\n\tpose_error << desired_pose(1), desired_pose(2), desired_pose(3), htm_error(0,3), htm_error(1,3), htm_error(2,3);\n\treturn pose_error;\n}\n\nRowVectorXd DQoperations::spatial2CartPoseError(Matrix<double,8,1> desired_pose, Matrix<double,8,1> current_pose)\n{\n\tRowVectorXd pose_error = RowVectorXd::Zero(6);\n\t// This way of getting position error will not work because it is screw distance. It is the error screw twist in base frame \n\t// Matrix<double,8,1> pose_error_dq = DQoperations::mulDQ(desired_pose, DQoperations::classicConjDQ(current_pose));\n\t// Matrix4d htm_error = DQoperations::dq2HTM(pose_error_dq);\n\t// std::cout << \"dq_error = \" << htm_error(0,3) << htm_error(1,3) << htm_error(2,3) << std::endl; \n\tMatrix4d htm_error = DQoperations::dq2HTM(desired_pose) - DQoperations::dq2HTM(current_pose);\n\t// std::cout << \"htm_error = \" << htm_error(0,3) << htm_error(1,3) << htm_error(2,3) << std::endl;\n\t// std::cout << \"Are they equal!!\" << std::endl; \n\tRowVector3d v_e, w_e;\n\tdouble norm_error = DQoperations::get_error_screw(current_pose, desired_pose, v_e, w_e);\n\tpose_error << w_e(0), w_e(1), w_e(2), htm_error(0,3), htm_error(1,3), htm_error(2,3);\n\treturn pose_error;\n}\n\nMatrix3d DQoperations::crossProductOp_3d(Vector3d vector)\n{\n\tMatrix3d crossProductOp = MatrixXd::Zero(3, 3);\n\tcrossProductOp << 0., -vector(2), vector(1),\n \t\t\t\t vector(2), 0., -vector(0),\n -vector(1), vector(0), 0.;\n \n\treturn crossProductOp;\n}\n\nMatrixXd DQoperations::crossProductOp_6d(VectorXd vector)\n{\n\tMatrixXd cross_6d = MatrixXd::Zero(6, 6);\n\tVector3d w;\n\tw << vector(0), vector(1), vector(2);\n\tVector3d v0;\n\tv0 << vector(3), vector(4), vector(5);\n\n\tcross_6d.block(0, 0, 3, 3) = crossProductOp_3d(w);\n\tcross_6d.block(3, 0, 3, 3) = crossProductOp_3d(v0);\n\tcross_6d.block(3, 3, 3, 3) = crossProductOp_3d(w);\n\treturn cross_6d;\n}\n\n\nMatrix4d DQoperations::htmFromGeometryMsgPose(geometry_msgs::Pose pose)\n{\n Matrix4d htm;\n Eigen::Quaterniond q;\n q.x()=-pose.orientation.x;\n q.y()=-pose.orientation.y;\n q.z()=-pose.orientation.z;\n q.w()=-pose.orientation.w;\n Eigen::Matrix3d rot = q.normalized().toRotationMatrix();\n\n Eigen::RowVector4d translation;\n translation << pose.position.x, pose.position.y, pose.position.z, 1;\n\n htm.setIdentity();\n htm.block<3,3>(0,0) = rot;\n htm.rightCols<1>() =translation;\n return htm;\n}\n\nMatrix<double,8,1> DQoperations::dqFromGeometryMsgPose(geometry_msgs::Pose pose)\n{\n\tMatrix<double,8,1> dq;\n\tMatrix4d htm = DQoperations::htmFromGeometryMsgPose(pose);\n\tdq = DQoperations::htm2DQ(htm);\n\treturn dq;\n}\n\ngeometry_msgs::Twist DQoperations::Rowvector2geometry_msgsTwist(RowVectorXd vel)\n{\n\tgeometry_msgs::Twist twist;\n\ttwist.linear.x = vel(0);\n\ttwist.linear.y = vel(1);\n\ttwist.linear.z = vel(2);\n\ttwist.angular.x = vel(3);\n\ttwist.angular.y = vel(4);\n\ttwist.angular.z = vel(5);\n\treturn twist;\n}\n\ngeometry_msgs::Pose DQoperations::DQ2geometry_msgsPose(Matrix<double,8,1> pose_now)\n{\n\n\tgeometry_msgs::Pose pose;\n\tpose.orientation.w=pose_now(0);\t\n\tpose.orientation.x=pose_now(1);\t\n\tpose.orientation.y=pose_now(2);\t\n\tpose.orientation.z=pose_now(3);\n\n\tMatrix4d pose_now_htm= DQoperations::dq2HTM(pose_now);\n\tpose.position.x=pose_now_htm(0,3);\t\n\tpose.position.y=pose_now_htm(1,3);\t\n\tpose.position.z=pose_now_htm(2,3);\n\t// std::cout << \"pose_geomMsg: \" << pose << std::endl;\n\treturn pose;\t\n}\n\nRowVectorXd DQoperations::DQEigen2twistEigen(RowVectorXd DQtwist)\n{\n\tRowVectorXd rowVector(8);\n\trowVector << DQtwist(1), DQtwist(2), DQtwist(3), DQtwist(5), DQtwist(6), DQtwist(7);\n\treturn rowVector;\n}\n\nRowVectorXd DQoperations::twistEigen2DQEigen(RowVectorXd twist)\n{\n\tRowVectorXd rowVector(8);\n\trowVector << 0, twist(0), twist(1), twist(2), 0, twist(3), twist(4), twist(5);\n\treturn rowVector;\n}\n\nMatrix<double,8,1> DQoperations::RowVector6d2Matrix8d(RowVectorXd rowVector6d)\n{\n\tMatrix<double,8,1> matrix8d;\n\tmatrix8d << 0, rowVector6d(0), rowVector6d(1), rowVector6d(2), 0, rowVector6d(3), rowVector6d(4), rowVector6d(5);\n\treturn matrix8d;\n}\n\nRowVectorXd DQoperations::Matrix8d2RowVector6d(Matrix<double,8,1> matrix8d)\n{\n\tRowVectorXd rowVector(6);\n\trowVector << matrix8d(1), matrix8d(2), matrix8d(3), matrix8d(5), matrix8d(6), matrix8d(7);\n\treturn rowVector;\n}\n\n\nRowVectorXd DQoperations::Matrix8d2RowVector8d(Matrix<double,8,1> matrix8d)\n{\n\tRowVectorXd rowVector(8);\n\trowVector << matrix8d(0), matrix8d(1), matrix8d(2), matrix8d(3), matrix8d(4), matrix8d(5), matrix8d(6), matrix8d(7);\n\treturn rowVector;\n}\n\nMatrix<double,8,1> DQoperations::sclerp(Matrix<double,8,1> pose_now, Matrix<double,8,1> &pose_intermediate, Matrix<double,8,1> pose_desired, double tau)\n{\n\tMatrix<double,8,1> pose_error=DQoperations::mulDQ(DQoperations::classicConjDQ(pose_now), pose_desired);\n\tdouble theta_e, d_e;\n\tRowVector3d l_e, m_e;\n\tDQoperations::dq2screw(pose_error, theta_e, d_e, l_e, m_e);\n\tRowVector3d realPart_velocity= 0.5*theta_e*l_e, dualPart_velocity=0.5*theta_e*m_e+0.5*d_e*l_e;\n\tMatrix<double,8,1> velocity;\n\tvelocity << 0, realPart_velocity(0), realPart_velocity(1), realPart_velocity(2), 0, dualPart_velocity(0), dualPart_velocity(1), dualPart_velocity(2); \n\t// velocity=mulDQ(pose_now, mulDQ(velocity, pose_error));\n\t// std::cout << \"velocity: \" << velocity << std::endl;\n\tpose_intermediate =DQoperations::screw2DQ(tau*theta_e, l_e, tau*d_e, m_e);\n\tpose_intermediate=DQoperations::mulDQ(pose_now, pose_intermediate);\n\t// DQoperations::dq2screw(velocity, theta_e, d_e, l_e, m_e);\n\t// realPart_velocity= theta_e*l_e;\n\t// dualPart_velocity=theta_e*m_e+d_e*l_e;\n\t\n\n\treturn velocity;\t\n}\n\nMatrix<double,8,1> DQoperations::preGraspFromGraspPose(Matrix<double,8,1> grasp_location, double distance, RowVector3d approach_direction)\n{\n\tMatrix<double,8,1> dq_result;\n\n\tdouble theta= 0;\n\tRowVector3d axis=-approach_direction;\n\tdouble d= distance;\n\tRowVector3d moment =RowVector3d::Zero();\n\tdq_result= DQoperations::screw2DQ(theta, axis, d, moment);\n\tdq_result= mulDQ(grasp_location, dq_result);\n\treturn dq_result;\n}\n\nMatrix<double,8,1> DQoperations::transformLine(Matrix<double,8,1> line, Matrix<double,8,1> transform)\n{\n\t// line=mulDQ(transform, mulDQ(line, classicConjDQ(transform)));\n\t// std::cout << \"lineVector: \" << line.transpose() << std::endl;\t\t\n\t// std::cout << \"transform: \" << transform.transpose() << std::endl;\t\t\n\tline=mulDQ(transform, mulDQ(line, classicConjDQ(transform)));\n\t// std::cout << \"lineVector_transformed: \" << line.transpose() << std::endl;\t\t\t\n\treturn line;\n}\n\nRowVectorXd DQoperations::transformLineVector(RowVectorXd lineVector, Matrix<double,8,1> transform)\n{\n\tMatrix<double,8,1> line_dq;\n\tline_dq << 0, lineVector(0), lineVector(1), lineVector(2), 0, 0, 0, 0;\n\tline_dq = mulDQ(transform, mulDQ(line_dq, classicConjDQ(transform)));\n\tlineVector.resize(3);\n\tlineVector << line_dq(1), line_dq(2), line_dq(3);\n\treturn lineVector;\n}\n\nRowVectorXd DQoperations::transformLine6dVector(RowVectorXd lineVector, Matrix<double,8,1> transform)\n{\n\t// std::cout << \"lineVector: \" << lineVector << std::endl;\t\t\n\t// std::cout << \"transform: \" << transform.transpose() << std::endl;\t\t\n\tMatrix<double,8,1> line_dq;\n\tline_dq << 0, lineVector(0), lineVector(1), lineVector(2), 0, lineVector(3), lineVector(4), lineVector(5);\n\tline_dq = mulDQ(transform, mulDQ(line_dq, classicConjDQ(transform)));\n\tlineVector.resize(6);\n\tlineVector << line_dq(1), line_dq(2), line_dq(3), line_dq(5), line_dq(6), line_dq(7);\n\t// std::cout << \"lineVector_after: \" << lineVector << std::endl;\t\t\t\n\treturn lineVector;\n}\n\nRowVector3d DQoperations::transformPoint(RowVector3d point, Matrix<double,8,1> transform)\n{\n\tMatrix<double,8,1> point_dq;\n\tpoint_dq << 1, 0, 0, 0, 0, point(0), point(1), point(2);\t\n\tpoint_dq=DQoperations::mulDQ(DQoperations::mulDQ(transform, point_dq), DQoperations::combinedConjDQ(transform));\n\tpoint.resize(3);\n\tpoint << point_dq(5), point_dq(6), point_dq(7);\n\treturn point;\n}\n\nMatrix<double,8,1> DQoperations::htm2DQ(Matrix4d htm_original)\n{\n\t// std::cout << \"htm_original:\" << std::endl;\t\n\t// std::cout << htm_original << std::endl;\t\n\tMatrix<double,8,1> dq;\n\tMatrix3d htm_, htm_eye;\n\thtm_=htm_original.block<3,3>(0,0);\n\t// RowVector3d trans=RowVector3d(3, 4, 5);\n\thtm_eye =htm_-MatrixXd::Identity(3,3);\n EigenSolver<MatrixXd> eigensolver(htm_eye);\n\n std::vector<double> eigenVal, eigenVec;\n eigenVal.clear();\n eigenVal.resize(htm_.rows());\n eigenVec.clear();\n\n int index=0;\n for(int i=0;i<htm_.rows(); i++)\n {\n eigenVal[i]=abs(eigensolver.eigenvalues()[i]);\n if(eigenVal[i]<eigenVal[index])\n \tindex=i;\n }\n\n if (eigenVal[index]>0.001)\n std::cerr << \"Rotation Matrix seems dubious\\n\";\n\tRowVector3d vecAxis=eigensolver.eigenvectors().col(index).real();\n\tif (abs(vecAxis.norm()-1)>0.0001)\n\t\tstd::cerr << \"Non-unit rotation axis\"<< std::endl;\n\n\tdouble twoCosTheta=htm_.trace()-1;\n\t// std::cout << \"twoCosTheta:\" << twoCosTheta <<std::endl; \n\tRowVector3d twoSinThetaV= RowVector3d ((htm_(2,1)-htm_(1,2)), (htm_(0,2)-htm_(2,0)), (htm_(1,0)-htm_(0,1)));\n\tdouble twoSinTheta=vecAxis*twoSinThetaV.transpose();\n\t// std::cout << \"twoSinTheta:\" << twoSinTheta <<std::endl;\n\tdouble theta= std::atan2(twoSinTheta,twoCosTheta);\n\t// std::cout << \"theta:\" << theta <<std::endl;\n\tRowVector4d rot_q=RowVector4d(cos(theta/2), sin(theta/2)*vecAxis(0), sin(theta/2)*vecAxis(1), sin(theta/2)*vecAxis(2));\n\t// std::cout << \"rot_q:\" << rot_q <<std::endl;\n\tRowVector4d trans_q=RowVector4d(0., htm_original(0,3), htm_original(1,3), htm_original(2,3));\n\n\tRowVector4d prodRotTrans=0.5*DQoperations::multQuat(trans_q, rot_q);\n\n\tdq<< rot_q(0),\n\t\trot_q(1),\n\t\trot_q(2),\n\t\trot_q(3),\n\t\tprodRotTrans(0),\n\t\tprodRotTrans(1),\n\t\tprodRotTrans(2),\n\t\tprodRotTrans(3);\n\n\treturn dq;\n}\n\nRowVector4d DQoperations::multQuat(RowVector4d p, RowVector4d q)\n{\n\tdouble s1=\tp(0);\n\tdouble s2=\tq(0);\n\tRowVector3d v1= RowVector3d(p(1), p(2), p(3));\n\tRowVector3d v2= RowVector3d(q(1), q(2), q(3));\n\tdouble term1= (s1*s2-v1.dot(v2));\n\tRowVector3d term2=s1*v2+s2*v1 +v1.cross(v2);\n\tRowVector4d result=RowVector4d(term1, term2(0), term2(1), term2(2));\n\treturn result;\n}\n\nRowVector4d DQoperations::conjQuat(RowVector4d p)\n{\n\tRowVector4d result;\n\tresult=RowVector4d(p(0),-p(1),-p(2),-p(3));\n\treturn result;\n}\n\n\nMatrix4d DQoperations::dq2HTM(Matrix<double,8,1> dq)\n{\n RowVector4d qrr, qtt;\n\tRowVector3d u;\n\n qrr=RowVector4d(dq(0),dq(1),dq(2),dq(3));\n qtt=RowVector4d(dq(4),dq(5),dq(6),dq(7));\n qtt=2*DQoperations::multQuat(qtt, DQoperations::conjQuat(qrr));\n\n double theta=2*acos(qrr(0));\n // std::cout << \"theta_dq2HTM: \" << theta << std::endl; \n if (theta!=0)\n \tu=RowVector3d(qrr(1),qrr(2),qrr(3))/sin(theta/2);\n else\n \tu=RowVector3d(0, 0, 1);\n\n Matrix3d skw, rot;\n skw<< 0, -u(2), u(1),\n \t\tu(2), 0., -u(0),\n \t\t-u(1), u(0), 0;\n\n rot=MatrixXd::Identity(3,3)+sin(theta)*skw+skw*skw*(1-cos(theta));\n Matrix4d htm_;\n htm_<< rot(0,0), rot(0,1), rot(0,2), qtt(1),\n \t\trot(1,0), rot(1,1), rot(1,2), qtt(2),\n \t\trot(2,0), rot(2,1), rot(2,2), qtt(3),\n \t\t0, 0, 0, 1;\t\n\treturn htm_;\n}\n\nMatrix<double,8,1> DQoperations::classicConjDQ(Matrix<double,8,1> dq) // p*+ iq*\n{\n\tMatrix<double,8,1> dq_result;\n\tdq_result << dq(0), -dq(1), -dq(2), -dq(3), dq(4), -dq(5), -dq(6), -dq(7);\n\treturn dq_result;\n}\nMatrix<double,8,1> DQoperations::dualConjDQ(Matrix<double,8,1> dq) // p-iq\n{\n\tMatrix<double,8,1> dq_result;\t\n\tdq_result<<dq(0), dq(1), dq(2), dq(3), -dq(4), -dq(5), -dq(6), -dq(7);\n\treturn dq_result;\n}\n\nMatrix<double,8,1> DQoperations::combinedConjDQ(Matrix<double,8,1> dq) //p* - iq* same as conjdualq in matlab\n{\n\tMatrix<double,8,1> dq_result;\t\n\tdq_result<<dq(0), -dq(1), -dq(2), -dq(3), -dq(4), dq(5), dq(6), dq(7);\t\n\treturn dq_result;\n}\n\nMatrix<double,8,1> DQoperations::inverseDQ(Matrix<double,8,1> dq) \n{\n\tRowVector4d rot; \n\tRowVector4d trans;\n\tdq2rotAndTransQuat(dq, rot, trans);\n\tdq << conjQuat(rot), 0.5*multQuat(conjQuat(rot), -trans);\n\treturn dq;\n}\n\n\nMatrix<double,8,1> DQoperations::screw2DQ(double theta, RowVector3d axis, double d, RowVector3d moment)\n{\n\n\tRowVector4d q_rot, q_tr;\n\tq_rot << cos(theta/2),\n\t\t\tsin(theta/2)*axis;\n\n\tq_tr << -(d/2)*sin(theta/2),\n\t\t\t(d/2)*cos(theta/2)*axis+sin(theta/2)*moment;\n\n\tMatrix<double, 8,1> dq;\n\tdq << q_rot(0), q_rot(1), q_rot(2), q_rot(3), q_tr(0), q_tr(1), q_tr(2), q_tr(3); \n\n\treturn dq;\n}\n\nMatrixXd DQoperations::transformJacobian(MatrixXd jacobian_8d, Matrix<double,8,1> dq)\n{\n\tstd::cout << \"jacobian_8d_beforeTransform: \" << std::endl;\n\tstd::cout << jacobian_8d << std::endl;\n\tMatrixXd jacobian, jacobian_6d;\n\tjacobian_6d = MatrixXd::Zero(6, jacobian_8d.cols());\n\tjacobian = jacobian_6d;\n\t// relJacobian_8d = MatrixXd::Zero(8, (jacobian_ref.cols() + jacobian_tool.cols()));\n\tjacobian_6d.block(0, 0, 3, jacobian_8d.cols()) = jacobian_8d.block(5, 0, 3, jacobian_8d.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian_8d.cols()) = jacobian_8d.block(1, 0, 3, jacobian_8d.cols());\n\t// RowVector3d p_rel;\n\n\t// Matrix4d pose_ref = DQoperations::dq2HTM(p_ee_ref);\n\t// Matrix4d pose_tool = DQoperations::dq2HTM(p_ee_tool);\n\t// p_rel << (pose_ref(0,3) - pose_tool(0,3)), (pose_ref(1,3) - pose_tool(1,3)), (pose_ref(2,3) - pose_tool(2,3));\n\t// ROS_INFO(\"here 24\");\n\t\n\t// std::cout << \"relJacobian: \" << std::endl;\n\tfor (int i = 0; i < (jacobian_8d.cols()); i++)\n\t{\n\t\t// std::cout << \"before transformation: \" << DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref)) << std::endl;\n\t\tjacobian.col(i) << DQoperations::transformLine6dVector(jacobian_6d.col(i).transpose(), dq).transpose();\n\t\t// std::cout << relJacobian.col(i).transpose() << std::endl;\t\t\n\t\t// relJacobian.col(i + jacobian_ref.cols()) = DQoperations::transformLine6dVector(jacobian_6d.col(i), DQoperations::classicConjDQ(p_ee_ref));\n\t}\n\t// ROS_INFO(\"here 25\");\n\tjacobian_6d.block(0, 0, 3, jacobian.cols()) = jacobian.block(3, 0, 3, jacobian.cols());\n\tjacobian_6d.block(3, 0, 3, jacobian.cols()) = jacobian.block(0, 0, 3, jacobian.cols());\t\n\n\tjacobian_8d = MatrixXd::Zero(8, jacobian.cols());\n\tjacobian_8d.block(1, 0, 3, jacobian_6d.cols()) = jacobian_6d.block(0, 0, 3, jacobian_6d.cols());\n\tjacobian_8d.block(5, 0, 3, jacobian_6d.cols()) = jacobian_6d.block(3, 0, 3, jacobian_6d.cols()) ; \n\tstd::cout << \"jacobian_8d_afterTransform: \" << std::endl;\n\tstd::cout << jacobian_8d << std::endl;\n\treturn jacobian_8d;\n}\n\nMatrix<double,8,1> DQoperations::rotTrans2dq(RowVector4d rot, RowVector4d trans)\n{\n\tMatrix<double,8,1> dq;\n\tRowVector4d trans_quat = DQoperations::multQuat(trans, rot)/2;\n\tdq << rot(0), rot(1), rot(2), rot(3), trans_quat(0), trans_quat(1), trans_quat(2), trans_quat(3);\n\treturn dq;\n}\n\nvoid DQoperations::dq2rotAndTransQuat(Matrix<double,8,1> dq, RowVector4d &rot, RowVector4d &trans)\n{\n\t// translation then rotation.\n\trot << dq(0), dq(1), dq(2), dq(3);\n\ttrans << dq(4), dq(5), dq(6), dq(7);\n\ttrans= 2*DQoperations::multQuat(conjQuat(rot), trans);\n}\n\nMatrix<double,8,1> DQoperations::twist2dq(Matrix<double,8,1> dq_twist) \n{\n\tMatrix<double,8,1> dq;\n\tdouble theta_e, d_e;\n\tRowVector3d l_e, m_e, w, v;\n\n\tw << dq_twist(1,0), dq_twist(2,0), dq_twist(3,0);\n\tstd::cout << \"w: \" << w; \n\tv << dq_twist(5,0), dq_twist(6,0), dq_twist(7,0);\n\tstd::cout << \"v: \" << v;\n\ttheta_e = w.norm();\n\tif (theta_e != 0)\n\t{\n\t\tl_e = w/theta_e;\n\t\td_e = (l_e.transpose()*v)(0,0);\n\t\tm_e = (v - d_e*l_e)/theta_e;\n\t\t// dq = DQoperations::screw2DQ;\n\t\tdq = DQoperations::screw2DQ(theta_e, l_e, d_e, m_e);\n\t} \n\telse\n\t{\n\t\tdq << 1, 0, 0, 0, 0, 0, 0, 0;\n\t}\n\tstd::cout << \"dq_fromTwist: \" << dq.transpose();\n\treturn dq;\n}\n\nMatrix<double,8,1> DQoperations::dq2twist(Matrix<double,8,1> dq) \n{\n\tMatrix<double,8,1> dq_twist;\n\tdouble theta_e, d_e; \n\tRowVector3d l_e, m_e, v, w;\n\tDQoperations::dq2screw(dq, theta_e, d_e, l_e, m_e) ;\n\tw = l_e*theta_e;\n\tstd::cout << \"w_dq2twist: \" << w << std::endl;\n\tv = l_e*d_e + m_e*theta_e;\n\tstd::cout << \"v_dq2twist: \" << v << std::endl;\t\n\tDQoperations::dq2screw(dq, theta_e, d_e, l_e, m_e);\n\tdq_twist << 0, w.transpose(), 0 , v.transpose(); \n\treturn dq_twist;\n}\n\nvoid DQoperations::dq2screw(Matrix<double,8,1> dq, double &theta_e, double &d_e, RowVector3d &l_e, RowVector3d &m_e) \n{\n\tdouble eps_theta=0.05; /*0.1 degrees*/ \n\tdouble sr, sd, theta;\n\tRowVector3d vr, vd;\n\t// std::cout << \"dq(dq2screw): \" << dq.transpose() << std::endl;\n\t// std::cout << \"dq(0,0): \" << dq(0,0) << std::endl;\n\tif(dq(0,0)<0)\n\t{\n\t\tdq=-dq;\n\t\t// std::cout << \"dq(dq2screw): \" << dq.transpose() << std::endl;\n\t}\t\n\n\tsr=dq(0);\n\n\t// if(sr > 1.0)\n\t// \tsr =1.0 ;\n\t// else if(sr < -1.0)\n\t// \tsr=-1;\n\n\tvr << dq(1), dq(2), dq(3);\n\tsd=dq(4);\n\tvd << dq(5), dq(6), dq(7);\n\ttheta_e=2*acos(sr);\n\t// std::cout << \"sr: \" << sr << std::endl;\n\tdouble absTheta=fabs(theta_e);\n\t// std::cout << \"abs(theta_e): \" << absTheta << std::endl;\n\tif (absTheta > eps_theta && absTheta < (2*M_PI -eps_theta))\n\t{\n\t\t// std::cout << \"check:: theta_e: \" << absTheta << \"eps_theta: \" << eps_theta << \"(2*M_PI -eps_theta): \" << (2*M_PI -eps_theta) << std::endl;\n\t\t// std::cout << \"definitly here, vr: \" << std::endl;\n\t\t// std::cout << \"vr: \" << vr << std::endl;\n\t\t// std::cout << \"vr.norm \" << vr.norm() << std::endl;\n\t\t// std::cout << \"vr/vr.norm \" << vr/vr.norm() << std::endl;\n\t\tl_e=vr/vr.norm();\n\t\td_e=-sd*(2/(vr.norm()));\n\t\tm_e=(vd-sr*0.5*d_e*l_e)/vr.norm();\n\t}\t\n\telse\n\t{\n\t\t// std::cout << \"why do you have to come here: \" << std::endl;\n\t\t// std::cout << \"check:: theta_e: \" << absTheta << \"eps_theta: \" << eps_theta << \"(2*M_PI -eps_theta): \" << (2*M_PI -eps_theta) << std::endl;\n\t\tRowVector4d qrr, qdd, tt;\n\t\tRowVector3d t;\n\t\tqrr << dq(0), dq(1), dq(2), dq(3);\t\n\t\tqdd << dq(4), dq(5), dq(6), dq(7);\n\t\ttt=2*DQoperations::multQuat(qdd, DQoperations::conjQuat(qrr));\n\t\tt << tt(1), tt(2), tt(3); \n\t\td_e=t.norm();\n\t\tif (d_e == 0)\n\t\t{\n\t\t\tl_e << 0,0,1;\n\t\t}\n\t\telse l_e=t/d_e;\n\t\tm_e << 0,0,0;\t\t\t\n\t}\n\t// std::cout << \"dq:\" << dq << std::endl;\n\t// std::cout << \"theta:\" << theta_e << std::endl;\n\t// std::cout << \"l_e:\" << l_e << std::endl;\n\t// std::cout << \"d_e:\" << d_e << std::endl;\n\t// std::cout << \"m_e:\" << m_e << std::endl;\n}\n\nMatrix<double,8,1> DQoperations::mulDQ(Matrix<double,8,1> p, Matrix<double,8,1> q)\n{\n\tRowVector4d p1, p2, q1, q2;\n\tp1<< p(0), p(1), p(2), p(3);\t\n\tp2<< p(4), p(5), p(6), p(7);\t\n\tq1<< q(0), q(1), q(2), q(3);\t\n\tq2<< q(4), q(5), q(6), q(7);\t\n\t\n\tMatrix<double,8,1> result;\n\tresult << DQoperations::multQuat(p1, q1).transpose(), (DQoperations::multQuat(p1, q2)+DQoperations::multQuat(p2, q1)).transpose();\n\t// std::cout << \"result:\" << std::endl;\n\t// std::cout << result << std::endl;\n\n\treturn result;\n}\n\n\nstd::vector<Matrix<double,8,1> > DQoperations::fkm_dual(RowVectorXd q /*q is defined as [q1 d1 q2 d2 ...]*/, std::vector<RowVector3d> u, std::vector<RowVector3d> p)\n{\n\tint joint_size=q.size()/2;\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\tscrewDispalcementArray.clear();\n\tscrewDispalcementArray.resize(joint_size);\n\n\tif (u.size()!=joint_size || p.size()!=joint_size)\n\t{\n\t\tstd::cerr << \"Size mismatch error in the input for forward kinematic computation.\" << std::endl;\n\t\tstd::cerr << \"u_size\"<< u.size()<< std::endl;\n\t\tstd::cerr << \"p_size\"<< p.size()<< std::endl;\n\t\tstd::cerr << \"joint_size\"<< joint_size<< std::endl;\n\t\treturn screwDispalcementArray;\n\t}\n\n\tfor (int i=0;i<joint_size; i++)\n\t{\n\t\tdouble theta_i=q[2*i];\n\t\tRowVector3d u_i=u[i];\n\t\tRowVector3d p_i=p[i];\n\t\tdouble d_i=q[2*i+1];\n\t\tMatrix<double,8,1> screwDispalcementArray_i;\n\t\tscrewDispalcementArray_i= DQoperations::screw2DQ(theta_i, u_i, d_i, p_i.cross(u_i));\n\t\tif (i==0)\n\t\t\tscrewDispalcementArray[i]=screwDispalcementArray_i;\n\t\telse\n\t\t\tscrewDispalcementArray[i]=DQoperations::mulDQ(screwDispalcementArray[i-1],screwDispalcementArray_i);\n\t}\n\n\n\treturn screwDispalcementArray;\t\n}\n\nstd::vector<Matrix<double,8,1> > DQoperations::fkm_revolute_only(RowVectorXd q /*q is defined as [q1 q2 ...]*/, std::vector<RowVector3d> u, std::vector<RowVector3d> p)\n{\n\tint joint_size=q.size();\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\tscrewDispalcementArray.clear();\n\tscrewDispalcementArray.resize(joint_size);\n\n\tif (u.size()!=joint_size || p.size()!=joint_size)\n\t{\n\t\tstd::cerr << \"Size mismatch error in the input for forward kinematic computation.\" << \"u_size\"<< std::endl;\n\t\tstd::cerr << \"u_size\"<< u.size()<< std::endl;\n\t\tstd::cerr << \"p_size\"<< p.size()<< std::endl;\n\t\tstd::cerr << \"q_size\"<< joint_size<< std::endl;\n\t\treturn screwDispalcementArray;\n\t}\n\n\tfor (int i=0;i<joint_size; i++)\n\t{\n\t\tdouble theta_i=q[i];\n\t\tRowVector3d u_i=u[i];\n\t\tRowVector3d p_i=p[i];\n\t\tdouble d_i=0;\n\t\tMatrix<double,8,1> screwDispalcementArray_i;\n\t\tscrewDispalcementArray_i= DQoperations::screw2DQ(theta_i, u_i, d_i, p_i.cross(u_i));\n\t\tif (i==0)\n\t\t\tscrewDispalcementArray[i]=screwDispalcementArray_i;\n\t\telse\n\t\t\tscrewDispalcementArray[i]=DQoperations::mulDQ(screwDispalcementArray[i-1],screwDispalcementArray_i);\n\t}\n\n\n\treturn screwDispalcementArray;\t\t\n}\n\nMatrixXd DQoperations::jacobian_revolute_only(RowVectorXd q /*q is defined as [q1 q2 ...]*/, std::vector<RowVector3d> u, std::vector<RowVector3d> p , Matrix<double,8,1> pose_ee_init)\n{\n\tint joint_size=q.size();\n\n\tMatrixXd jacobian_result(6,joint_size);\n\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\tscrewDispalcementArray.clear();\n\tscrewDispalcementArray.resize(joint_size);\n\n\tscrewDispalcementArray=\tDQoperations::fkm_revolute_only(q, u, p);\n\tMatrix<double,8,1> screwDispalcementArray_i, screw_axis_i, pose_i;\n\t\n\tscrewDispalcementArray_i= screwDispalcementArray[joint_size-1];/*The numbering in C++ starts at 0*/\n\t\n\tscrewDispalcementArray_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_ee_init), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\n\tRowVector3d pose_ee_now;\n\tMatrix4d htm_ee_now;\n\thtm_ee_now=DQoperations::dq2HTM(screwDispalcementArray_i);\n\t// pose_ee_now << htm_ee_now(0,3), htm_ee_now(1,3), htm_ee_now(2,3);\n\t// std::cout << \"pose_ee_now_including_rotation(using dq2HTM): \" << pose_ee_now << std::endl;\n\tpose_ee_now << screwDispalcementArray_i(5), screwDispalcementArray_i(6), screwDispalcementArray_i(7); \n\t// std::cout << \"pose_ee_now_no_rotation(original): \" << pose_ee_now << std::endl;\t\n\tjacobian_result.col(0)<< (p[0].cross(u[0])- pose_ee_now.cross(u[0])).transpose(), u[0].transpose();/*writing Jacobian seperately for first joint for faster operation*/\n\t\n\tfor(int i=1; i<joint_size; i++)\n\t{\n\t\tscrewDispalcementArray_i=screwDispalcementArray[i-1];\n\t\n\t\tscrew_axis_i<< 0, u[i].transpose(), 0, (p[i].cross(u[i])).transpose();\n\t\n\t\tscrew_axis_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, screw_axis_i), DQoperations::classicConjDQ(screwDispalcementArray_i));\t\n\t\n\t\tRowVector3d u_i, p_i;\n\t\tu_i << screw_axis_i(1), screw_axis_i(2), screw_axis_i(3);\n\t\tpose_i << 1, 0, 0, 0, 0, p[i].transpose();\n\t\tpose_i= DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_i), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\tp_i << pose_i(5), pose_i(6), pose_i(7);\n\t\tjacobian_result.col(i) << (p_i.cross(u_i)- pose_ee_now.cross(u_i)).transpose(), u_i.transpose(); \t\n\t}\n\n\treturn jacobian_result;\n}\n\nMatrixXd DQoperations::jacobian_dual_vm(RowVectorXd q /*q is defined as [q1 d1 q2 d2 ...]*/, RowVectorXd joint_type, std::vector<RowVector3d> u, std::vector<RowVector3d> p , Matrix<double,8,1> pose_ee_init)\n{\n\t// Some changes from regular jacobian calculation:\n\t// 1. q format is [q1 d1 q2 d2 ...] instead of [q1 q2 ...].\n\t// 2. We are using fkm_dual here instead of fkm_revolute_only.\n\t// 3. We need extra input(RowVectorXd joint_type) to tell which joints are revolute and which are prismatic, 0 for revolute and 1 for prismatic.\n\t// 4. To get the ee velocity from joint velocity you just have to make a column array with active joints, i.e., if is revolute, just put the joint velocity of the revolute joint in the respective position and similarly from prismatic joint.\n\n\tint joint_size=q.size()/2;\n\n\tMatrixXd jacobian_result(6,joint_size);\n\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\tscrewDispalcementArray.clear();\n\tscrewDispalcementArray.resize(joint_size);\n\n\tscrewDispalcementArray=\tDQoperations::fkm_dual(q, u, p);\n\tMatrix<double,8,1> screwDispalcementArray_i, screw_axis_i, pose_i;\n\t\n\tscrewDispalcementArray_i= screwDispalcementArray[joint_size-1];/*The numbering in C++ starts at 0*/\n\t\n\tscrewDispalcementArray_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_ee_init), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\n\tRowVector3d pose_ee_now;\n\tMatrix4d htm_ee_now;\n\thtm_ee_now=DQoperations::dq2HTM(screwDispalcementArray_i);\n\t// pose_ee_now << htm_ee_now(0,3), htm_ee_now(1,3), htm_ee_now(2,3);\n\t// std::cout << \"pose_ee_now_including_rotation(using dq2HTM): \" << pose_ee_now << std::endl;\n\tpose_ee_now << screwDispalcementArray_i(5), screwDispalcementArray_i(6), screwDispalcementArray_i(7); \n\t// std::cout << \"pose_ee_now_no_rotation(original): \" << pose_ee_now << std::endl;\t\n\tif(joint_type(0)==0)\n\t\tjacobian_result.col(0)<< (p[0].cross(u[0])- pose_ee_now.cross(u[0])).transpose(), u[0].transpose();/*writing Jacobian seperately for first joint for faster operation*/\n\telse\n\t\tjacobian_result.col(0)<< u[0].transpose(), 0, 0, 0;\n\n\tfor(int i=1; i<joint_size; i++)\n\t{\n\t\tscrewDispalcementArray_i=screwDispalcementArray[i-1];\n\t\n\t\tscrew_axis_i<< 0, u[i].transpose(), 0, (p[i].cross(u[i])).transpose();\n\t\n\t\tscrew_axis_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, screw_axis_i), DQoperations::classicConjDQ(screwDispalcementArray_i));\t\n\t\n\t\tRowVector3d u_i, p_i;\n\t\tu_i << screw_axis_i(1), screw_axis_i(2), screw_axis_i(3);\n\t\tpose_i << 1, 0, 0, 0, 0, p[i].transpose();\n\t\tpose_i= DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_i), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\tp_i << pose_i(5), pose_i(6), pose_i(7);\n\t\tif(joint_type(i)==0)\n\t\t\tjacobian_result.col(i) << (p_i.cross(u_i)- pose_ee_now.cross(u_i)).transpose(), u_i.transpose(); \t\n\t\telse\n\t\t\tjacobian_result.col(i) << u_i.transpose(), 0, 0, 0;\n\t}\n\n\treturn jacobian_result;\n}\n\ndouble DQoperations::normalizeAngle(double theta)\n{\n\tif (theta < 0)\n\t\twhile (theta<0)\n\t\t\ttheta= theta+ 2*M_PI;\n\telse if(theta >=2*M_PI)\n\t\twhile (theta>=2*M_PI)\n\t\t\ttheta=theta-2*M_PI;\n\treturn theta;\n}\n\nMatrixXd DQoperations::invDamped_8d(MatrixXd jacobian_8d, double mu)\n{\n\tMatrixXd jacobian_damped_, A; \n\t// std::cout << \"jacobian_.size: \" << jacobian_.rows() << \":\" << jacobian_.cols() << std::endl; \n\tint joint_size = jacobian_8d.cols();\n\tA= jacobian_8d.transpose()*jacobian_8d + mu*MatrixXd::Identity(joint_size, joint_size); \n\tjacobian_damped_=((A.inverse())*jacobian_8d.transpose());\t\n\treturn jacobian_damped_;\n}\n// This is the proper error i.e screw to desired from current in base frame\n\n\ndouble DQoperations::get_error_screw(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_ee_desired, RowVector3d &v_e, RowVector3d &w_e)\n{\n\tMatrix<double,8,1> pose_error;\n\tpose_error=DQoperations::mulDQ(pose_ee_desired, DQoperations::classicConjDQ(pose_now));\n\t// std::cout << \"pose_now: \" << pose_now.transpose() << std::endl;\n\t// std::cout << \"pose_ee_desired: \" << pose_ee_desired.transpose() << std::endl;\n\t// std::cout << \"pose_error: \" << pose_error.transpose() << std::endl;\n\tRowVector3d l_e, m_e;\n\tdouble theta_e, d_e;\n\tDQoperations::dq2screw(pose_error, theta_e, d_e, l_e, m_e);\n\ttheta_e=normalizeAngle(theta_e);\n\n\tv_e = theta_e*m_e + d_e*l_e;\n\tw_e = theta_e*l_e;\n\n\tdouble norm_error;\n\tnorm_error=v_e.norm()+w_e.norm();\n\t// std::cout << \"norm_error:\" << norm_error << std::endl;\n\treturn norm_error;\n}\n\n// This is the Erol's error i.e screw to current to desired in base frame\ndouble DQoperations::get_error_screw_param(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_ee_desired, RowVector3d &v_e, RowVector3d &w_e)\n{\n\tMatrix<double,8,1> pose_error;\n\tpose_error=DQoperations::mulDQ(pose_now, DQoperations::classicConjDQ(pose_ee_desired));\n\t// std::cout << \"pose_now: \" << pose_now.transpose() << std::endl;\n\t// std::cout << \"pose_ee_desired: \" << pose_ee_desired.transpose() << std::endl;\n\t// std::cout << \"pose_error: \" << pose_error.transpose() << std::endl;\n\tRowVector3d l_e, m_e;\n\tdouble theta_e, d_e;\n\tDQoperations::dq2screw(pose_error, theta_e, d_e, l_e, m_e);\n\ttheta_e=normalizeAngle(theta_e);\n\n\tv_e = theta_e*m_e + d_e*l_e;\n\tw_e = theta_e*l_e;\n\n\tdouble norm_error;\n\tnorm_error=v_e.norm()+w_e.norm();\n\t// std::cout << \"norm_error:\" << norm_error << std::endl;\n\treturn norm_error;\n}\n\nvoid DQoperations::dqEigenToDQdouble(RowVectorXd dq_eigen, std::vector<double> &dq_double)\n{\n\tdq_double.clear();\n\t// dq_double.resize(dq_eigen.size());\n\t// std::cout << \"dq_eigen.rows(): \" << dq_eigen.rows() << \"cols: \" << dq_eigen.cols() << std::endl;\n\t// std::cout << \"dq_double:\" << std::endl;\n\tfor (int i=0; i< dq_eigen.size(); i++)\n\t{\n\t\tdq_double.push_back(dq_eigen(i));\n\t\t// std::cout << dq_double[i] << std::endl;\n\t}\n}\n\nvoid DQoperations::doubleToDQ(Matrix<double,8,1> &dq_eigen, std::vector<double> dq_double)\n{\n\t// std::cout << \"dq_double:\" << std::endl;\n\tfor (int i=0; i< dq_double.size(); i++)\n\t{\n\t\tdq_eigen(i)=dq_double[i];\n\t}\n}\n\nstd::vector<double> DQoperations::dqEigenToDQdouble(RowVectorXd dq_eigen)\n{\n\tstd::vector<double> dq_double;\n\tdq_double.clear();\n\tfor (int i=0; i< dq_eigen.size(); i++)\n\t{\n\t\tdq_double.push_back(dq_eigen(i));\n\t}\n\treturn dq_double;\n}\n\n\n\nstd::vector<double> DQoperations::DQToDouble(Matrix<double,8,1> dq_eigen)\n{\n\tstd::vector<double> dq_double;\n\tdq_double.clear();\n\tfor (int i=0; i< 8; i++)\n\t{\n\t\tdq_double.push_back(dq_eigen(i,0));\n\t}\n\treturn dq_double;\n}\n\nstd::vector<double> DQoperations::RowVectorToDouble(RowVectorXd eigenVector)\n{\n\tstd::vector<double> dq_double;\n\tdq_double.clear();\n\tfor (int i=0; i< eigenVector.size(); i++)\n\t{\n\t\tdq_double.push_back(eigenVector(i));\n\t}\n\treturn dq_double;\n}\n\n" }, { "alpha_fraction": 0.6494355201721191, "alphanum_fraction": 0.6707178950309753, "avg_line_length": 39.51203536987305, "blob_id": "da8cdab1925e97075cc114a89d4678373df7709e", "content_id": "518a47cd83d7292c18cce4a44116afa9f04d33e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18513, "license_type": "no_license", "max_line_length": 181, "num_lines": 457, "path": "/dq_robotics/src/test/kdl_convntnl_controller.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/DQoperations.h>\n#include <dq_robotics/baxter_dq.h>\n#include <dq_robotics/dq_controller.h>\n#include <dq_robotics/DualArmPlotData.h>\n#include <dq_robotics/baxter_poseControl_server.h>\n#include <sensor_msgs/JointState.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <math.h>\n#include \"baxter_core_msgs/JointCommand.h\"\n#include \"dq_robotics/BaxterControl.h\"\n#include <kdl/frames.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chainidsolver_recursive_newton_euler.hpp>\n#include <kdl/chainjnttojacdotsolver.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <dynamic_reconfigure/server.h>\n#include <dq_robotics/kdl_controllerConfig.h>\n#include \"baxter_core_msgs/JointCommand.h\"\n// ros::NodeHandle node_;\nbool dynRcnfgr_toggle;\ndouble K_p, K_d, K_i, total_time, theta_init, theta_final, norm_error;\nros::WallTime start_, end_;\nstd::string robot_desc_string;\t\nKDL::ChainIdSolver_RNE *idsolver;\nKDL::ChainJntToJacDotSolver *jacDotKDL;\nKDL::ChainJntToJacSolver *jacKDL;\nKDL::Tree tree;\nKDL::Chain chain;\nKDL::Vector g;\nMatrix4d crclCntr_dsrdTraj, startPose_dsrdTraj;\nMatrix<double,8,1> pe_init_right, pe_now_right, crclCntr_dsrdTraj_dq, startPose_dsrdTraj_dq, lineTraj_dq_cc, pose_desired_right, vel_desired_right, acc_desired_right, acc_cmd_right;\nRowVectorXd q_right, q_vel_right, qdd_cmd;\nMatrixXd jacobian_6d_right, jacobian_6d_dot_right;\nBaxterPoseControlServer* baxter_controller;\ndouble time_now, theta, theta_d, theta_dd;\nRowVector3d v_e, w_e;\nKDL::JntArray q_kdl;\nKDL::JntArray dq_kdl;\nKDL::JntArray v_kdl;\nKDL::JntArray torque_kdl;\nKDL::Wrenches fext;\n// KDL::Twist jac_dot_q_dot;\nros::Publisher right_cmd_pub ;\nbaxter_core_msgs::JointCommand cmd;\ngeometry_msgs::PoseStamped desired_pose;\nros::Publisher pose_publisher;\nRowVector3d vel_cart, position_cart, acc_cart;\nRowVector3d angVel_cart, angPosition_cart, angAcc_cart;\n// RowVectorXd DQoperations::spatial2CartPoseError(Matrix<double,8,1> desired_pose, Matrix<double,8,1> current_pose)\n// RowVectorXd DQoperations::spatial2CartAcc(RowVectorXd screwAcc, RowVectorXd screwVel, RowVector3d ee_pose)\n\n// RowVectorXd DQoperations::spatial2CartVel(RowVectorXd screwVel, RowVector3d ee_pose)\n\n\n\nvoid initializeTraj()\n{\n\tlineTraj_dq_cc << 0, 0, 0, 1, 0, 0, 0, 0;\n\tcrclCntr_dsrdTraj << 1, 0, 0, 0.5,\n\t\t\t\t\t\t 0, 1, 0, 0,\n\t\t\t\t\t\t 0, 0, 1, 0.2,\n\t\t\t\t\t\t 0, 0, 0, 1;\n\tcrclCntr_dsrdTraj_dq = DQoperations::htm2DQ(crclCntr_dsrdTraj);\n\tstartPose_dsrdTraj << -1, 0, 0, 0,\n\t\t\t\t\t\t 0, 1, 0, -0.3,\n\t\t\t\t\t\t 0, 0, -1, 0,\n\t\t\t\t\t\t 0, 0, 0, 1;\n\tstartPose_dsrdTraj = crclCntr_dsrdTraj*startPose_dsrdTraj;\n\tstartPose_dsrdTraj_dq = DQoperations::htm2DQ(startPose_dsrdTraj);\n}\n\n\nbool initializeAccController(ros::NodeHandle &node_)\n{\n\tpose_publisher = node_.advertise<geometry_msgs::PoseStamped>(\"dq_robotics/desired_pose\", 1000);\n\tdesired_pose.header.frame_id = \"base\";\n\tdesired_pose.header.stamp = ros::Time::now();\n\tright_cmd_pub = node_.advertise<baxter_core_msgs::JointCommand>(\"/robot/limb/right/joint_command\", 1);\n\tcmd.mode = baxter_core_msgs::JointCommand::TORQUE_MODE;\n\tcmd.names.push_back(\"right_s0\");\n\tcmd.names.push_back(\"right_s1\");\n\tcmd.names.push_back(\"right_e0\");\n\tcmd.names.push_back(\"right_e1\");\n\tcmd.names.push_back(\"right_w0\");\n\tcmd.names.push_back(\"right_w1\");\n\tcmd.names.push_back(\"right_w2\");\n\tcmd.command.resize(cmd.names.size());\n\ttime_now = 0;\n\tdynRcnfgr_toggle = false;\n\n\tif(!node_.getParam(\"/robot_description\",robot_desc_string))\n\t {\n\t\t\tROS_ERROR(\"Could not find '/robot_description'.\");\n\t\t\treturn false;\n\t}\n\tif (!kdl_parser::treeFromString(robot_desc_string,tree))\n\t{\n\t\tROS_ERROR(\"Failed to construct KDL tree.\");\n\t\treturn false;\n\t}\n\n\n\tif (!tree.getChain(\"base\",\"right_hand\",chain)) \n\t{\n\t\tROS_ERROR(\"Failed to get chain from KDL tree.\");\n\t\treturn false;\n\t}\n\tnode_.param(\"/gazebo/gravity_x\",g[0],0.0);\n\tnode_.param(\"/gazebo/gravity_y\",g[1],0.0);\n\t// node_.param(\"/gazebo/gravity_z\",g[2],-9.8); // put it to zero to use baxter gravity comps. Try both\n\tnode_.param(\"/gazebo/gravity_z\",g[2],0.0); // put it to zero to use baxter gravity comps. Try both\n\t\n\tif (!baxter_controller->BaxterPoseControlServer::initializeController())\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\t\n\tROS_INFO(\"hello1\");\n\tif((jacKDL=new KDL::ChainJntToJacSolver (chain)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainJntToJacSolver.\");\n\t\treturn false;\n\t}\n\tROS_INFO(\"hello2\");\n\tif((jacDotKDL=new KDL::ChainJntToJacDotSolver (chain)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainJntToJacDotSolver.\");\n\t\treturn false;\n\t}\n\tROS_INFO(\"hello3\");\n\n\tif((idsolver=new KDL::ChainIdSolver_RNE(chain,g)) == NULL)\n\t{\n\t\tROS_ERROR(\"Failed to create ChainIDSolver_RNE.\");\n\t\treturn false;\n\t}\n\tROS_INFO(\"hello4\");\t\n\treturn 1;\n}\n\nvoid dynReconfgr_callback(dq_robotics::kdl_controllerConfig &config, uint32_t level) \n{\n\tif (config.start_controller)\n\t\tdynRcnfgr_toggle = true;\n\tK_p = config.accCntrl_K_p;\n\tK_d = config.accCntrl_K_d;\n\tK_i = config.accCntrl_K_i;\n\ttotal_time = config.accCntrl_total_time;\n\ttheta_init = config.accCntrl_theta_init;\n\ttheta_final = config.accCntrl_theta_final;\n \tROS_INFO(\"Reconfigure Request: K_p: %f, K_d: %f, K_i: %f, total_time: %f\", \n K_p, \n K_d, \n K_i, \n total_time);\n}\n\nvoid getCubicTheta()\n{\n\ttheta = (theta_init - 3.0 * (time_now * time_now) * (theta_init - theta_final)\n\t / (total_time * total_time)) + 2.0 * pow(time_now, 3.0) *\n\t(theta_init - theta_final) / pow(total_time, 3.0);\n\tstd::cout << \"time_now: \" << time_now << \"theta: \" << theta << std::endl;\n\t/* theta_d = -(6*time_now*(theta_init - theta_final))/total_time^2 - (6*time_now^2*(theta_init - theta_final))/total_time^3; */\n\ttheta_d = 6.0 * (time_now * time_now) * (theta_init - theta_final) /\n\tpow(total_time, 3.0) - 6.0 * time_now * (theta_init - theta_final) /\n\t(total_time * total_time);\n\n\t/* theta_dd = -(6*(theta_init - theta_final))/total_time^2 - (12*time_now*(theta_init - theta_final))/total_time^3; */\n\ttheta_dd = 12.0 * time_now * (theta_init - theta_final) / pow(total_time, 3.0) - 6.0 * (theta_init - theta_final) / (total_time*total_time);\n}\n\nvoid updateManipulatorState()\n{\n\t// ROS_INFO(\"updateManipulatorState\");\n\tstd::string arm =\"right\";\n\tbaxter_controller->BaxterPoseControlServer::update_rightAcc();\n\tif(!baxter_controller->BaxterPoseControlServer::importManipulatorState_accControl(arm, pe_init_right, pe_now_right, q_right, q_vel_right, jacobian_6d_right, jacobian_6d_dot_right))\n\t\tROS_INFO(\"%s arm can not be updated\", arm);\n}\n\nvoid getDesiredTraj()\n{\n\t// ROS_INFO(\"getDesiredTraj\");\n\tgetCubicTheta();\n\tMatrix<double,8,1> cc_startinPose_dq, l_startingPose, l_baseFrame; \t\n\tcc_startinPose_dq = DQoperations::classicConjDQ( DQoperations::mulDQ(DQoperations::classicConjDQ(crclCntr_dsrdTraj_dq), startPose_dsrdTraj_dq));\n\tl_startingPose = DQoperations::mulDQ(cc_startinPose_dq , DQoperations::mulDQ(lineTraj_dq_cc, DQoperations::classicConjDQ(cc_startinPose_dq )));\n\tl_baseFrame = DQoperations::mulDQ(startPose_dsrdTraj_dq, DQoperations::mulDQ(l_startingPose, DQoperations::classicConjDQ(startPose_dsrdTraj_dq)));\n \tRowVector3d axis, moment;\n \taxis << l_startingPose(1), l_startingPose(2), l_startingPose(3);\n \tmoment << l_startingPose(5), l_startingPose(6), l_startingPose(7);\n \tdouble d_traj = 0.05*theta;\n\tpose_desired_right = DQoperations::screw2DQ(theta, axis, d_traj, moment);\n\tpose_desired_right = DQoperations::mulDQ(startPose_dsrdTraj_dq, pose_desired_right);\n\tvel_desired_right = l_baseFrame*theta_d;\n\tacc_desired_right = l_baseFrame*theta_dd;\n\tdesired_pose.pose = DQoperations::DQ2geometry_msgsPose(pose_desired_right);\n\tpose_publisher.publish(desired_pose);\n}\n\nvoid getControlLaw_regulation()\n{\n\tvel_desired_right = RowVectorXd::Zero(8);\n\tacc_desired_right = RowVectorXd::Zero(8);\n\t// ROS_INFO(\"getControlLaw\");\n\t// get cmd acc for kdl\n\tMatrix<double,8,1> error_dq, vel_now_8d;\n\tnorm_error = DQoperations::get_error_screw_param(pe_now_right, pose_desired_right, v_e, w_e);\n\terror_dq << 0, w_e(0), w_e(1), w_e(2), 0, v_e(0), v_e(1), v_e(2);\n\t// ROS_INFO(\"getControlLaw_1\");\n\t// Notice negative sign in K_p term, because the twist error is from curr to des in base frame\n\t// std::cout << \"vel_now: \" << jacobian_6d_right*q_vel_right.transpose() << std::endl;\n\tRowVectorXd vel_now = jacobian_6d_right*q_vel_right.transpose();\n\tvel_now_8d << 0, vel_now(0), vel_now(1), vel_now(2), 0, vel_now(3), vel_now(4), vel_now(5); \n\tstd::cout << \"vel_now_8d: \" << vel_now_8d.transpose() << std::endl;\n\tacc_cmd_right = acc_desired_right + K_d*(vel_desired_right - vel_now_8d) - K_p*(error_dq);\n\tstd::cout << \"acc_cmd_right: \" << acc_cmd_right.transpose() << std::endl;\n\t// ROS_INFO(\"getControlLaw_2, acc_cmd_right.rows(): %d, acc_cmd_right.cols(): %d \", acc_cmd_right.rows(), acc_cmd_right.cols());\n\tRowVectorXd acc_cmd_6d = RowVectorXd::Zero(6);\n\t\n\tacc_cmd_6d << acc_cmd_right(1,0), acc_cmd_right(2,0), acc_cmd_right(3,0), acc_cmd_right(5,0), acc_cmd_right(6,0), acc_cmd_right(7,0);\n\tstd::cout << \"acc_cmd_6d : \" << acc_cmd_6d.transpose() << std::endl;\n\t// ROS_INFO(\"getControlLaw_3\");\n\tMatrixXd jacobian_8d = MatrixXd::Zero(8, jacobian_6d_right.cols());\n\t// ROS_INFO(\"getControlLaw_4\");\n\tjacobian_8d.block(1, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(0, 0, 3, jacobian_8d.cols());\n\tjacobian_8d.block(5, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(3, 0, 3, jacobian_8d.cols());\t\n\t// ROS_INFO(\"getControlLaw_5\");\n\tdouble mu = 0.0001;\n\tMatrixXd jac_inv_damped = DQoperations::invDamped_8d(jacobian_8d, mu);\n\t// std::cout << \"acc_cart1: \" << std::endl;\n\t// std::cout << acc_cmd_6d.transpose() << std::endl;\n\t// std::cout << \"acc_cart2: \" << std::endl;\n\t// std::cout << - jacobian_6d_dot_right*q_vel_right.transpose() << std::endl;\t\n\t// ROS_INFO(\"getControlLaw_7\");\n\tRowVectorXd acc_term_8d= RowVectorXd::Zero(8);\n\tacc_term_8d = DQoperations::twistEigen2DQEigen(acc_cmd_6d.transpose() - jacobian_6d_dot_right*q_vel_right.transpose()); \n\tqdd_cmd = jac_inv_damped*acc_term_8d.transpose();\n\tstd::cout << \"qdd_cmd: \" << qdd_cmd << std::endl;\n}\n\nvoid getControlLaw()\n{\n\t// ROS_INFO(\"getControlLaw\");\n\t// get cmd acc for kdl\n\tMatrix<double,8,1> error_dq, vel_now_8d;\n\tnorm_error = DQoperations::get_error_screw_param(pe_now_right, pose_desired_right, v_e, w_e);\n\terror_dq << 0, w_e(0), w_e(1), w_e(2), 0, v_e(0), v_e(1), v_e(2);\n\t// ROS_INFO(\"getControlLaw_1\");\n\t// Notice negative sign in K_p term, because the twist error is from curr to des in base frame\n\t// std::cout << \"vel_now: \" << jacobian_6d_right*q_vel_right.transpose() << std::endl;\n\tRowVectorXd vel_now = jacobian_6d_right*q_vel_right.transpose();\n\tvel_now_8d << 0, vel_now(0), vel_now(1), vel_now(2), 0, vel_now(3), vel_now(4), vel_now(5); \n\tstd::cout << \"vel_now_8d: \" << vel_now_8d.transpose() << std::endl;\n\tacc_cmd_right = acc_desired_right + K_d*(vel_desired_right - vel_now_8d) - K_p*(error_dq);\n\t// acc_cmd_right = K_d*(vel_desired_right - vel_now_8d) - K_p*(error_dq);\n\tstd::cout << \"acc_cmd_right: \" << acc_cmd_right.transpose() << std::endl;\n\t// ROS_INFO(\"getControlLaw_2, acc_cmd_right.rows(): %d, acc_cmd_right.cols(): %d \", acc_cmd_right.rows(), acc_cmd_right.cols());\n\tRowVectorXd acc_cmd_6d = RowVectorXd::Zero(6);\n\t\n\tacc_cmd_6d << acc_cmd_right(1,0), acc_cmd_right(2,0), acc_cmd_right(3,0), acc_cmd_right(5,0), acc_cmd_right(6,0), acc_cmd_right(7,0);\n\tstd::cout << \"acc_cmd_6d : \" << acc_cmd_6d.transpose() << std::endl;\n\t// ROS_INFO(\"getControlLaw_3\");\n\tMatrixXd jacobian_8d = MatrixXd::Zero(8, jacobian_6d_right.cols());\n\t// ROS_INFO(\"getControlLaw_4\");\n\tjacobian_8d.block(1, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(0, 0, 3, jacobian_8d.cols());\n\tjacobian_8d.block(5, 0, 3, jacobian_8d.cols()) = jacobian_6d_right.block(3, 0, 3, jacobian_8d.cols());\t\n\t// ROS_INFO(\"getControlLaw_5\");\n\tdouble mu = 0.0001;\n\tMatrixXd jac_inv_damped = DQoperations::invDamped_8d(jacobian_8d, mu);\n\t// std::cout << \"acc_cart1: \" << std::endl;\n\t// std::cout << acc_cmd_6d.transpose() << std::endl;\n\t// std::cout << \"acc_cart2: \" << std::endl;\n\t// std::cout << - jacobian_6d_dot_right*q_vel_right.transpose() << std::endl;\t\n\t// ROS_INFO(\"getControlLaw_7\");\n\tRowVectorXd acc_term_8d= RowVectorXd::Zero(8);\n\tacc_term_8d = DQoperations::twistEigen2DQEigen(acc_cmd_6d.transpose() - jacobian_6d_dot_right*q_vel_right.transpose()); \n\tqdd_cmd = jac_inv_damped*acc_term_8d.transpose();\n\tstd::cout << \"qdd_cmd: \" << qdd_cmd << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"kdl_controller\");\n\tros::NodeHandle node_;\n\n\tdynamic_reconfigure::Server<dq_robotics::kdl_controllerConfig> server;\n\tdynamic_reconfigure::Server<dq_robotics::kdl_controllerConfig>::CallbackType f;\n\tf = boost::bind(&dynReconfgr_callback, _1, _2);\n\tserver.setCallback(f);\n\tdynRcnfgr_toggle =false;\n\tbaxter_controller = new BaxterPoseControlServer();\n\tif (!initializeAccController(node_))\n\t{\n\t\tROS_ERROR(\"The acc controller can not be initialized.\");\n\t\treturn 0;\n\t}\n\t// updating manipulator\n\tinitializeTraj();\n\tstart_ = ros::WallTime::now();\n\tros::Duration(1.0).sleep();\n\n\tstart_ = ros::WallTime::now();\n\n\tROS_INFO(\"starting acceleration control\");\n\twhile (!dynRcnfgr_toggle)\n\t{\n\t\tROS_INFO(\"dyn reconf waiting...\");\n\t\tros::spinOnce();\n\t\t// dynRcnfgr_toggle =true;\n\t}\n\tros::spinOnce();\t\n\tdynRcnfgr_toggle =false;\t\t\t\n\tstart_ = ros::WallTime::now();\n\tstd::cout << \"chain.getNrOfJoints(): \" << chain.getNrOfJoints() << std::endl; \n\tstd::cout << \"chain.getNrOfSegments(): \" << chain.getNrOfSegments() << std::endl; \n\tfext.resize(chain.getNrOfSegments());\n\tfor(unsigned int i=0;i < fext.size();i++) fext[i].Zero();\n\tint joint_size = chain.getNrOfJoints(); \n\tq_kdl.resize(joint_size);\n\tdq_kdl.resize(joint_size);\n\tv_kdl.resize(joint_size);\t\n\ttorque_kdl.resize(joint_size);\t\n\n\tstart_ = ros::WallTime::now();\n\tend_ = ros::WallTime::now();\n\n\twhile (time_now < total_time)\n\t{\n\t\tdynRcnfgr_toggle =false;\n\t\tupdateManipulatorState();\n\t\tgetDesiredTraj();\n\t\t\n\t\tRowVector3d ee_position_now, ee_position_desired;\n\t\tMatrix4d htm_desired, htm_current;\n\t\thtm_current = DQoperations::dq2HTM(pe_now_right);\n\t\thtm_desired = DQoperations::dq2HTM(pose_desired_right);\n\t\tee_position_now << htm_current(0,3), htm_current(1,3), htm_current(2,3);\n\t\tee_position_desired << htm_desired(0,3), htm_desired(1,3), htm_desired(2,3);\n\n\t\tRowVectorXd kdl_error_pose = DQoperations::spatial2CartPoseError(pose_desired_right, pe_now_right);\n\t\t\n\t\tRowVectorXd vel_cart_now = jacobian_6d_right*q_vel_right.transpose();\n\t\tvel_cart_now = DQoperations::Matrix8d2RowVector6d(vel_cart_now);\n\t\tvel_cart_now = DQoperations::spatial2CartVel(vel_cart_now, ee_position_now);\t\t\n\t\tRowVectorXd vel_cart_desired = DQoperations::Matrix8d2RowVector6d(vel_desired_right);\n\t\tvel_cart_desired = DQoperations::spatial2CartVel(vel_cart_desired, ee_position_desired);\t\t\n\t\tRowVectorXd kdl_error_vel = vel_cart_desired - vel_cart_now;\n\n\t\tRowVectorXd kdl_acc_desired = DQoperations::Matrix8d2RowVector6d(acc_desired_right);\n\t\tkdl_acc_desired = DQoperations::spatial2CartAcc(acc_desired_right, DQoperations::Matrix8d2RowVector6d(vel_desired_right), ee_position_desired);\t\t\n\t\tRowVectorXd kdl_acc_cmd = kdl_acc_desired + K_d*(vel_cart_desired - vel_cart_now) + K_p*(kdl_error_pose);\n\t\tkdl_acc_cmd << kdl_acc_cmd(3), kdl_acc_cmd(4), kdl_acc_cmd(5), kdl_acc_cmd(0), kdl_acc_cmd(1), kdl_acc_cmd(2);\n\n\n\n\t\t// getControlLaw();\t\n\t\tfor(unsigned int i=0;i < joint_size;i++)\n\t\t{\n\t\t\tq_kdl(i) = q_right(i);\n\t\t\tdq_kdl(i) = q_vel_right(i);\n\t\t\tv_kdl(i) = qdd_cmd(i);\n\t\t}\n\t\tKDL::Jacobian jac, jdot;\n\t\tif(jacKDL->JntToJac (q_kdl, jac) < 0)\n\t\t\tROS_ERROR(\"KDL jacobian solver failed.\");\n\t\tjacDotKDL->setRepresentation(0);\n\t\tif(jacDotKDL->JntToJacDot (KDL::JntArrayVel(q_kdl, dq_kdl), jdot) < 0)\t\t\t\t\n\t\t\t\t\tROS_ERROR(\"KDL jacobian dot solver failed.\");\n\t\t// std::cout << \"q_kdl: \" < q_kdl.data << std::endl;\n\t\tif(idsolver->CartToJnt(q_kdl,dq_kdl,v_kdl,fext,torque_kdl) < 0)\n\t\t\tROS_ERROR(\"KDL inverse dynamics solver failed.\");\t\t\n\t\tstd::cout << \"computed_torque: \" ; \n\t\t// double mu = 0.0001;\n\t\t// MatrixXd jac_inv_damped = DQoperations::invDamped_8d(jac.data, mu);\n\t\t// VectorXd acc_term= RowVectorXd::Zero(6);\n\t\t// acc_term = (kdl_acc_cmd.transpose() - jdot.data*q_vel_right.transpose()); \n\t\t// qdd_cmd = jac_inv_damped*acc_term.transpose();\n\t\t// std::cout << \"computed_torque: \" ; \n\t\t// for(unsigned int i=0;i < joint_size;i++)\n\t\t// {\n\t\t// \tstd::cout << torque_kdl(i) << \", \";\n\t\t// \tcmd.command[i] = torque_kdl(i);\n\t\t// }\t\t\n\t\t// std::cout << std::endl;\n\t // right_cmd_pub.publish(cmd);\t\t\n\t\tfor(unsigned int i=0;i < joint_size;i++)\n\t\t{\n\t\t\tstd::cout << torque_kdl(i) << \", \";\n\t\t\tcmd.command[i] = torque_kdl(i);\n\t\t}\t\t\n\t\tstd::cout << std::endl;\n\t right_cmd_pub.publish(cmd);\n\t ros::spinOnce();\n\t // loop_rate.sleep();\t\t\n\t\tend_ = ros::WallTime::now();\n\t\ttime_now = (end_ - start_).toSec();\n\t\tROS_INFO(\"time_now: %f\", time_now);\n\t}\n\n\n\tROS_INFO(\"starting regulation now.\");\n\tstart_ = ros::WallTime::now();\n\tend_ = ros::WallTime::now();\n\ttime_now = 0;\n\twhile (ros::ok())\n\t{\n\t\tupdateManipulatorState();\n\t\tgetControlLaw_regulation();\n\t\tfor(unsigned int i=0;i < joint_size;i++)\n\t\t{\n\t\t\tq_kdl(i) = q_right(i);\n\t\t\tdq_kdl(i) = q_vel_right(i);\n\t\t\tv_kdl(i) = qdd_cmd(i);\n\t\t}\n\t\t// std::cout << \"q_kdl: \" < q_kdl.data << std::endl;\n\t\tif(idsolver->CartToJnt(q_kdl,dq_kdl,v_kdl,fext,torque_kdl) < 0)\n\t\t\tROS_ERROR(\"KDL inverse dynamics solver failed.\");\t\t\n\t\tstd::cout << \"computed_torque: \" ; \n\t\tfor(unsigned int i=0;i < joint_size;i++)\n\t\t{\n\t\t\tstd::cout << torque_kdl(i) << \", \";\n\t\t\tcmd.command[i] = torque_kdl(i);\n\t\t}\t\t\n\t\tstd::cout << std::endl;\n\t right_cmd_pub.publish(cmd);\n\t ros::spinOnce();\n\t // loop_rate.sleep();\t\t\n\t\tend_ = ros::WallTime::now();\n\t\ttime_now = (end_ - start_).toSec();\n\t\tROS_INFO(\"time_now: %f\", time_now);\t\t\n\t}\n\t// \tros::Duration(1.0).sleep();\n\t// \tros::Duration(1.0).sleep();\n\t// \tend_ = ros::WallTime::now();\n\n\t// // print results\n\t// \tdouble execution_time = (end_ - start_).toNSec() * 1e-6;\n\t// \tROS_INFO_STREAM(\"Exectution time (ms): \" << execution_time);\n\treturn 0;\n}\n\n\t// get current joint position and velocity\n\t// make your control law\n\t// \tget kp, kv and kd from dynamic reconfigure: done\n\t// \tget desired acc, vel and position..generate circular trajectory\n\t// \tget current position and velocity from the update_accControl thing you made\n\t// \tcompute control law like this\n\t// \t\tv.data=ddqr.data+Kp*(qr.data-q.data)+Kd*(dqr.data-dq.data);\n\t// \tget torque from kdl like this\n\t// \t\tif(idsolver->CartToJnt(q,dq,v,fext,torque) < 0)\n\t// \t ROS_ERROR(\"KDL inverse dynamics solver failed.\");\n\t// \tsend torque cmd. \n\t// repeat" }, { "alpha_fraction": 0.5577204823493958, "alphanum_fraction": 0.5957120060920715, "avg_line_length": 40.13793182373047, "blob_id": "2fd75f1e16214e8a4d907a72b95f699e015750f0", "content_id": "1f0076c757068cd0356ad7e3a61a4dd052cfbf6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14319, "license_type": "no_license", "max_line_length": 113, "num_lines": 348, "path": "/dq_robotics/src/test/baxterTaskSpaceClient.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n#include <dq_robotics/Grasp.h>\n#include <dq_robotics/BaxterControl.h>\n\nint main( int argc, char** argv )\n{\n ros::init(argc, argv, \"grasp_client\");\n ros::NodeHandle n;\n ros::ServiceClient client = n.serviceClient<dq_robotics::BaxterControl>(\"baxter/coopTaskSpaceControlCallback\");\n\n dq_robotics::BaxterControl::Request baxterControl_req;\n\n Matrix<double,8,1> desiredAbsPose, desiredRelPose;\n\tMatrix4d htm_abs, htm_rel;\n\n ros::Duration(5).sleep();\n\t// htm_abs << -0.5000, -0.5000, 0.7071, 0.5,\n // 0.7071, -0.7071, 0.0000, -0.0000,\n // 0.5000, 0.5000, 0.7071, 0.2,\n // 0, 0 , 0 , 1.0000;\n // htm_rel << 0, 1, 0, 0,\n // 1, 0, 0, 0,\n // 0, 0, -1, 0.5,\n // 0, 0, 0, 1; \n // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n // desiredRelPose = DQoperations::htm2DQ(htm_rel);\n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desiredRelPose);\n // baxterControl_req.tracking = false;\n // dq_robotics::BaxterControl client_msg;\n // client_msg.request = baxterControl_req;\n // ROS_INFO(\"going to grasp now\"); \n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n\n // ROS_INFO(\"rotating absolute now.\");\n // double total_time = 0, total_rotation = 0, total_translation =0, intial_rot_trans = 0;\n // double final_rotation =1;\n // Matrix<double,8,1> desired_pose;\n // double rotation_rate = 0.00, d = 0;\n // double time_start =ros::Time::now().toSec();\n // std::cout << \"time_start: \" << time_start;\n // ros::Duration(0.5).sleep();\n // time_start =ros::Time::now().toSec();\n // std::cout << \"time_start: \" << time_start;\n\n // while (total_rotation < final_rotation)\n // {\n // double time_now = ros::Time::now().toSec();\n // total_time = time_now - time_start;\n // std::cout << \"total_time: \" << total_time << std::endl;\n // total_rotation = intial_rot_trans + rotation_rate*total_time; \n // RowVector3d l, p, m;\n // l << 0, 0, 1;\n // p << 0, 0, 0;\n // m = p.cross(l);\n // Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n // desired_pose = DQoperations::mulDQ(desiredAbsPose, change_dq);\n // std::cout << \"htm_abs_desired: \" << std::endl; \n // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desired_pose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desiredRelPose);\n // baxterControl_req.tracking = true;\n // client_msg.request = baxterControl_req;\n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n // }\n // htm_abs << -0.5000, -0.5000, 0.7071, 0.7,\n // 0.7071, -0.7071, 0.0000, -0.0000,\n // 0.5000, 0.5000, 0.7071, 0.2,\n // 0, 0 , 0 , 1.0000;\n htm_abs << 1, 0, 0, 0.770645,\n 0, 1, 0, 0,\n 0, 0, 1, 0.373905,\n 0, 0, 0, 1;\n\n // htm_abs << -0.991292, 0.0351464, -0.126905, 0.7393,\n // 0.129208, 0.445522, -0.885898, 0,\n // 0.0254027, -0.894581, -0.446184, 0.199363,\n // 0, 0, 0, 1;\n\n\n\n htm_rel << 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1; \n desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n desiredRelPose = DQoperations::htm2DQ(htm_rel);\n baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desiredRelPose);\n baxterControl_req.starting_abs_pose = DQoperations::DQToDouble(desiredAbsPose);\n baxterControl_req.velocity_control = false;\n baxterControl_req.newTask =true;\n baxterControl_req.virtualSticks =true;\n dq_robotics::BaxterControl client_msg;\n client_msg.request = baxterControl_req;\n ROS_INFO(\"going to grasp now\"); \n if (client.call(client_msg))\n {\n ROS_INFO(\"normError: %f\", client_msg.response.normError);\n }\n else\n {\n ROS_ERROR(\"Failed to call service grasp_service\");\n return 1;\n }\n\n ROS_INFO(\"rotating absolute now.\");\n double total_time = 0, total_rotation = 0, total_translation =0, intial_rot_trans = 0;\n double final_rotation =0.05;\n Matrix<double,8,1> desired_pose;\n double rotation_rate = 0.005, d = 0;\n double time_start =ros::Time::now().toSec();\n std::cout << \"time_start: \" << time_start;\n ros::Duration(0.5).sleep();\n time_start =ros::Time::now().toSec();\n std::cout << \"time_start: \" << time_start;\n baxterControl_req.newTask =false;\n // while (total_rotation < final_rotation)\n // {\n // double time_now = ros::Time::now().toSec();\n // total_time = time_now - time_start;\n // std::cout << \"total_time: \" << total_time << std::endl;\n // total_rotation = intial_rot_trans + rotation_rate*total_time; \n // RowVector3d l, p, m;\n // l << 1, 0, 0 ;\n // p << 0, 0, 0;\n // m = p.cross(l);\n // Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n // desired_pose = desiredRelPose;\n // // desired_pose = DQoperations::mulDQ(desiredRelPose, change_dq);\n // std::cout << \"desiredRelPose: \" << std::endl; \n // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // htm_abs(0,3)= htm_abs(0,3) + 0.5*rotation_rate*total_time;\n // htm_abs(2,3)= htm_abs(2,3) + 0.5*rotation_rate*total_time;\n // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desired_pose);\n // // baxterControl_req.velocity_control = true;\n // client_msg.request = baxterControl_req;\n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n // }\n // ros::Duration(0.5).sleep();\n // time_start =ros::Time::now().toSec();\n // std::cout << \"time_start: \" << time_start;\n // intial_rot_trans = 0;\n // total_rotation = 0;\n // final_rotation =0.05;\n // total_time = 0;\n // total_time = 0, total_rotation = 0, total_translation =0, intial_rot_trans = 0;\n // rotation_rate = 0.005, d = 0;\n // while (total_rotation < final_rotation)\n // {\n // double time_now = ros::Time::now().toSec();\n // total_time = time_now - time_start;\n // std::cout << \"total_time: \" << total_time << std::endl;\n // total_rotation = intial_rot_trans + rotation_rate*total_time; \n // RowVector3d l, p, m;\n // l << 1, 0, 0 ;\n // p << 0, 0, 0;\n // m = p.cross(l);\n // Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n // desired_pose = desiredRelPose;\n // // desired_pose = DQoperations::mulDQ(desiredRelPose, change_dq);\n // std::cout << \"desiredRelPose: \" << std::endl; \n // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // htm_abs(0,3)= htm_abs(0,3) - rotation_rate*total_time;\n // htm_abs(2,3)= htm_abs(2,3) + rotation_rate*total_time;\n // // htm_abs(2,3)= htm_abs(2,3) + rotation_rate*total_time;\n // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desired_pose);\n // // baxterControl_req.velocity_control = true;\n // client_msg.request = baxterControl_req;\n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n // } \n\n ros::Duration(0.5).sleep();\n time_start =ros::Time::now().toSec();\n std::cout << \"time_start: \" << time_start;\n intial_rot_trans = 0;\n total_rotation = 0;\n final_rotation = 1;\n total_time = 0;\n total_time = 0, total_rotation = 0, total_translation =0, intial_rot_trans = 0;\n rotation_rate = 0.01, d = 0;\n ros::WallTime start = ros::WallTime::now();\n\n while (total_rotation < final_rotation)\n {\n start = ros::WallTime::now();\n double time_now = ros::Time::now().toSec();\n total_time = time_now - time_start;\n std::cout << \"total_time: \" << total_time << std::endl;\n total_rotation = intial_rot_trans + 2*rotation_rate*total_time; \n RowVector3d l, p, m;\n l << -1, 0, 0;\n p << 0, 0, 0;\n m = p.cross(l);\n Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n desired_pose = desiredRelPose;\n desiredAbsPose = DQoperations::mulDQ(desiredAbsPose, change_dq);\n // desired_pose = DQoperations::mulDQ(desiredAbsPose, change_dq);\n // Matrix4d change_htm = DQoperations::dq2HTM(desired_pose);\n // change_htm(1,3) = change_htm(1,3) - 0.001*rotation_rate*total_time;\n // desired_pose = DQoperations::htm2DQ(change_htm); \n // std::cout << \"desiredRelPose: \" << std::endl; \n // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // htm_abs(0,3)= htm_abs(0,3) - rotation_rate*total_time;\n // htm_abs(2,3)= htm_abs(2,3) + 0.01*rotation_rate*total_time;\n // htm_abs(0,3)= htm_abs(0,3) + 0.01*rotation_rate*total_time;\n // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desiredRelPose);\n // baxterControl_req.velocity_control = true;\n client_msg.request = baxterControl_req;\n if (client.call(client_msg))\n {\n ROS_INFO(\"normError: %f\", client_msg.response.normError);\n }\n else\n {\n ROS_ERROR(\"Failed to call service grasp_service\");\n return 1;\n }\n // ros::WallTime end = ros::WallTime::now();\n // ros::WallDuration dur = end - start;\n // std::cout << \"master loop duration: \" << dur.toSec() << std::endl;\n } \n\n\n // time_start =ros::Time::now().toSec();\n // std::cout << \"time_start: \" << time_start;\n // intial_rot_trans = 0;\n // total_rotation = 0;\n // final_rotation = 0.10;\n // total_time = 0;\n // total_time = 0, total_rotation = 0, total_translation =0, intial_rot_trans = 0;\n // rotation_rate = 0.01, d = 0;\n // while (total_rotation < final_rotation)\n // {\n // double time_now = ros::Time::now().toSec();\n // total_time = time_now - time_start;\n // std::cout << \"total_time: \" << total_time << std::endl;\n // total_rotation = intial_rot_trans + 0.01*rotation_rate*total_time; \n // RowVector3d l, p, m;\n // l << 0, 1, 0;\n // p << 0, 0, 0;\n // m = p.cross(l);\n // Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n // desired_pose = desiredRelPose;\n // // desiredAbsPose = DQoperations::mulDQ(desiredAbsPose, change_dq);\n // // desired_pose = DQoperations::mulDQ(desiredRelPose, change_dq);\n // // Matrix4d change_htm = DQoperations::dq2HTM(desired_pose);\n // // change_htm(1,3) = change_htm(1,3) - 0.001*rotation_rate*total_time;\n // // desired_pose = DQoperations::htm2DQ(change_htm); \n // // std::cout << \"desiredRelPose: \" << std::endl; \n // // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // // htm_abs(0,3)= htm_abs(0,3) - rotation_rate*total_time;\n // htm_abs(2,3)= htm_abs(2,3) - 0.01*rotation_rate*total_time;\n // htm_abs(0,3)= htm_abs(0,3) - 0.01*rotation_rate*total_time;\n // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desired_pose);\n // // baxterControl_req.velocity_control = true;\n // client_msg.request = baxterControl_req;\n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n // } \n return 0;\n} \n\n//////////////////////relative rotation along -x frame and -ve traslation relative along y axis \n // while (total_rotation < final_rotation)\n // {\n // double time_now = ros::Time::now().toSec();\n // total_time = time_now - time_start;\n // std::cout << \"total_time: \" << total_time << std::endl;\n // total_rotation = intial_rot_trans + 2*rotation_rate*total_time; \n // RowVector3d l, p, m;\n // l << -1, 0, 0;\n // p << 0, 0, 0;\n // m = p.cross(l);\n // Matrix<double,8,1> change_dq = DQoperations::screw2DQ(total_rotation, l, d, m);\n // // desired_pose = desiredRelPose;\n // desired_pose = DQoperations::mulDQ(desiredRelPose, change_dq);\n // Matrix4d change_htm = DQoperations::dq2HTM(desired_pose);\n // change_htm(1,3) = change_htm(1,3) - 0.001*rotation_rate*total_time;\n // desired_pose = DQoperations::htm2DQ(change_htm); \n // std::cout << \"desiredRelPose: \" << std::endl; \n // std::cout << DQoperations::dq2HTM(desired_pose) << std::endl; \n // // htm_abs(0,3)= htm_abs(0,3) - rotation_rate*total_time;\n // // htm_abs(2,3)= htm_abs(2,3) + rotation_rate*total_time;\n // // htm_abs(0,3)= htm_abs(0,3) + 0.01*rotation_rate*total_time;\n // // desiredAbsPose = DQoperations::htm2DQ(htm_abs);\n // baxterControl_req.desiredAbsPose = DQoperations::DQToDouble(desiredAbsPose);\n // baxterControl_req.desiredRelPose = DQoperations::DQToDouble(desired_pose);\n // // baxterControl_req.velocity_control = true;\n // client_msg.request = baxterControl_req;\n // if (client.call(client_msg))\n // {\n // ROS_INFO(\"normError: %f\", client_msg.response.normError);\n // }\n // else\n // {\n // ROS_ERROR(\"Failed to call service grasp_service\");\n // return 1;\n // }\n // } " }, { "alpha_fraction": 0.7471482753753662, "alphanum_fraction": 0.7509505748748779, "avg_line_length": 51.61428451538086, "blob_id": "5395afe9f2d0c689ba32e6a8350bba5dd3eaeeb8", "content_id": "23fdfd70d4ebafdd56c5d81bede74d56658e5d29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3682, "license_type": "no_license", "max_line_length": 648, "num_lines": 70, "path": "/dq_robotics/include/dq_robotics/baxter_dq.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#ifndef MANIPULATOR_DQ_MOD_H\n#define MANIPULATOR_DQ_MOD_H\n \n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/DQoperations.h>\n// #include <baxter_trajectory_interface/GetIKSolution.h>\n// #include <baxter_trajectory_interface/GetJointTrajectory.h>\n// #include <baxter_trajectory_interface/ControlSystemStates.h>\n#include <joint_limits_interface/joint_limits.h>\n#include <joint_limits_interface/joint_limits_urdf.h>\n#include <joint_limits_interface/joint_limits_rosparam.h>\n#include <urdf/model.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <math.h>\n#include \"baxter_core_msgs/JointCommand.h\"\n#include <sensor_msgs/JointState.h>\n\nusing namespace Eigen;\n\nclass ManipulatorModDQ\n{\nprivate:\n\tros::NodeHandle rh;\n\t// baxter_trajectory_interface::ControlSystemStates state;\n\tstd::vector<RowVector3d> u, p, u_right, p_right, u_left, p_left, u_baxter, p_baxter;\n\tMatrix<double,8,1> pe_init_left, pe_init_right, pe_now, pe_init, pe_now_dot_dq;\n\tMatrixXd jacobian, jacobian_8d, joint_limit_jacobian, jointLimit_repulsive_function, pe_now_htm, pe_init_htm;\n\tRowVectorXd q_init, q, q_vel, q_dual, q_baxter, q_vel_baxter;\n\tstd::vector<int> joint_type, joint_type_left, joint_type_right, joint_type_baxter;\n\tint joint_size, joint_size_right, joint_size_left, joint_size_baxter; \n\tstd::string root_name, tip_name_left, tip_name_right, tip_name;\n\tstd::vector<std::string> joint_names, joint_names_left, joint_names_right, joint_names_baxter;\n\tstd::vector<double> velocity_limit, velocity_limit_ordered, velocity_limit_ordered_left, velocity_limit_ordered_right, velocity_limit_ordered_baxter, joint_low_limit, joint_high_limit, joint_low_limit_ordered, joint_low_limit_ordered_left, joint_low_limit_ordered_right, joint_low_limit_ordered_baxter, joint_high_limit_ordered, joint_high_limit_ordered_left, joint_high_limit_ordered_right, joint_high_limit_ordered_baxter, min_safe, min_safe_left, min_safe_right, min_safe_baxter, max_safe, max_safe_left, max_safe_right, max_safe_baxter, joint_mid_point, joint_mid_point_left, joint_mid_point_right, joint_mid_point_baxter, vel_desired_control;\n\t\n\tstd::vector<Matrix<double,8,1> > fkm_current;\n\t// urdf::Model robot_model;\n\tstd::string xml;\n\tros::Time last_time, current_time;\n\tdouble fraction_jointLimit, dt, totalTime, sleepTimeout;\n\n\tros::Publisher left_cmd_pub, right_cmd_pub;\n\tbaxter_core_msgs::JointCommand cmd_left, cmd_right;\n\tros::Subscriber joint_state_sub;\npublic:\n\tvoid joint_state_callback(const sensor_msgs::JointState& jointStateConsPtr);\n\tbool initialize_baxter();\n\tbool getRobotParams_baxter();\n\tbool loadModel_baxter();\n\tbool readJoints_baxter(std::string tip_name, std::vector<std::string> &joint_names_new, urdf::Model &robot_model);\n\tvoid getCurrentJointState_baxter();\n\t// void fkmDual();\n\t// void jacobianDual();\n\t// void jacobianDual_8d();\n\t// void getDQderivative();\n\t\n\tvoid mapJointName2JointCmds();\n\tvoid robotParams(std::vector<RowVector3d> &u_, std::vector<RowVector3d> &p_, Matrix<double,8,1> &pe_init_left_, Matrix<double,8,1> &pe_init_right_, std::vector<double> &joint_high_limit_, std::vector<double> &joint_low_limit_, std::vector<double> &velocity_limit_, std::vector<double> &max_safe_, std::vector<double> &min_safe_, std::vector<std::string> &joint_names_, std::vector<int> &joint_type_);\n\tvoid currentRobotState(ros::Time &current_time_, RowVectorXd &q_, RowVectorXd &q_vel_);\n\tvoid sendJointCommandBaxter(std::vector<double> jointCmds_, int mode, double sleepTimeout_, bool velocity_control=true);\n\t// void initialize_leftArm();\n\t// void initialize_rightArm();\n\t// void robot_state_right();\n\t// void robot_state_left();\n\tManipulatorModDQ();\n\t~ManipulatorModDQ();\n};\n#endif" }, { "alpha_fraction": 0.6590248346328735, "alphanum_fraction": 0.6798514723777771, "avg_line_length": 42.51990509033203, "blob_id": "6ee06aa257382c53a773bd5c0877038d1726642a", "content_id": "d9b61aa56cdf78efb2d96359d45905cc38b67ae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18582, "license_type": "no_license", "max_line_length": 280, "num_lines": 427, "path": "/dq_robotics/src/baxter_ar10_kinematics.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n#include <dq_robotics/Grasp.h>\n// #include <baxter_trajectory_interface/baxter_poseControl_server.h>\n#define PI 3.14159265\n\ndouble ar10_timeStep, mu, Kp, K_jl, Kp_position, K_jl_position, sleepTimeout, dt, timeStep, norm_error_const, ar10_Kp, ar10_dt;\nMatrix<double,8,1> pe_init_baxterRight, pe_now_baxterRight, pe_init_thumbRight, pe_init_indexRight, pe_now_thumbRight, pe_now_indexRight, pe_desired_thumb, pe_desired_index, tf_rightHand2handBase;\nMatrixXd jacobian_baxterRight, jacobian_thumbRight, jacobian_indexRight;\nRowVectorXd q_baxterRight, q_thumbRight, q_indexRight, q_init_thumbRight, q_init_indexRight;\nstd::vector<double> joint_velocity_limit_baxterRight;\nBaxterPoseControlServer* baxter_controller;\nAR10Kinematics* ar10;\nMatrix<double,8,1> tfRight_baxterBase2handBase;\n\nbool getControllerParams()\n{\n\tstd::string paramName=\"Kp\";\n\tif(!ros::param::get(paramName, Kp))\n\t{\n\t\tstd::cout << \"controller param Kp not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"ar10_Kp\";\n\tif(!ros::param::get(paramName, ar10_Kp))\n\t{\n\t\tstd::cout << \"controller param ar10_Kp not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\tparamName=\"Kp_position\";\n\tif(!ros::param::get(paramName, Kp_position))\n\t{\n\t\tstd::cout << \"controller param Kp_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"ar10_timeStep\";\n\tif(!ros::param::get(paramName, timeStep))\n\t{\n\t\tstd::cout << \"controller param timeStep not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl\";\n\tif(!ros::param::get(paramName, K_jl))\n\t{\n\t\tstd::cout << \"controller param K_jl not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl_position\";\n\tif(!ros::param::get(paramName, K_jl_position))\n\t{\n\t\tstd::cout << \"controller param K_jl_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"mu\";\n\tif(!ros::param::get(paramName, mu))\n\t{\n\t\tstd::cout << \"controller param mu not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\t// paramName=\"use_VM\";\n\t// int value;\n\t// if(ros::param::get(paramName, value))\n\t// {\n\t// \tif(value)\n\t// \t\tuse_VM=true;\n\t// }\n\t// else\n\t// {\n\t// \tstd::cout << \"controller param use_VM not found\" << std::endl;\n\t// \treturn 0;\n\t// }\n\n\t// paramName=\"dualArm\";\n\t// if(ros::param::get(paramName, value))\n\t// {\n\t// \tif(value)\n\t// \t\tdualArm=true;\n\t// }\n\t// else\n\t// {\n\t// \tstd::cout << \"controller param dualArm not found\" << std::endl;\n\t// \treturn 0;\n\t// }\n\n\n\tparamName=\"sleepTimeout\";\n\tif(!ros::param::get(paramName, sleepTimeout))\n\t{\n\t\tstd::cout << \"controller param sleepTimeout not found\" << std::endl;\n\t\treturn 0;\n\t}\n\tparamName=\"ar10_dt\";\n\tif(!ros::param::get(paramName, ar10_dt))\n\t{\n\t\tstd::cout << \"controller param sleepTimeout not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"norm_error_const\";\n\tif(!ros::param::get(paramName, norm_error_const))\n\t{\n\t\tstd::cout << \"controller param norm_error_const not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tROS_INFO(\"Controller parameters loaded\");\n\treturn 1;\n}\n\nbool update_baxterAR10()\n{\n\n\tif(baxter_controller->BaxterPoseControlServer::updateManipulatorVariables(\"right\"))\n\t{\n\t\t// std::cout << \"Here 4\" << std::endl;\n\t\tif(baxter_controller->BaxterPoseControlServer::importManipulatorState(\"right\", pe_init_baxterRight, pe_now_baxterRight, jacobian_baxterRight, q_baxterRight, joint_velocity_limit_baxterRight))\n\t\t{\t\t\n\t\t\t\t\t// std::cout << \"Here 5\" << std::endl;\n\t\t\tif(ar10->AR10Kinematics::updateFingerVariables(\"thumb_right\"))\n\t\t\t{\n\t\t\t\t\t\t// std::cout << \"Here 6\" << std::endl;\n\t\t\t\tif(ar10->AR10Kinematics::importHandState(\"thumb_right\", pe_init_thumbRight, pe_now_thumbRight, jacobian_thumbRight, q_thumbRight, q_init_thumbRight))\n\t\t\t\t{\n\t\t\t\t\t\t\t// std::cout << \"Here 7\" << std::endl;\n\t\t\t\t\tif(ar10->AR10Kinematics::updateFingerVariables(\"index_right\"))\n\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// std::cout << \"Here 8\" << std::endl;\n\t\t\t\t\t\tif(!ar10->AR10Kinematics::importHandState(\"index_right\", pe_init_indexRight, pe_now_indexRight, jacobian_indexRight, q_indexRight, q_init_indexRight))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// std::cout << \"Here 9\" << std::endl;\n\t\t\t\t\t\t\tstd::cout<< \"could not get state for indexRight\" << std::endl;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// else return true;\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout<< \"could not update variables for indexRight\" << std::endl;\t\t\t\n\t\t\t\t\t\treturn false;\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"could not update variables for thumb_right\" << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t std::cout<< \"could not get state for thumb_right\" << std::endl;\n\t\t\t}\n\t\t\t// std::cout << \"jacobian_baxterRight: \" << std::endl;\n\t\t\t// std::cout << jacobian_baxterRight << std::endl;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tstd::cout<< \"could not get state for baxter\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout<< \"could not update state for baxter\" << std::endl;\n\t\treturn 0;\n\t}\n\t// std::cout << \"Here 3\" << std::endl;\n\t// std::cout << \"Here 3\" << std::endl;\n\t// std::cout << \"Here 3\" << std::endl;\n\tstd::cout << \"htm_pe_now_baxterRight: \" << std::endl;\n\tstd::cout << DQoperations::dq2HTM(pe_now_baxterRight) << std::endl;\n\tstd::cout << \"q_baxterRight: \" << std::endl;\n\tstd::cout << q_baxterRight << std::endl;\n\t// std::cout << \"Here 3\" << std::endl;\n\t// std::cout << \"Here 3\" << std::endl;\n\t// std::cout << \"Here 3\" << std::endl;\n\n\t// pe_now_thumbRight = DQoperations::mulDQ(DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase), pe_now_thumbRight);\n\t// pe_now_indexRight = DQoperations::mulDQ(DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase), pe_now_indexRight);\n\n\t// std::cout << \"jacobian_thumbRight: \" << std::endl;\n\t// std::cout << jacobian_thumbRight << std::endl;\t\n\t\n\t// MatrixXd jacobian = jacobian_thumbRight;\n\t// jacobian.block(0, 0, 4, jacobian_thumbRight.cols()) = \tjacobian_thumbRight.block(4, 0, 4, jacobian_thumbRight.cols()) ;\n\t// jacobian.block(4, 0, 4, jacobian_thumbRight.cols()) = \tjacobian_thumbRight.block(0, 0, 4, jacobian_thumbRight.cols()) ;\n\t// jacobian.col(0) = DQoperations::transformLine(jacobian.col(0), DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase));\n\t// jacobian.col(1) = DQoperations::transformLine(jacobian.col(1), DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase));\n\t// jacobian_thumbRight.block(0, 0, 4, jacobian_thumbRight.cols()) = \tjacobian.block(4, 0, 4, jacobian_thumbRight.cols()) ;\n\t// jacobian_thumbRight.block(4, 0, 4, jacobian_thumbRight.cols()) = \tjacobian.block(0, 0, 4, jacobian_thumbRight.cols()) ;\n\n\t// std::cout << \"jacobian_thumbRight_aftertf: \" << std::endl;\n\t// std::cout << jacobian_thumbRight << std::endl;\t\n\n\t// jacobian = jacobian_indexRight;\n\t// jacobian.block(0, 0, 4, jacobian_indexRight.cols()) = \tjacobian_indexRight.block(4, 0, 4, jacobian_indexRight.cols()) ;\n\t// jacobian.block(4, 0, 4, jacobian_indexRight.cols()) = \tjacobian_indexRight.block(0, 0, 4, jacobian_indexRight.cols()) ;\n\t// jacobian.col(0) = DQoperations::transformLine(jacobian.col(0), DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase));\n\t// jacobian.col(1) = DQoperations::transformLine(jacobian.col(1), DQoperations::mulDQ(pe_now_baxterRight, tf_rightHand2handBase));\n\t// jacobian_indexRight.block(0, 0, 4, jacobian_indexRight.cols()) = \tjacobian.block(4, 0, 4, jacobian_indexRight.cols()) ;\n\t// jacobian_indexRight.block(4, 0, 4, jacobian_indexRight.cols()) = \tjacobian.block(0, 0, 4, jacobian_indexRight.cols()) ;\n}\n\n\n\nbool grasp_callback(dq_robotics::Grasp::Request& grasp_req, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dq_robotics::Grasp::Response& grasp_res)\n{\n\t// std::cout << \"Here 1\" << std::endl;\n\tRowVectorXd screw_error_thumb, screw_error_right, screw_error_index, combined_screw_error, q_dot, q, jointCmds_baxterRight, jointCmds_thumbRight, jointCmds_indexRight;\t\n\tMatrixXd combined_jacobian_8d;\n\tdouble normError =1;\n while (normError > norm_error_const)\n {\n \t\t// std::cout << \"is it this function!\" << std::endl;\n\t\tif(!update_baxterAR10())\n\t\t{\n\t\t\tstd::cout << \"The arm and hand could not be updated\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\t// std::cout << \"or not!\" << std::endl;\n\t\tDQoperations::doubleToDQ(pe_desired_thumb, grasp_req.grasp_pose_thumb);\n\t\tDQoperations::doubleToDQ(pe_desired_index, grasp_req.grasp_pose_index);\n\n\t\t// std::cout << \"pe_desired_thumb: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(pe_desired_thumb) << std::endl;\n\t\t// std::cout << \"pe_desired_index: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(pe_desired_index) << std::endl;\t\n\n\t\tstd::cout << \"htm_pe_current_index: \" << std::endl;\n\t\tstd::cout << DQoperations::dq2HTM(pe_now_indexRight) << std::endl;\n\t\tstd::cout << \"htm_pe_desired_index: \" << std::endl;\n\t\tstd::cout << DQoperations::dq2HTM(pe_desired_index) << std::endl;\t\t\n\n\t\tstd::cout << \"htm_pe_current_thumb: \" << std::endl;\n\t\tstd::cout << DQoperations::dq2HTM(pe_now_thumbRight) << std::endl;\n\t\tstd::cout << \"htm_pe_desired_thumb: \" << std::endl;\t\t\n\t\tstd::cout << DQoperations::dq2HTM(pe_desired_thumb) << std::endl;\t\t\n\t\t\n\t\tscrew_error_thumb= DQController::getScrewError_8d(pe_now_thumbRight, pe_desired_thumb);\n\t\tscrew_error_index= DQController::getScrewError_8d(pe_now_indexRight, pe_desired_index);\n\t\t// screw_error_right= DQController::getScrewError_8d(pe_now_baxterRight, pe_desired_index);\n\n\t\t// std::cout << \"pe_now_baxterRight: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(pe_now_thumbRight) << std::endl;\n\n\t\t// std::cout << \"pe_desired_index: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(pe_desired_index) << std::endl;\n\t\t\n\t\t// combined_jacobian_8d= MatrixXd::Zero(16, (jacobian_baxterRight.cols() + jacobian_thumbRight.cols() + jacobian_indexRight.cols()));\n\t\t// combined_jacobian_8d.block(0, 0, jacobian_baxterRight.rows(), jacobian_baxterRight.cols()) = jacobian_baxterRight;\n\t\t// combined_jacobian_8d.block(jacobian_baxterRight.rows(), 0, jacobian_baxterRight.rows(), jacobian_baxterRight.cols()) = jacobian_baxterRight;\n\t\t// combined_jacobian_8d.block(0, jacobian_baxterRight.cols(), jacobian_indexRight.rows(), jacobian_indexRight.cols()) = jacobian_indexRight;\n\t\t// combined_jacobian_8d.block(jacobian_baxterRight.rows(), (jacobian_baxterRight.cols() + jacobian_indexRight.cols()), jacobian_thumbRight.rows(), jacobian_thumbRight.cols()) = jacobian_thumbRight;\n\t\t// combined_screw_error =RowVectorXd::Zero(screw_error_thumb.cols()+screw_error_index.cols());\n\t\t// combined_screw_error << screw_error_index, screw_error_thumb;\n\n\t\t// RowVectorXd errorScrew_positionOnly = RowVectorXd::Zero((screw_error_thumb.cols()+screw_error_index.cols())/2);\n\t\t// errorScrew_positionOnly << screw_error_index.head(4), screw_error_thumb.head(4);\n\n\t\tMatrixXd combined_jacobian_positionOnly ;\n\tcombined_jacobian_positionOnly = MatrixXd::Zero(16, (jacobian_thumbRight.cols() + jacobian_indexRight.cols()));\n\t\t// combined_jacobian_positionOnly = MatrixXd::Zero(8, (jacobian_baxterRight.cols() + jacobian_thumbRight.cols() + jacobian_indexRight.cols()));\n\n\t\tcombined_jacobian_positionOnly.block(0, 0, jacobian_indexRight.rows(), jacobian_indexRight.cols()) = jacobian_indexRight.block(0, 0, jacobian_indexRight.rows(), jacobian_indexRight.cols()); \n\t\tcombined_jacobian_positionOnly.block(jacobian_indexRight.rows(), jacobian_indexRight.cols(), jacobian_thumbRight.rows(), jacobian_thumbRight.cols()) = jacobian_thumbRight.block(0, 0, jacobian_thumbRight.rows(), jacobian_thumbRight.cols()); \n\n\t\t// combined_jacobian_positionOnly.block(jacobian_baxterRight.rows()/2, 0, jacobian_baxterRight.rows()/2, jacobian_baxterRight.cols()) = jacobian_baxterRight.block(0, 0, jacobian_baxterRight.rows()/2, jacobian_baxterRight.cols()); \n\n\t\t// combined_jacobian_positionOnly.block(0, jacobian_baxterRight.cols(), jacobian_indexRight.rows()/2, jacobian_indexRight.cols())=jacobian_indexRight.block(0, 0, jacobian_indexRight.rows()/2, jacobian_indexRight.cols());\n\n\t\t// combined_jacobian_positionOnly.block(jacobian_baxterRight.rows()/2, (jacobian_baxterRight.cols()+jacobian_indexRight.cols()), jacobian_thumbRight.rows()/2, jacobian_thumbRight.cols())=jacobian_thumbRight.block(0, 0, jacobian_thumbRight.rows()/2, jacobian_thumbRight.cols());\n\n\t\t// std::cout << \"Jacobian_positionOnly: \" << std::endl;\n\t\t// std::cout << combined_jacobian_positionOnly << std::endl;\n\n\t\t// RowVectorXd errorScrew_indexOnly = RowVectorXd::Zero((screw_error_index.cols()));\n\t\t// RowVectorXd errorScrew_thumbOnly = RowVectorXd::Zero((screw_error_thumb.cols()));\n\t\t// errorScrew_indexOnly << screw_error_index;\n\t\t// errorScrew_thumbOnly << screw_error_thumb.head(4);\n\t\t// errorScrew_indexOnly << screw_error_index.head(4);\n\t\t// std::cout << \"errorScrew_indexOnly: \" << std::endl;\n\t\t// std::cout << errorScrew_indexOnly << std::endl;\n\t\t// std::cout << \"jacobian_thumbRight: \" << std::endl;\n\t\t// std::cout << jacobian_thumbRight << std::endl;\t\t\n\t\t// std::cout << \"jacobian_indexRight: \" << std::endl;\n\t\t// std::cout << jacobian_indexRight << std::endl;\t\t\t\t\n\t\t\n\t\t// std::cout << \"combined_jacobian_positionOnly: \" << std::endl;\n\t\t// std::cout << combined_jacobian_positionOnly << std::endl;\t\t\t\t\t\t\n\t\t// MatrixXd combined_jacobian_indexOnly ;\n\t\t\n\t\t// combined_jacobian_indexOnly = MatrixXd::Zero(4, (jacobian_baxterRight.cols() + jacobian_indexRight.cols()));\n\n\t\t// combined_jacobian_indexOnly.block(0, 0, jacobian_baxterRight.rows()/2, jacobian_baxterRight.cols()) = jacobian_baxterRight.block(0, 0, jacobian_baxterRight.rows()/2, jacobian_baxterRight.cols()); \n\n\t\t// combined_jacobian_indexOnly.block(0, jacobian_baxterRight.cols(), jacobian_indexRight.rows()/2, jacobian_indexRight.cols())=jacobian_indexRight.block(0, 0, jacobian_indexRight.rows()/2, jacobian_indexRight.cols());\n\n\n\t\t// std::cout << \"Jacobian_indexOnly: \" << std::endl;\n\t\t// std::cout << combined_jacobian_indexOnly << std::endl;\n\n\t\tRowVectorXd errorScrew_positionOnly = RowVectorXd::Zero((screw_error_thumb.cols()+screw_error_index.cols()));\n\t\terrorScrew_positionOnly << screw_error_index, screw_error_thumb;\n\t\tstd::cout << \"screw_error_thumb:\" << screw_error_thumb << std::endl;\n\t\t// std::cout << \"screw_error_index:\" << screw_error_index << std::endl;\n\t\t// std::cout << \"errorScrew_positionOnly:\" << errorScrew_positionOnly << std::endl;\n\t\t// RowVectorXd errorScrew_rightOnly = RowVectorXd::Zero((screw_error_right.cols())/2);\n\t\t// errorScrew_rightOnly << screw_error_right.head(4);\n\n\t\t// MatrixXd combined_jacobian_rightOnly ;\n\t\t\n\t\t// combined_jacobian_rightOnly = MatrixXd::Zero(4, (jacobian_baxterRight.cols()));\n\n\t\t// combined_jacobian_rightOnly= jacobian_baxterRight.block(0, 0, jacobian_baxterRight.rows()/2, jacobian_baxterRight.cols()); \n\n\n\t\t// std::cout << \"combined_jacobian_rightOnly: \" << std::endl;\n\t\t// std::cout << combined_jacobian_rightOnly << std::endl;\n\n\n\t\t// q_dot= DQController::calculateControlVel(Kp, mu, errorScrew_positionOnly, combined_jacobian_positionOnly, (combined_jacobian_positionOnly.cols()));\n\t\t// q_dot= DQController::calculateControlVel(Kp, mu, screw_error_index, jacobian_indexRight, (jacobian_indexRight.cols()));\n\t\tq_dot= DQController::calculateControlVel(Kp, mu, screw_error_thumb, jacobian_thumbRight, (jacobian_thumbRight.cols()));\n\t\t// q_dot= DQController::calculateControlVel(Kp, mu, errorScrew_indexOnly, combined_jacobian_indexOnly, (combined_jacobian_indexOnly.cols()));\n\t\t// q_dot= DQController::calculateControlVel(ar10_Kp, mu, errorScrew_indexOnly, jacobian_indexRight.block(0,0,jacobian_indexRight.rows()/2, jacobian_indexRight.cols()), (jacobian_indexRight.cols()));\n\t\t// q_dot= DQController::calculateControlVel(ar10_Kp, mu, errorScrew_thumbOnly, jacobian_thumbRight.block(0,0,jacobian_thumbRight.rows()/2, jacobian_thumbRight.cols()), (jacobian_thumbRight.cols()));\n\t\tstd::cout << \"q_dot: \" << q_dot << std::endl;\n\t\tq.resize(q_dot.size());\n\t\t// q << q_baxterRight, q_indexRight, q_thumbRight;\n\t\t// q << q_indexRight, q_thumbRight;\n\t\t// q << q_baxterRight, q_indexRight;\n\t\t// q << q_indexRight;\n\t\tq << q_thumbRight;\n\t\tq = q + q_dot*ar10_timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\n\t\tstd::cout << \"q: \" << q << std::endl;\n\t\t// jointCmds_indexRight = q ;\n\t\t// jointCmds_thumbRight = q ;\n\t\t// jointCmds_baxterRight = q.head(7); \n\t\t// jointCmds_indexRight = q.segment(7, 2) ;\n\t\t// jointCmds_thumbRight = q.segment(9, 2) ;\n\t\t// jointCmds_thumbRight = q.tail(2) ;\n\t\t// jointCmds_indexRight = q.head(2) ;\n\t\tjointCmds_thumbRight = q;\n\t\t// baxter_controller->sendBaxterJointCmds(\"right\", DQoperations::dqEigenToDQdouble(jointCmds_baxterRight));\n\t\tif(ar10->AR10Kinematics::sendJointCmds_AR10(DQoperations::dqEigenToDQdouble(jointCmds_thumbRight), \"thumb\"))\n\t\t{\n\t\t\tstd::cout << \"Grasp cmds for ar10 thumb sent\" << std::endl;\n\t\t\t\n\t\t}\n\t\telse \n\t\t{\n\t\t\tROS_ERROR(\"AR10 joint servive not working for thumb.\");\n\t\t\treturn 0;\n\t\t}\n\t\t// if(ar10->AR10Kinematics::sendJointCmds_AR10(DQoperations::dqEigenToDQdouble(jointCmds_indexRight), \"index\"))\n\t\t// {\n\t\t// \tstd::cout << \"Grasp cmds for ar10 index sent\" << std::endl;\n\t\t// }\n\t\t// else \n\t\t// {\n\t\t// \tROS_ERROR(\"AR10 joint servive not working for index.\");\n\t\t// \treturn 0;\n\t\t// }\t\n\t\t\t// if(ar10->AR10Kinematics::sendJointCmds_AR10(DQoperations::dqEigenToDQdouble(jointCmds_thumbRight), \"thumb\"))\n\t\t\t// {\n\t\t\t// \tstd::cout << \"Grasp cmds for ar10 sent\" << std::endl;\n\t\t\t// }\n\t\t\t// else \n\t\t\t// {\n\t\t\t// \tROS_ERROR(\"AR10 joint servive not working.\");\n\t\t\t// \treturn 0;\n\t\t\t// }\t\t\t\n\t\t// normError = errorScrew_indexOnly.norm();\n\t\t// normError = errorScrew_thumbOnly.norm();\n\t\t// normError = errorScrew_positionOnly.norm();\n\t\tnormError = screw_error_thumb.norm();\n\t\tstd::cout << \"normError: \" << normError << std::endl;\n\t\tros::Duration(ar10_dt).sleep();\n\t}\n\tgrasp_res.normError = normError;\n\n\treturn true;\n\t// DQoperations::dqEigenToDQdouble(q, jointCmds);\n\n}\n\n\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"baxter_ar10_kinematics\");\n\tros::NodeHandle n;\n\n\tMatrix4d htm_rightHand2handBase = Matrix4d::Identity();\n\thtm_rightHand2handBase << -0.0002037, 1.0000000, 0.0000000, 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t -1.0000000, -0.0002037, 0.0000000, 0, \n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.0000000, 0.0000000, 1.0000000, -0.0021,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0,\t\t\t\t\t 0,\t\t\t\t\t 0, \t\t\t\t 1;\n\ttf_rightHand2handBase = DQoperations::htm2DQ(htm_rightHand2handBase);\n\n\tros::ServiceServer service = n.advertiseService(\"baxterAR10/grasp_service\", grasp_callback);\n\n\tif (!getControllerParams())\n\t\tstd::cout << \"Controller params not found for COMBO controller.\" << std::endl;\n\n\n\tbaxter_controller = new BaxterPoseControlServer();\n\tif (!baxter_controller->BaxterPoseControlServer::initializeController())\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\n\n\tar10 = new AR10Kinematics();\n\tar10->AR10Kinematics::init_AR10Kinematics();\n\tar10->AR10Kinematics::init_fingers();\n\tros::spin();\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.5192734599113464, "alphanum_fraction": 0.6532795429229736, "avg_line_length": 35.96268844604492, "blob_id": "a196332bd79286a0c1aa197e9833b35ce4df8328", "content_id": "9293d1238340df27a6c932bf8087ac49e6be1754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4955, "license_type": "no_license", "max_line_length": 137, "num_lines": 134, "path": "/dq_robotics/src/ar10_client.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": " \n#include <iostream>\n#include <math.h>\n#include <stdexcept> //for range_error\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n#include <complex>\n#include <cmath>\n#include <vector>\n#include <cstddef>\n#include <Eigen/SVD>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/dq_controller.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <cstdio>\n#include <tf2/LinearMath/Quaternion.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_msgs/MultiArrayDimension.h>\n#include <ar10_kinematics/IkHand.h>\n\nusing namespace Eigen;\n\n\n// float64[] desiredPose \n// int32 finger # finger=0 for thumb, finger4=index, and so on\n// bool getJacobian\n\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"ar10_kinematics_client\");\n\n ros::NodeHandle n;\n\tros::ServiceClient client = n.serviceClient<ar10_kinematics::IkHand>(\"/ar10_right/finger_ik_sever\");\n\n\tros::WallDuration sleep_time(2);\n sensor_msgs::JointState right_hand_cmds;\n\tright_hand_cmds.position.resize(2);\n\tright_hand_cmds.name.resize(2);\n\tright_hand_cmds.name[0]= \"servo0\";\n\tright_hand_cmds.name[1]= \"servo1\";\n ros::Publisher right_ar10Hand_pub = n.advertise<sensor_msgs::JointState>(\"/ar10_right/ar10/right/joint_states\", 1000);\n right_hand_cmds.position[0] = 1.2;\n right_hand_cmds.position[0] = 0.85;\n right_hand_cmds.position[1] = 0.92;\n\tROS_INFO(\"moving thumb out of the way\"); \n\tdo\n\t{\n\t\tsleep_time.sleep();\n\t\tright_ar10Hand_pub.publish(right_hand_cmds);\n\t\tsleep_time.sleep();\n\t}\n\twhile (!right_ar10Hand_pub.getNumSubscribers());\n\tsleep_time.sleep();\n\n\tROS_INFO(\"opening index finger\"); \n\tright_hand_cmds.position.resize(2);\n\tright_hand_cmds.name.resize(2);\n\tright_hand_cmds.name[0]= \"servo8\";\n\tright_hand_cmds.name[1]= \"servo9\";\n // ros::Publisher right_ar10Hand_pub = n.advertise<sensor_msgs::JointState>(\"/ar10_right/ar10/right/joint_states\", 1000);\n right_hand_cmds.position[0] = 0.87;\n right_hand_cmds.position[1] = 0.87;\n\tdo\n\t{\n\t\tsleep_time.sleep();\n\t\tright_ar10Hand_pub.publish(right_hand_cmds);\n\t\tsleep_time.sleep();\n\t}\n\twhile (!right_ar10Hand_pub.getNumSubscribers());\n\tsleep_time.sleep();\n\n\tar10_kinematics::IkHand srv;\n\n\n srv.request.getJacobian=false;\n srv.request.finger=5; // finger=5 for thumb, finger4=index, and so on\n srv.request.desiredPose.clear();\n // Result_1 /// K=0.1\n // std::vector<double> desired_pose= { 0.555484, -0.437536, -0.555484, 0.437536, -0.0167888, 0.0221666, 0.00355661, 0.0479966};\n // Result_2 /// K=0.1\n // std::vector<double> desired_pose={ 0.706236, -0.0350761, -0.706236, 0.0350761, 0.0229575, 0.0377621, 0.0245886, 0.0706021};\n // std::vector<double> desired_pose={ 0.695946, -0.125139, -0.695946, 0.125139, 0.00773141, 0.0393977, 0.0135504, 0.0717592};\n // std::vector<double> desired_pose={ 0.680947, -0.190554, -0.680947, 0.190554, 0.0135467, 0.0246946, 0.0224075, 0.0563586};\n\n\n\n\t/////////////////////// FOR THUMB ////////////////////////////////////////////////////\n // std::vector<double> desired_pose={0.774791, 0.448202, -0.134365, -0.425159, 0.0216271, 0.00461104, 0.0419339, 0.0310207}; \n std::vector<double> desired_pose={0.960477, 0.235529, 0.122626, -0.0835014, 0.0014986, -0.02179, 0.0518687, 0.0319472}; \n\t/////////////////////// FOR RELATIVE INDEXTIP AND THUMBTIP //////////////////////////////////////////////////// \n // std::vector<double> desired_pose={0.61437, 0.0830506, 0.748433, -0.235586, 0.0131437, 0.00283279, -0.0162992, -0.0165058}; \n // std::vector<double> desired_pose={0.614229, 0.0857312, 0.746268, -0.241779, 0.012737, 0.0030581, -0.0162134, -0.0166017}; \n // std::vector<double> desired_pose={0.732594, -0.201061, 0.526397, -0.381821, 0.00459042, 0.0240458, -0.0261999, -0.0399749}; \n for (int i=0; i<desired_pose.size(); i++)\n {\n srv.request.desiredPose.push_back(desired_pose[i]); \n }\n\n\n if (client.call(srv))\n {\n std::cout << \"q: \" << std::endl;\n for(int i=0; i<srv.response.jointPosition.size(); i++)\n std::cout << srv.response.jointPosition[i] << std::endl;\n }\n else\n {\n ROS_ERROR(\"Failed to call service finger_ik_sever\");\n return 1;\n }\n\t// ros::WallDuration sleep_time(2);\n // sensor_msgs::JointState right_hand_cmds;\n\n\n\n\t// right_hand_cmds.position.resize(2);\n\t// right_hand_cmds.name.resize(2);\n\t// right_hand_cmds.name[0]= \"servo8\";\n\t// right_hand_cmds.name[1]= \"servo9\";\n // // ros::Publisher right_ar10Hand_pub = n.advertise<sensor_msgs::JointState>(\"/ar10_right/ar10/right/joint_states\", 1000);\n // right_hand_cmds.position[0] = srv.response.jointPosition[0];\n // right_hand_cmds.position[1] = srv.response.jointPosition[1];\n\t// do\n\t// {\n\t// \tsleep_time.sleep();\n\t// \tright_ar10Hand_pub.publish(right_hand_cmds);\n\t// \tsleep_time.sleep();\n\t// }\n\t// while (!right_ar10Hand_pub.getNumSubscribers());\n\t// ROS_INFO(\"commanding right hand index finger for desired position\"); \n return 0;\n}" }, { "alpha_fraction": 0.646822452545166, "alphanum_fraction": 0.6691339612007141, "avg_line_length": 37.1370964050293, "blob_id": "3974108d2b997179453cbdd6392d3576150adf7b", "content_id": "d3ca22a0819e9f6689ddb80734b062d6d0e124a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9457, "license_type": "no_license", "max_line_length": 355, "num_lines": 248, "path": "/dq_robotics/include/dq_robotics/dq_controller.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/dq_controller.h>\nusing namespace Eigen;\n\nDQController::DQController(){}\nDQController::~DQController(){}\n\nstd::vector<Matrix<double,8,1> > DQController::fkmDual(std::vector<RowVector3d> u,std::vector<RowVector3d> p, RowVectorXd q, std::vector<int> joint_type)\n{\n\tint joint_size=joint_type.size();\n// ROS_INFO(\"joint_size=%d\", joint_size);\n\tRowVectorXd q_dual;\t\n\tq_dual=RowVectorXd::Zero(joint_size*2);\n// ROS_INFO(\"11\");\n\tfor (int j=0; j< joint_size; j++)\n\t{\n\t\tif(joint_type[j]==0)\n\t\t\tq_dual(2*j)=q(j);\n\t\telse\n\t\t\tq_dual(2*j+1)=q(j);\n\t\t// ROS_INFO(\"j=%d\", j);\n\t}\n// ROS_INFO(\"00\");\n\tstd::vector<Matrix<double,8,1> > fkm_current;\n\tfkm_current.clear();\n\tfkm_current.resize(joint_size);\n// ROS_INFO(\"22\");\n\tfor (int i=0;i<joint_size; i++)\n\t{\n\t\tdouble theta_i=q_dual[2*i];\n\t\tRowVector3d u_i=u[i];\n\t\tRowVector3d p_i=p[i];\n\t\tdouble d_i=q_dual[2*i+1];\n\t\tMatrix<double,8,1> screwDispalcementArray_i;\n\t\tscrewDispalcementArray_i= DQoperations::screw2DQ(theta_i, u_i, d_i, p_i.cross(u_i));\n\t\t// std::cout << \"screwDispalcementArray_\" << i << \": \" << screwDispalcementArray_i.transpose() << std::endl;\n\t\tif (i==0)\n\t\t\tfkm_current[i]=screwDispalcementArray_i;\n\t\telse\n\t\t\tfkm_current[i]=DQoperations::mulDQ(fkm_current[i-1],screwDispalcementArray_i);\n\t\t// ROS_INFO(\"i=%d\",i);\n\t\t// std::cout << \"fkm_current_source_\" << i << \": \" << fkm_current[i].transpose() << std::endl;\n\t}\n\n\treturn fkm_current;\n}\n\nMatrixXd DQController::jacobianDual(std::vector<RowVector3d> u, std::vector<RowVector3d> p, Matrix<double,8,1> pe_init, std::vector<int> joint_type, std::vector<Matrix<double,8,1> > fkm_current)\n{\n\tint joint_size =u.size();\n\n\tMatrixXd jacobian;\n\tjacobian =MatrixXd::Zero(6,joint_size);\n\t\n\n\tMatrix<double,8,1> screwDispalcementArray_i, screw_axis_i, pose_i;\n\t\n\tscrewDispalcementArray_i= fkm_current[joint_size-1];/*The numbering in C++ starts at 0*/\n\t\n\tscrewDispalcementArray_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pe_init), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\n\tRowVector3d pose_ee_now;\n\n\tpose_ee_now << screwDispalcementArray_i(5), screwDispalcementArray_i(6), screwDispalcementArray_i(7); \n\n\tif(joint_type[0]==0)\n\t{\n\t\tjacobian.col(0)<< (p[0].cross(u[0])).transpose(), u[0].transpose();/*writing Jacobian seperately for first joint for faster operation*/\n\t}\n\telse\n\t{\n\t\tjacobian.col(0)<< u[0].transpose(), 0, 0, 0;\n\t\t\n\t}\n\n\tfor(int i=1; i<joint_size; i++)\n\t{\n\n\t\tscrewDispalcementArray_i=fkm_current[i-1];\n\t\n\t\tscrew_axis_i<< 0, u[i].transpose(), 0, (p[i].cross(u[i])).transpose();\n\t\n\t\tscrew_axis_i=DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, screw_axis_i), DQoperations::classicConjDQ(screwDispalcementArray_i));\t\n\t\n\t\tRowVector3d u_i, p_i;\n\t\tu_i << screw_axis_i(1), screw_axis_i(2), screw_axis_i(3);\n\t\tpose_i << 1, 0, 0, 0, 0, p[i].transpose();\n\t\tpose_i= DQoperations::mulDQ(DQoperations::mulDQ(screwDispalcementArray_i, pose_i), DQoperations::combinedConjDQ(screwDispalcementArray_i));\n\t\tp_i << pose_i(5), pose_i(6), pose_i(7);\n\t\tif(joint_type[i]==0)\n\t\t{\n\t\t\tjacobian.col(i) << (p_i.cross(u_i)).transpose(), u_i.transpose(); \n\t\t}\n\t\telse\n\t\t\tjacobian.col(i) << u_i.transpose(), 0, 0, 0;\n\t}\n\treturn jacobian;\n}\n\nMatrixXd DQController::jacobianDual_8d(int joint_size, MatrixXd jacobian)\n{\n\tMatrixXd jacobian_8d;\n\tjacobian_8d=MatrixXd::Zero(8,joint_size);\n jacobian_8d.row(1)=jacobian.row(0);\n\tjacobian_8d.row(2)=jacobian.row(1);\n\tjacobian_8d.row(3)=jacobian.row(2);\n\tjacobian_8d.row(5)=jacobian.row(3);\n\tjacobian_8d.row(6)=jacobian.row(4);\n\tjacobian_8d.row(7)=jacobian.row(5);\n\treturn jacobian_8d;\n}\n\n// MatrixXd = DQController::getJacobianDot(link_velocity_right, jacobian_6d);\n// {\n// \tint joint_size = jacobian_6d.cols();\n// \tMatrixXd jacobian_6d_dot_right = MatrixXd::Zero(6, joint_size);\n// \t\tfor (int i=0;i<joint_size; i++)\n// \t{\n// \t}\n// }\nMatrixXd DQController::getJacobianDot(MatrixXd link_velocity, MatrixXd jacobian_6d)\n{\n\tint joint_size = jacobian_6d.cols();\n\tMatrixXd jacobian_6d_dot = MatrixXd::Zero(6, joint_size);\n\tfor (int i=0;i<joint_size; i++)\n\t{\n\t\tjacobian_6d_dot.col(i) = DQoperations::crossProductOp_6d(link_velocity.col(i))*jacobian_6d.col(i);\t\t\n\t} \n\treturn jacobian_6d_dot;\n}\n\nMatrixXd DQController::linkVelocites(MatrixXd jacobian_6d, RowVectorXd joint_velocities)\n{\n\t// link_velocities.col(0) refers to first link velocity and so on, because we assume the joint is fixed with child links\n\tint joint_size = jacobian_6d.cols();\n\tMatrixXd link_velocities = MatrixXd::Zero(6, joint_size);\n\tfor (int i=0;i<joint_size; i++)\n\t{\n\t\tif(i == 0)\n\t\t\tlink_velocities.col(i) = jacobian_6d.col(i)*joint_velocities(i);\n\t\telse\n\t\t\tlink_velocities.col(i) = link_velocities.col(i-1) + jacobian_6d.col(i)*joint_velocities(i);\n\t}\n\treturn link_velocities;\n}\n\nRowVectorXd DQController::getScrewError_8d(Matrix<double,8,1> pose_now, Matrix<double,8,1> pose_desired)\n{\n\tRowVectorXd screw_error=RowVectorXd::Zero(8);\n\tRowVector3d v_e, w_e;\t\n \tdouble norm_error_position=DQoperations::get_error_screw_param(pose_now, pose_desired, v_e, w_e);\n \tscrew_error << 0, v_e(0), v_e(1), v_e(2), 0, w_e(0), w_e(1), w_e(2);\n \t// std::cout << \"screwError(getScrewError_8d): \" << 0 << v_e(0) << v_e(1) << v_e(2) << 0 << w_e(0) << w_e(1) << w_e(2) << std::endl;\n \treturn screw_error;\n}\n\nRowVectorXd DQController::calculateControlVel_velcityFF(double Kp, double mu, RowVectorXd screwError_8d, MatrixXd jacobian_8d, int joint_size, Matrix<double,8,1> cart_velocity_desired)\n{\n\tscrewError_8d=-Kp*screwError_8d+DQoperations::Matrix8d2RowVector8d(cart_velocity_desired);\n\t// ROS_INFO(\"5\");\n\tMatrixXd jacobian_damped_, A; \n\t// std::cout << \"jacobian_.size: \" << jacobian_.rows() << \":\" << jacobian_.cols() << std::endl; \n\tA= jacobian_8d.transpose()*jacobian_8d + mu*MatrixXd::Identity(joint_size, joint_size); \n\tjacobian_damped_=((A.inverse())*jacobian_8d.transpose());\t\n\t// std::cout << \"screw_error_.size: \" << screw_error_.rows() << \":\" << screw_error_.cols() << std::endl; \n\t// std::cout << \"jacobian_damped_.size: \" << jacobian_damped_.rows() << \":\" << jacobian_damped_.cols() << std::endl; \n\tRowVectorXd q_dot_1=(jacobian_damped_*screwError_8d.transpose()).transpose();\t\n\t// RowVectorXd q_dot_1=(pseudoInverse(jacobian_)*screw_error_.transpose()).transpose();\t\n\tRowVectorXd q_dot;\n\tq_dot=q_dot_1;\n\treturn q_dot;\n}\n\n\nRowVectorXd DQController::jointVelocity4velocityControl(double Kp, double mu, std::vector<RowVector3d> u, std::vector<RowVector3d> p, Matrix<double,8,1> pose_now, Matrix<double,8,1> pe_init, std::vector<int> joint_type, Matrix<double,8,1> pose_desired, Matrix<double,8,1> cart_vel_desired, std::vector<Matrix<double,8,1> > fkm_matrix, double& norm_error)\n{\n\t\n\tint joint_size=u.size();\n\t// std::cout << \"fkm_matrix: \" << std::endl;\n\n\t// for (int i=0; i<u.size(); i++)\n\t// {\n\t// \tstd::cout << fkm_matrix[i] << std::endl;\n\t// \tstd::cout << \"u_left[i]: \" << u[i] << std::endl;\n\t// \tstd::cout << \"p_left[i]: \" << p[i] << std::endl;\t\t\n\t// }\n\n// std::cout << \"pose_now: \" << pose_now << std::endl;\n// std::cout << \"pose_desired: \" << pose_desired << std::endl;\n// std::cout << \"pe_init: \" << pe_init << std::endl;\n\tMatrixXd jacobian_8d;\n\tjacobian_8d= DQController::jacobianDual(u, p, pe_init, joint_type, fkm_matrix);\t\n\tjacobian_8d= DQController::jacobianDual_8d(joint_size, jacobian_8d);\n\t// std::cout << \"jacobian_8d: \" << std::endl;\n\t// std::cout << jacobian_8d << std::endl;\n\tRowVectorXd screw_error= DQController::getScrewError_8d(pose_now, pose_desired);\n\n\tnorm_error=screw_error.norm();\n\t// RowVectorXd q_dot= DQController::calculateControlVel_velcityFF(Kp, mu, screw_error, jacobian_8d, joint_size, cart_vel_desired);\n\tRowVectorXd q_dot= DQController::calculateControlVel(Kp, mu, screw_error, jacobian_8d, joint_size);\n\t// std::cout << \"q_dot: \" << q_dot << std::endl;\n\treturn q_dot;\n\n}\n\nRowVectorXd DQController::calculateControlVel(double Kp, double mu, RowVectorXd screwError_8d, MatrixXd jacobian_8d, int joint_size)\n{\n\tscrewError_8d=-Kp*screwError_8d;\n\t// ROS_INFO(\"5\");\n\tMatrixXd jacobian_damped_, A; \n\t// std::cout << \"jacobian_.size: \" << jacobian_.rows() << \":\" << jacobian_.cols() << std::endl; \n\tA= jacobian_8d.transpose()*jacobian_8d + mu*MatrixXd::Identity(joint_size, joint_size); \n\tjacobian_damped_=((A.inverse())*jacobian_8d.transpose());\t\n\t// std::cout << \"screw_error_: \" << screwError_8d << std::endl; \n\t// std::cout << \"jacobian_damped_: \" << std::endl; \n\t// std::cout << jacobian_damped_ << std::endl; \n\tRowVectorXd q_dot_1=(jacobian_damped_*screwError_8d.transpose()).transpose();\t\n\t// std::cout << \"q_dot_1: \" << q_dot_1 << std::endl; \t\n\t// RowVectorXd q_dot_1=(pseudoInverse(jacobian_)*screw_error_.transpose()).transpose();\t\n\tRowVectorXd q_dot;\n\tq_dot=q_dot_1;\n\treturn q_dot;\n}\n\nRowVectorXd DQController::normalizeControlVelocity( RowVectorXd q_dot, std::vector<double> joint_velocity_limit)\n{\n\tstd::vector<double> ratio;\n\tbool shouldNormalizeVelocity=false;\n\tdouble ratio_to_normalize_velocity_cmds=1.0;\n\tratio.clear();\n\tint joint_size=q_dot.size();\n \t\t// ROS_INFO(\"Hi norm 1\");\n \tfor(int i=0; i<q_dot.size(); i++)\n \t{\n \t\t// ROS_INFO(\"Hi norm 2, i=%d\", i);\n \t\tdouble ratio_i=1;\n \t\tratio_i=fabs(q_dot(i)/(0.5*joint_velocity_limit[i]));\n \t\tratio.push_back(ratio_i);\n \t\tif(ratio_i>1)\n \t\t\tshouldNormalizeVelocity=true;\n \t}\n \tif(shouldNormalizeVelocity)\n \t{\n \t\t// ROS_INFO(\"Hi norm 3\");\n \t\tratio_to_normalize_velocity_cmds = *max_element(ratio.begin(), ratio.end());\n \t\tq_dot=q_dot/(ratio_to_normalize_velocity_cmds);\n \t}\n \treturn q_dot;\n}" }, { "alpha_fraction": 0.7445743083953857, "alphanum_fraction": 0.7499678730964661, "avg_line_length": 39.24289321899414, "blob_id": "18768640f71d5da427b2a4d832521b931cb41715", "content_id": "3cc7a8f22a2dcde842ded1736a6c7731c48840ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 15574, "license_type": "no_license", "max_line_length": 165, "num_lines": 387, "path": "/dq_robotics/CMakeLists.txt", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(dq_robotics C CXX)\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\nSET(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations\")\n## Compile as C++11, supported in ROS Kinetic and newer\n# add_compile_options(-std=c++11)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n rospy\n actionlib\n sensor_msgs\n std_msgs\n control_msgs\n trajectory_msgs\n dynamic_reconfigure\n baxter_core_msgs\n roslib\n fcl_capsule\n kdl_parser\n message_generation\n baxter_interface\n tf\n joint_limits_interface\n urdf\n baxter_core_msgs\n visualization_msgs\n geometry_msgs\n)\n\nlist(APPEND CMAKE_MODULE_PATH ${controlit_cmake_DIR}/../../../../src/controlit/controlit_cmake/cmake)\n\ncatkin_python_setup()\n\n add_service_files(\n FILES\n # IkHand.srv\n BaxterControl.srv\n Grasp.srv\n# Service1.srv\n# Service2.srv\n )\n\n\nadd_message_files(\n FILES\n DualArmPlotData.msg\n ControllerPerformance.msg\n ResolveAccControlPrfmnc.msg\n ResolveAccControlPrfmnc_processed.msg\n)\n \ngenerate_messages(\n DEPENDENCIES\n std_msgs\n sensor_msgs\n)\n\ngenerate_dynamic_reconfigure_options(\n config/acc_control_params.cfg\n #...\n)\n\n# add_service_files(\n# FILES\n# GetIKSolution.srv\n# SetJointGoals.srv\n# GetJointTrajectory.srv\n# BaxterControl.srv\n# )\n\n\n\n\ncatkin_package(\n CATKIN_DEPENDS\n message_runtime\n rospy\n actionlib\n sensor_msgs\n std_msgs\n control_msgs\n trajectory_msgs\n dynamic_reconfigure\n baxter_core_msgs\n roslib\n kdl_parser\n baxter_interface\n tf\n tf_conversions\n joint_limits_interface\n urdf\n orocos_kinematics_dynamics\n INCLUDE_DIRS include\n LIBRARIES dq_operations dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib\n DEPENDS orocos_kdl\n) \n\n\nfind_package(urdf REQUIRED) \nfind_package(Eigen3 REQUIRED) \n# find_package(orocos_kdl REQUIRED)\n# find_package(Rbdl REQUIRED)\ninclude_directories(${EIGEN3_INCLUDE_DIR})\ninclude_directories(include\n ${catkin_INCLUDE_DIRS}\n ${Boost_INCLUDE_DIRS}\n ${GSTREAMER_INCLUDE_DIRS}\n ${fcl_capsule_INCLUDE_DIRS})\n\n\nadd_library(graph include/dq_robotics/graph.cpp)\nadd_dependencies(graph ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\nadd_library(dq_operations include/dq_robotics/DQoperations.cpp)\nadd_dependencies(dq_operations ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\nadd_library(dq_controller include/dq_robotics/dq_controller.cpp)\nadd_dependencies(dq_controller ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\nadd_library(jacDotSolver include/dq_robotics/jacDotSolver.cpp)\nadd_dependencies(jacDotSolver ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n# add_library(chainjnttojacsolver include/dq_robotics/chainjnttojacsolver.cpp)\n# add_dependencies(chainjnttojacsolver ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n# add_library(chainjnttojacdotsolver include/dq_robotics/chainjnttojacdotsolver.cpp)\n# add_dependencies(chainjnttojacdotsolver ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n\nadd_library(baxter_dq include/dq_robotics/baxter_dq.cpp)\nadd_dependencies(baxter_dq ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(baxter_dq ${catkin_LIBRARIES})\n\nadd_library(baxter_pose_Control_server_lib src/baxter_poseControl_server.cpp)\nadd_dependencies(baxter_pose_Control_server_lib ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(baxter_pose_Control_server_lib ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller)\n\nadd_executable(baxterPoseControl_server src/baxter_poseControl_server.cpp)\ntarget_link_libraries(baxterPoseControl_server ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller)\n\n# add_executable(manipulationTaskController src/manipulation_task_controller.cpp)\n# target_link_libraries(manipulationTaskController ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller)\n\n# add_library(ar10_kinematics_lib src/ar10_kinematics.cpp)\n# add_dependencies(ar10_kinematics_lib ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(ar10_kinematics_lib ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller)\n\n# add_executable(ar10Kinematics src/ar10_kinematics.cpp)\n# # add_dependencies(ar10Kinematics ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(ar10Kinematics ${catkin_LIBRARIES} dq_operations dq_controller)\n\n# add_executable(baxter_ar10_kinematics src/baxter_ar10_kinematics.cpp)\n# add_dependencies(baxter_ar10_kinematics ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(baxter_ar10_kinematics ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n\n# add_executable(baxter_AbsRelative_Control src/baxter_AbsRelative_Control.cpp)\n# add_dependencies(baxter_AbsRelative_Control ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(baxter_AbsRelative_Control ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(baxterTaskSpaceClient src/test/baxterTaskSpaceClient.cpp)\n# add_dependencies(baxterTaskSpaceClient ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(baxterTaskSpaceClient ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(ar10Client src/ar10_client.cpp)\n# add_dependencies(ar10Client ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(ar10Client ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(fake_ar10_jointStates src/test/fake_ar10_jointStates.cpp)\n# add_dependencies(fake_ar10_jointStates ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(fake_ar10_jointStates ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(rviz_shape_publisher src/test/rviz_shape_publisher.cpp)\n# target_link_libraries(rviz_shape_publisher ${catkin_LIBRARIES})\n\n# add_executable(test_graph src/test/test_graph.cpp)\n# target_link_libraries(test_graph ${catkin_LIBRARIES})\n\n# add_executable(grasp_client_test src/test/grasp_client_test.cpp)\n# add_dependencies(grasp_client_test ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(grasp_client_test ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(kdl_controller src/kdl_controller.cpp)\n# add_dependencies(kdl_controller ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(kdl_controller ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib)\n\n# add_executable(kdl_controller_new src/kdl_controller_new.cpp)\n# add_dependencies(kdl_controller_new ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# target_link_libraries(kdl_controller_new ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib ar10_kinematics_lib jacDotSolver)\n\nadd_executable(resolved_acc_control src/resolvedAccControl/resolved_acc_control.cpp)\nadd_dependencies(resolved_acc_control ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(resolved_acc_control ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib jacDotSolver)\n\nadd_executable(new_traj_resolved_acc_control src/resolvedAccControl/new_traj_resolved_acc_control.cpp)\nadd_dependencies(new_traj_resolved_acc_control ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(new_traj_resolved_acc_control ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller baxter_pose_Control_server_lib jacDotSolver)\n\nadd_executable(disable_gravity_baxSDK src/resolvedAccControl/disable_gravity_baxSDK.cpp)\nadd_dependencies(disable_gravity_baxSDK ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(disable_gravity_baxSDK ${catkin_LIBRARIES})\n\nadd_executable(result_analyzer_ResolcedAccControl src/resolvedAccControl/result_analyzer_ResolcedAccControl.cpp)\nadd_dependencies(result_analyzer_ResolcedAccControl ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\ntarget_link_libraries(result_analyzer_ResolcedAccControl ${catkin_LIBRARIES})\n\n# add_executable(test_rbdl_ros src/test/test_rbdl_ros.cpp)\n# target_link_libraries(test_rbdl_ros ${catkin_LIBRARIES} dq_operations)\n\n\n\n# add_dependencies(manipulationTaskController ${control_msgs_EXPORTED_TARGETS} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n# add_executable(baxterPoseControl_server_2 src/baxter_poseControl_server_2.cpp)\n# target_link_libraries(baxterPoseControl_server_2 ${catkin_LIBRARIES} dq_operations baxter_dq dq_controller)\n## System dependencies are found with CMake's conventions\n# find_package(Boost REQUIRED COMPONENTS system)\n\n\n## Uncomment this if the package has a setup.py. This macro ensures\n## modules and global scripts declared therein get installed\n## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html\n# catkin_python_setup()\n\n################################################\n## Declare ROS messages, services and actions ##\n################################################\n\n## To declare and build messages, services or actions from within this\n## package, follow these steps:\n## * Let MSG_DEP_SET be the set of packages whose message types you use in\n## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).\n## * In the file package.xml:\n## * add a build_depend tag for \"message_generation\"\n## * add a build_depend and a run_depend tag for each package in MSG_DEP_SET\n## * If MSG_DEP_SET isn't empty the following dependency has been pulled in\n## but can be declared for certainty nonetheless:\n## * add a run_depend tag for \"message_runtime\"\n## * In this file (CMakeLists.txt):\n## * add \"message_generation\" and every package in MSG_DEP_SET to\n## find_package(catkin REQUIRED COMPONENTS ...)\n## * add \"message_runtime\" and every package in MSG_DEP_SET to\n## catkin_package(CATKIN_DEPENDS ...)\n## * uncomment the add_*_files sections below as needed\n## and list every .msg/.srv/.action file to be processed\n## * uncomment the generate_messages entry below\n## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)\n\n## Generate messages in the 'msg' folder\n# add_message_files(\n# FILES\n# Message1.msg\n# Message2.msg\n# )\n\n## Generate services in the 'srv' folder\n# add_service_files(\n# FILES\n# Service1.srv\n# Service2.srv\n# )\n\n## Generate actions in the 'action' folder\n# add_action_files(\n# FILES\n# Action1.action\n# Action2.action\n# )\n\n## Generate added messages and services with any dependencies listed here\n# generate_messages(\n# DEPENDENCIES\n# std_msgs\n# )\n\n################################################\n## Declare ROS dynamic reconfigure parameters ##\n################################################\n\n## To declare and build dynamic reconfigure parameters within this\n## package, follow these steps:\n## * In the file package.xml:\n## * add a build_depend and a run_depend tag for \"dynamic_reconfigure\"\n## * In this file (CMakeLists.txt):\n## * add \"dynamic_reconfigure\" to\n## find_package(catkin REQUIRED COMPONENTS ...)\n## * uncomment the \"generate_dynamic_reconfigure_options\" section below\n## and list every .cfg file to be processed\n\n## Generate dynamic reconfigure parameters in the 'cfg' folder\n# generate_dynamic_reconfigure_options(\n# cfg/DynReconf1.cfg\n# cfg/DynReconf2.cfg\n# )\n\n###################################\n## catkin specific configuration ##\n###################################\n## The catkin_package macro generates cmake config files for your package\n## Declare things to be passed to dependent projects\n## INCLUDE_DIRS: uncomment this if your package contains header files\n## LIBRARIES: libraries you create in this project that dependent projects also need\n## CATKIN_DEPENDS: catkin_packages dependent projects also need\n## DEPENDS: system dependencies of this project that dependent projects also need\n\n\n## Declare a C++ library\n# add_library(${PROJECT_NAME}\n# src/${PROJECT_NAME}/dualQuaternion_robotics.cpp\n# )\n\n## Add cmake target dependencies of the library\n## as an example, code may need to be generated before libraries\n## either from message generation or dynamic reconfigure\n# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Declare a C++ executable\n## With catkin_make all packages are built within a single CMake context\n## The recommended prefix ensures that target names across packages don't collide\n# add_executable(${PROJECT_NAME}_node src/dualQuaternion_robotics_node.cpp)\n\n## Rename C++ executable without prefix\n## The above recommended prefix causes long target names, the following renames the\n## target back to the shorter version for ease of user use\n## e.g. \"rosrun someones_pkg node\" instead of \"rosrun someones_pkg someones_pkg_node\"\n# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX \"\")\n\n## Add cmake target dependencies of the executable\n## same as for the library above\n# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\n# target_link_libraries(${PROJECT_NAME}_node\n# ${catkin_LIBRARIES}\n# )\n\n#############\n## Install ##\n#############\n\n# all install targets should use catkin DESTINATION variables\n# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html\n\n## Mark executable scripts (Python etc.) for installation\n## in contrast to setup.py, you can choose the destination\n# install(PROGRAMS\n# scripts/my_python_script\n# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n# )\n\n## Mark executables and/or libraries for installation\n# install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node\n# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n# )\n\n## Mark cpp header files for installation\n# install(DIRECTORY include/${PROJECT_NAME}/\n# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}\n# FILES_MATCHING PATTERN \"*.h\"\n# PATTERN \".svn\" EXCLUDE\n# )\n\n## Mark other files for installation (e.g. launch and bag files, etc.)\n# install(FILES\n# # myfile1\n# # myfile2\n# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}\n# )\n\n#############\n## Testing ##\n#############\n\n## Add gtest based cpp test target and link libraries\n# catkin_add_gtest(${PROJECT_NAME}-test test/test_dualQuaternion_robotics.cpp)\n# if(TARGET ${PROJECT_NAME}-test)\n# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})\n# endif()\n\n## Add folders to be run by python nosetests\n# catkin_add_nosetests(test)\n" }, { "alpha_fraction": 0.6688230633735657, "alphanum_fraction": 0.6969449520111084, "avg_line_length": 38.10774230957031, "blob_id": "01893b61d7e6457a3e955f7aaaca99ea7a15a749", "content_id": "f7ef6a7b40571a7bfd70a51337c60650ee0e40e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 49001, "license_type": "no_license", "max_line_length": 394, "num_lines": 1253, "path": "/dq_robotics/src/ar10_kinematics.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/ar10_kinematics.h>\n// #include <baxter_trajectory_interface/baxter_poseControl_server.h>\n#define PI 3.14159265\n\nAR10Kinematics::AR10Kinematics(){}\n\nvoid AR10Kinematics::init_AR10Kinematics()\n{\n\n\tstd::string paramName=\"result_file_name\";\n\tif(!ros::param::get(paramName, result_file_name))\n\t{\n\t\tstd::cout << \"result_file_name not found\" << std::endl;\n\t}\n\t// result_file_name=\"iser2018_result.csv\";\n\tpath = ros::package::getPath(\"ar10_kinematics\");\n\tpath.append(\"/results/\");\n\tpath.append(result_file_name);\n\tbase_frame=\"ar10_right_mod/base\";\n\tright_ar10Hand_pub = n.advertise<sensor_msgs::JointState>(\"/ar10_right/ar10/right/joint_states\", 1000);\n\t// finger_ik_service=n.advertiseService(\"/ar10_right/finger_ik_sever\", &AR10Kinematics::computeHandIKCallback, this);\n\n\tMatrix4d mat = Matrix4d::Identity();\n\tmat(2,3)=-0.0021;\n\tframe_hand_base = DQoperations::htm2DQ(mat);\n hand_base_static_transformStamped.header.stamp = ros::Time::now();\n hand_base_static_transformStamped.header.frame_id = \"ar10_right/circuit_support\";\n\thand_base_static_transformStamped.child_frame_id = \"ar10_right_mod/hand_base\";\t \n\t\n\thand_base_static_transformStamped.transform.translation.x=mat(0,3);\n\thand_base_static_transformStamped.transform.translation.y=mat(1,3);\n\thand_base_static_transformStamped.transform.translation.z=mat(2,3);\n hand_base_static_transformStamped.transform.rotation.x = frame_hand_base(1);\n hand_base_static_transformStamped.transform.rotation.y = frame_hand_base(2);\n hand_base_static_transformStamped.transform.rotation.z = frame_hand_base(3);\n hand_base_static_transformStamped.transform.rotation.w = frame_hand_base(0);\t\t\n joint_size_coupled = 2;\n};\n\nAR10Kinematics::~AR10Kinematics(){};\n\n\nvoid AR10Kinematics::getJacobianCoupled(finger_params &finger)\n{\n\t\t\tstd::cout << \"ar10_here_1\" << std::endl;\n\tfinger.finger_jacobian_coupled=MatrixXd::Zero(8, 2);\n\tfinger.finger_jacobian_simple= DQController::jacobianDual(finger.u, finger.p, finger.finger_ee_init, finger.finger_joint_type, finger.screwDispalcementArray);\t\n\tfinger.finger_jacobian_simple= DQController::jacobianDual_8d(finger.p.size(), finger.finger_jacobian_simple);\n\tfinger.finger_jacobian_coupled.col(0)= finger.finger_jacobian_simple.col(0);\n\tdouble coupling_term = (finger.distal_phalanx.p*sin(finger.distal_phalanx.psi - finger.distal_phalanx.theta) - finger.distal_phalanx.h*sin(finger.distal_phalanx.theta + finger.distal_phalanx.alpha - finger.distal_phalanx.psi))/(finger.distal_phalanx.h*sin(finger.distal_phalanx.theta + finger.distal_phalanx.alpha - finger.distal_phalanx.psi));\n\tfinger.finger_jacobian_coupled.col(1) = finger.finger_jacobian_simple.col(1) + coupling_term*finger.finger_jacobian_simple.col(2);\n}\n\nbool AR10Kinematics::getControllerParms()\n{\n\tdouble value;\t\n\t\n\tstd::string paramName=\"ar10_dt\";\n\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"ar10 controller param: ar10_dt not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tdt = value;\n\n\tparamName=\"ar10_Kp\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"ar10 controller param: ar10_Kp not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tKp = value;\n\n\tparamName=\"ar10_mu\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"ar10 controller param: ar10_mu not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tmu = value;\n\n\tparamName=\"ar10_slider_cmd_tolerance\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"ar10 controller param: ar10_slider_cmd_tolerance not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tslider_cmd_tolerance = value;\n\t\n\treturn 1;\n}\n\n// void AR10Kinematics::update_relative()\n// {\n// \tu_relative.resize(5);\n// \tp_relative.resize(5);\n// \tAr10KinematicsLoop();\n// \tee_relative = DQoperations::mulDQ(DQoperations::classicConjDQ(index_finger.finger_ee_current), thumb.finger_ee_current);\n// \tu_relative[0]= DQoperations::transformLineVector(index_finger.u[2], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tu_relative[1]= DQoperations::transformLineVector(index_finger.u[1], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tu_relative[2]= DQoperations::transformLineVector(index_finger.u[0], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tu_relative[3]= DQoperations::transformLineVector(thumb.u[0], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tu_relative[4]= DQoperations::transformLineVector(thumb.u[1], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n\n// \tp_relative[0]= DQoperations::transformPoint(index_finger.p[2], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tp_relative[1]= DQoperations::transformPoint(index_finger.p[1], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tp_relative[2]= DQoperations::transformPoint(index_finger.p[0], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tp_relative[3]= DQoperations::transformPoint(thumb.p[0], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tp_relative[4]= DQoperations::transformPoint(thumb.p[1], DQoperations::classicConjDQ(index_finger.finger_ee_current));\n// \tq_relative << index_finger.q(2), index_finger.q(1), index_finger.q(0), thumb.q(0), thumb.q(1); \n// }\n\nbool AR10Kinematics::ik_relative(dq_robotics::IkHand::Request hand_ik_req, dq_robotics::IkHand::Response &hand_ik_res)\n{\n\tAr10KinematicsLoop();\n\n\tfinger_params\tindex_ik, thumb_ik;\n\tindex_ik = index_finger; \n\tthumb_ik = thumb;\n\n\tright_hand_cmds.position.resize(4);\n\tright_hand_cmds.name.resize(4);\n\n\tright_hand_cmds.name[0]= \"servo0\";\n\tright_hand_cmds.name[1]= \"servo1\";\n\tright_hand_cmds.name[2]= \"servo8\";\n\tright_hand_cmds.name[3]= \"servo9\";\n\n\tee_relative = DQoperations::mulDQ(DQoperations::classicConjDQ(index_finger.finger_ee_current), thumb.finger_ee_current);\n\tMatrix<double,8,1> desiredPose;\n\tDQoperations::doubleToDQ(desiredPose, hand_ik_req.desiredPose);\n\n // controller\n\n\tRowVectorXd q, q_dot, screw_error, screw_error_position;\n\tq.resize(4);\n\tq_dot.resize(4);\n\tq << -index_ik.q(1), -index_ik.q(0), thumb_ik.q(0), thumb_ik.q(1);\n\t// q_dot.resize(5);\n\t// q << q_relative(0), q_relative(1), q_relative(2), q_relative(3), q_relative(4);\n\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\n\t// std::cout << \"result_file_name: \" << path << std::endl;\n\t// std::ofstream result_file(path, std::ios::app);\n\t// result_file.open(result_file_name);\n\tMatrix4d error_htm, current_htm, desired_htm;\n\tcurrent_htm =DQoperations::dq2HTM(ee_relative);\n\tdesired_htm =DQoperations::dq2HTM(desiredPose);\n\n\n\n // if(result_file.is_open())\n // {\n // \tstd::cout << \"file is open\" << std::endl;\n // }\n\t// result_file << \"current_dq_pose:\" << \",\" << finger_ik.finger_ee_current(0,0) << \",\" << finger_ik.finger_ee_current(1,0) << \",\" << finger_ik.finger_ee_current(2,0) << \",\" << finger_ik.finger_ee_current(3,0) << \",\" << finger_ik.finger_ee_current(4,0) << \",\" << finger_ik.finger_ee_current(5,0) << \",\" << finger_ik.finger_ee_current(6,0) << \",\" << finger_ik.finger_ee_current(7,0) << \", \\n\"; \n\t// result_file << \"deisred_dq_pose:\" << \",\" << desiredPose(0,0) << \",\" << desiredPose(1,0) << \",\" << desiredPose(2,0) << \",\" << desiredPose(3,0) << \",\" << desiredPose(4,0) << \",\" << desiredPose(5,0) << \",\" << desiredPose(6,0) << \",\" << desiredPose(7,0) << \", \\n\";\n\n\t// result_file << \"desired_xy:\" << \",\" << desired_htm(1,3) << \",\" << desired_htm(2,3) << \", \\n\";\n\t// result_file << \"init_xy:\" << \",\" << current_htm(1,3) << \",\" << current_htm(2,3) << \", \\n\";\n\n\n\t// result_file << \"time\" << \",\" << \"x_current\" << \",\" << \"y_current\" << \",\" << \"norm_error\" << \",\" << \"error_x\" << \",\" << \"error_y\" << \", \\n\";\n\tMatrix<double,8,1> pose_error;\t\n\tros::Time end = ros::Time::now(), begin = ros::Time::now();\n\tdouble secs =0;\n\t\n\tros::WallDuration sleep_time(dt);\n\tdouble norm_error=1;\n\tMatrixXd jacobian_relative, jacobian_relative_position;\n\n\twhile(secs<60)\n\t{\n\t\tjacobian_relative = MatrixXd::Zero(8,4);\t\n\t\tjacobian_relative_position = MatrixXd::Zero(4,4);\t\n\t\tcurrent_htm =DQoperations::dq2HTM(ee_relative);\n\t\tpose_error =DQoperations::mulDQ(ee_relative, DQoperations::classicConjDQ(desiredPose));\t\t\n\t\tscrew_error= DQController::getScrewError_8d(ee_relative, desiredPose);\n\t\tscrew_error_position= screw_error.head(4);\n\t\t// norm_error=screw_error.norm();\n\t\tnorm_error=screw_error_position.norm();\n\t\n\t\tgetJacobianCoupled(index_ik);\n\t\tthumb_ik.finger_jacobian_simple= DQController::jacobianDual(thumb_ik.u, thumb_ik.p, thumb_ik.finger_ee_init, thumb_ik.finger_joint_type, thumb_ik.screwDispalcementArray);\t\n\t\tthumb_ik.finger_jacobian_simple= DQController::jacobianDual_8d(thumb_ik.p.size(), thumb_ik.finger_jacobian_simple);\t\n\n\t\t// std::cout << \"index_finger.finger_ee_current:\" << std::endl;\n\t\t// std::cout << index_finger.finger_ee_current << std::endl;\n\t\t\n\t\t// std::cout << \"jacob_rel_beforeTF:\" << std::endl;\n\t\t// std::cout << index_ik.finger_jacobian_coupled.col(0).transpose() << std::endl;\n\t\t// std::cout << index_ik.finger_jacobian_coupled.col(1).transpose() << std::endl;\n\t\t// std::cout << thumb_ik.finger_jacobian_simple.col(0).transpose() << std::endl;\n\t\t// std::cout << thumb_ik.finger_jacobian_simple.col(1).transpose() << std::endl;\n\n\n\n\t\tjacobian_relative.col(0) = DQoperations::transformLine(index_ik.finger_jacobian_coupled.col(1), DQoperations::classicConjDQ(index_finger.finger_ee_current));\n\t\tjacobian_relative.col(1) = DQoperations::transformLine(index_ik.finger_jacobian_coupled.col(0), DQoperations::classicConjDQ(index_finger.finger_ee_current));\t\t\t\t\n\t\tjacobian_relative.col(2) = DQoperations::transformLine(thumb_ik.finger_jacobian_simple.col(0), DQoperations::classicConjDQ(index_finger.finger_ee_current));\n\t\tjacobian_relative.col(3) = DQoperations::transformLine(thumb_ik.finger_jacobian_simple.col(1), DQoperations::classicConjDQ(index_finger.finger_ee_current));\n\t\tjacobian_relative_position = jacobian_relative.block(0,0,jacobian_relative.rows()/2, jacobian_relative.cols()); \n\t\t// std::cout << \"jacob_rel:\" << std::endl;\n\t\t// std::cout << jacobian_relative.col(0).transpose() << std::endl;\n\t\t// std::cout << jacobian_relative.col(1).transpose() << std::endl;\n\t\t// std::cout << jacobian_relative.col(2).transpose() << std::endl;\n\t\t// std::cout << \"jacobian_relative:\" << std::endl;\n\t\t// std::cout << jacobian_relative << std::endl;\n\n\t\t// std::cout << \"jacobian_relative_position:\" << std::endl;\n\t\t// std::cout << jacobian_relative_position << std::endl;\n\t\t// q_dot= DQController::calculateControlVel(Kp, mu, screw_error, jacobian_relative, 4);\n\n\t\tq_dot= DQController::calculateControlVel(Kp, mu, screw_error_position, jacobian_relative_position, 4);\n\t\n\t\t// std::cout << \"############# q_dot: \" << q_dot << std::endl;\n\t\t// std::cout << \"virtual_finger.finger_jacobian_coupled: \" << virtual_finger.finger_jacobian_coupled << std::endl;\n\t\tq = q + q_dot*dt;\n\t\tindex_ik.proximal_phalanx.alpha_cal = index_ik.q_init(0) - q(1); \n\t\tindex_ik.proximal_phalanx.current_sliderCmd= getSliderFromTheta(index_ik.proximal_phalanx);\n\t\tindex_ik.middle_phalanx.alpha_cal = index_ik.q_init(1) - q(0); \n\t\tindex_ik.middle_phalanx.current_sliderCmd= getSliderFromTheta(index_ik.middle_phalanx);\n\n\t\tthumb_ik.proximal_phalanx.alpha_cal = thumb_ik.q_init(0) + q(2); \n\t\tthumb_ik.proximal_phalanx.current_sliderCmd= getSliderFromTheta(thumb_ik.proximal_phalanx);\n\t\tthumb_ik.middle_phalanx.alpha_cal = thumb_ik.q_init(1) + q(3); \n\t\tthumb_ik.middle_phalanx.current_sliderCmd= getSliderFromTheta(thumb_ik.middle_phalanx);\n\n\n\t\tright_hand_cmds.position[0]= thumb_ik.proximal_phalanx.current_sliderCmd;\n\t\tright_hand_cmds.position[1]= thumb_ik.middle_phalanx.current_sliderCmd;\n\t\tright_hand_cmds.position[2]= index_ik.proximal_phalanx.current_sliderCmd;\n\t\tright_hand_cmds.position[3]= index_ik.middle_phalanx.current_sliderCmd;\n\t\t\n\t\t// right_hand_cmds.position[0]= 0.5;\n\t\t// right_hand_cmds.position[1]= 0.5;\n\t\t// right_hand_cmds.position[2]= 0.5;\n\t\t// right_hand_cmds.position[3]= 0.5;\n\n\t\t// std::cout << \"right_hand_cmds\" << std::endl;\n\t\t// for(int ii = 0; ii<right_hand_cmds.position.size(); ii++)\n\t\t// {\n\t\t// \tstd::cout << right_hand_cmds.position[ii] << std::endl;\n\t\t// }\n\n\t\tdo\n\t\t{\n\t\t\t// sleep_time.sleep();\n\t\t\tright_ar10Hand_pub.publish(right_hand_cmds);\n\t\t\tsleep_time.sleep();\n\t\t}\n\t\twhile (!right_ar10Hand_pub.getNumSubscribers());\n\n\t\tsleep_time.sleep();\n\t\tstd::cout << \"norm_error: \" << norm_error << std::endl;\n\t// Writing to csv :result\n\t\terror_htm = DQoperations::dq2HTM(pose_error);\n\t\tend = ros::Time::now();\n\t\tsecs = (end-begin).toSec();\n\t\t // std::cout << \"secs: \" << secs << std::endl;\n\t\t// result_file << secs << \",\" << current_htm(1,3) << \",\" << current_htm(2,3) << \",\" << norm_error << \",\" << (desired_htm(1,3) - current_htm(1,3)) << \",\" << (desired_htm(2,3) - current_htm(2,3)) << \", \\n\";\n\n\t\tAr10KinematicsLoop();\n\t\tindex_ik = index_finger; \n\t\tthumb_ik = thumb;\n\t\tee_relative = DQoperations::mulDQ(DQoperations::classicConjDQ(index_finger.finger_ee_current), thumb.finger_ee_current);\n\t\tq << -index_ik.q(1), -index_ik.q(0), thumb_ik.q(0), thumb_ik.q(1);\n\t}\n\tindex_finger = index_ik; \n\tthumb = thumb_ik;\t\n\thand_ik_res.jointPosition.clear();\n\thand_ik_res.jointPosition.push_back(index_ik.middle_phalanx.current_sliderCmd);\n\thand_ik_res.jointPosition.push_back(index_ik.proximal_phalanx.current_sliderCmd);\n\thand_ik_res.jointPosition.push_back(thumb_ik.proximal_phalanx.current_sliderCmd);\n\thand_ik_res.jointPosition.push_back(thumb_ik.middle_phalanx.current_sliderCmd);\n\treturn true;\n}\n\nbool AR10Kinematics::sendJointCmds_AR10(std::vector<double> jointCmds, std::string fingerName)\n{\n\tright_hand_cmds.name.resize(2);\n\tright_hand_cmds.position.resize(2);\n\tfinger_params\tfinger_ik;\n\t// std::cout << \"right_hand_cmds: \" << std::endl;\n\tif(!fingerName.compare(\"index\"))\n\t{\n\t\tright_hand_cmds.name[0]= \"servo8\";\n\t\tright_hand_cmds.name[1]= \"servo9\";\n\t\t// std::cout << right_hand_cmds.position[0] << std::endl;\n\t\t// std::cout << right_hand_cmds.position[1] << std::endl;\n\t\tfinger_ik = index_finger;\n\t}\t\n\telse if(!fingerName.compare(\"thumb\"))\n\t{\n\t\tright_hand_cmds.name[0]= \"servo0\";\n\t\tright_hand_cmds.name[1]= \"servo1\";\n\t\tfinger_ik = thumb;\n\t}\n\telse return 0;\n\t// right_hand_cmds.position = jointCmds;\n\tstd::cout << \"jointCmds(sendJointCmds_AR10): \" << jointCmds[0] << jointCmds[1] << std::endl;\n\tfinger_ik.proximal_phalanx.alpha_cal = finger_ik.q_init(0) + jointCmds[0]; \n\tfinger_ik.proximal_phalanx.current_sliderCmd= getSliderFromTheta(finger_ik.proximal_phalanx);\n\tfinger_ik.middle_phalanx.alpha_cal = finger_ik.q_init(1) + jointCmds[1]; \n\tfinger_ik.middle_phalanx.current_sliderCmd= getSliderFromTheta(finger_ik.middle_phalanx);\n\n\tright_hand_cmds.position[0]= finger_ik.proximal_phalanx.current_sliderCmd;\n\tright_hand_cmds.position[1]= finger_ik.middle_phalanx.current_sliderCmd;\n\n\n\tros::WallDuration sleep_time(0.1);\n\tdo\n\t{\n\t\t// sleep_time.sleep();\n\t\tright_ar10Hand_pub.publish(right_hand_cmds);\n\t\tsleep_time.sleep();\n\t}\n\twhile (!right_ar10Hand_pub.getNumSubscribers());\n\n\tif(!fingerName.compare(\"index\"))\n\t{\n\t\tindex_finger = finger_ik;\n\t}\t\n\telse if(!fingerName.compare(\"thumb\"))\n\t{\n\t\tthumb = finger_ik;\n\t}\n\tstd::cout << \"return from sendJointCmds_AR10: \" << std::endl; \n\treturn 1;\n}\n\nbool AR10Kinematics::computeHandIKCallback(dq_robotics::IkHand::Request& hand_ik_req, \n\t\t\t\t\t\t\t\t\tdq_robotics::IkHand::Response& hand_ik_res)\n{\t\n\tif(hand_ik_req.finger!=4 && hand_ik_req.finger!=5 && hand_ik_req.finger!=0)\n\t\treturn 0;\n\tif(hand_ik_req.finger==0)\n\t{\n\t\treturn ik_relative(hand_ik_req, hand_ik_res);\n\t}\n\tfinger_params\tfinger_ik;\n\tright_hand_cmds.position.resize(2);\n\tright_hand_cmds.name.resize(2);\n\n\n\tif(hand_ik_req.finger == 4)\n\t{\n\t\tright_hand_cmds.name[0]= \"servo8\";\n\t\tright_hand_cmds.name[1]= \"servo9\";\n\t\tfinger_ik = index_finger;\t\t\n\t}\t\n\n\tif(hand_ik_req.finger == 5)\n\t{\n\t\tright_hand_cmds.name[0]= \"servo0\";\n\t\tright_hand_cmds.name[1]= \"servo1\";\n\t\tfinger_ik = thumb;\n\t}\t\t\n\t//Controller params\n\tdouble norm_error=1;\n\t// double dt=0.1, Kp=0.5, mu=0.001;\n\t// slider_cmd_tolerance= 0.1;\n\t//update the finger\n// std::cout << \"hello _1\" << std::endl;\t\n\tfinger_ik.slider_position_output.clear();\n\tgetSliderPosition(finger_ik);\n// std::cout << \"hello _2\" << std::endl;\t\t\n\tcomputeJointRotation(finger_ik);\n\tfkmFinger(finger_ik)\t;\t\n// std::cout << \"hello _3\" << std::endl;\t\n\t//get request\n\tMatrix<double,8,1> desiredPose;\n\tDQoperations::doubleToDQ(desiredPose, hand_ik_req.desiredPose);\n\n // controller\n\n\tRowVectorXd q, q_dot, screw_error;\n\tq.resize(2);\n\tq_dot.resize(2);\n\tq << finger_ik.q(0), finger_ik.q(1);\n\n\tstd::vector<Matrix<double,8,1> > screwDispalcementArray;\n\n\tstd::cout << \"result_file_name: \" << path << std::endl;\n\tstd::ofstream result_file(path, std::ios::app);\n\t// result_file.open(result_file_name);\n\tMatrix4d error_htm, current_htm, desired_htm;\n\tcurrent_htm =DQoperations::dq2HTM(finger_ik.finger_ee_current);\n\tdesired_htm =DQoperations::dq2HTM(desiredPose);\n if(result_file.is_open())\n {\n \tstd::cout << \"file is open\" << std::endl;\n }\n\t\n\n\tresult_file << \"time\" << \",\" << \"x_current\" << \",\" << \"y_current\" << \",\" << \"norm_error\" << \",\" << \"error_x\" << \",\" << \"error_y\" << \", \\n\";\n\tMatrix<double,8,1> pose_error;\t\n\tros::Time end = ros::Time::now(), begin = ros::Time::now();\n\tdouble secs =0;\n\t\n\tros::WallDuration sleep_time(0.5);\n\twhile(secs<60)\n\t{\n\t\tcurrent_htm =DQoperations::dq2HTM(finger_ik.finger_ee_current);\n\t\tpose_error =DQoperations::mulDQ(finger_ik.finger_ee_current, DQoperations::classicConjDQ(desiredPose));\t\t\n\t\tscrew_error= DQController::getScrewError_8d(finger_ik.finger_ee_current, desiredPose);\n\t\tnorm_error=screw_error.norm();\n\t\tif(!finger_ik.is_thumb)\n\t\t{\n\t\t\tgetJacobianCoupled(finger_ik);\n\t\t\tq_dot= DQController::calculateControlVel(Kp, mu, screw_error, finger_ik.finger_jacobian_coupled, joint_size_coupled);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfinger_ik.finger_jacobian_simple= DQController::jacobianDual(finger_ik.u, finger_ik.p, finger_ik.finger_ee_init, finger_ik.finger_joint_type, finger_ik.screwDispalcementArray);\t\n\t\t\tfinger_ik.finger_jacobian_simple= DQController::jacobianDual_8d(finger_ik.p.size(), finger_ik.finger_jacobian_simple);\t\n\t\t\tq_dot= DQController::calculateControlVel(Kp, mu, screw_error, finger_ik.finger_jacobian_simple, joint_size_coupled);\t\t\n\t\t}\t\t\n\t\n\t\t// std::cout << \"q_dot: \" << q_dot << std::endl;\n\t\t// std::cout << \"virtual_finger.finger_jacobian_coupled: \" << virtual_finger.finger_jacobian_coupled << std::endl;\n\t\tq = q + q_dot;\n\t\tfinger_ik.proximal_phalanx.alpha_cal = finger_ik.q_init(0) + q(0); \n\t\tfinger_ik.proximal_phalanx.current_sliderCmd= getSliderFromTheta(finger_ik.proximal_phalanx);\n\t\tfinger_ik.middle_phalanx.alpha_cal = finger_ik.q_init(1) + q(1); \n\t\tfinger_ik.middle_phalanx.current_sliderCmd= getSliderFromTheta(finger_ik.middle_phalanx);\n\n\t\tright_hand_cmds.position[0]= finger_ik.proximal_phalanx.current_sliderCmd;\n\t\tright_hand_cmds.position[1]= finger_ik.middle_phalanx.current_sliderCmd;\n\n\t\tdo\n\t\t{\n\t\t\t// sleep_time.sleep();\n\t\t\tright_ar10Hand_pub.publish(right_hand_cmds);\n\t\t\tsleep_time.sleep();\n\t\t}\n\t\twhile (!right_ar10Hand_pub.getNumSubscribers());\n\n\t\tsleep_time.sleep();\n\t\tstd::cout << \"norm_error: \" << norm_error << std::endl;\n\t// Writing to csv :result\n\t\terror_htm = DQoperations::dq2HTM(pose_error);\n\t\tend = ros::Time::now();\n\t\tsecs = (end-begin).toSec();\n\t\t // std::cout << \"secs: \" << secs << std::endl;\n\t\tresult_file << secs << \",\" << current_htm(1,3) << \",\" << current_htm(2,3) << \",\" << norm_error << \",\" << (desired_htm(1,3) - current_htm(1,3)) << \",\" << (desired_htm(2,3) - current_htm(2,3)) << \", \\n\";\n\n\t\tAr10KinematicsLoop_finger(finger_ik);\n\t}\n\n\tresult_file.close();\n\t// if(virtual_finger.proximal_phalanx.current_sliderCmd < virtual_finger.proximal_phalanx.init_sliderCmd)\n\t// \tvirtual_finger.proximal_phalanx.init_sliderCmd;\n\t// if(virtual_finger.middle_phalanx.current_sliderCmd < virtual_finger.middle_phalanx.init_sliderCmd)\n\t// \tvirtual_finger.middle_phalanx.init_sliderCmd;\t\n\thand_ik_res.jointPosition.clear();\n\thand_ik_res.jointPosition.push_back(finger_ik.proximal_phalanx.current_sliderCmd);\n\thand_ik_res.jointPosition.push_back(finger_ik.middle_phalanx.current_sliderCmd);\n\t\n\tif(hand_ik_req.finger == 4)\n\t{\n\t\tindex_finger = finger_ik;\t\t\n\t}\t\n\n\tif(hand_ik_req.finger == 5)\n\t{\n\t\tthumb = finger_ik;\n\t}\t\t\n\t// command the sliders\n\t// std::cout << \"q_result: \" << q << std::endl;\n\treturn true;\n}\n\n\nstd::vector<int> AR10Kinematics::getSlidersList(std::vector<std::string> joint_names)\n{\n\tstd::vector<int> joint_order;\n\tjoint_order.clear();\n\t// std::cout << \"joint_names.size(): \" << joint_names.size() << std::endl;\n\t// const sensor_msgs::JointStateConstPtr joint_state = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/ar10_right/joint_states\");\n\tconst sensor_msgs::JointStateConstPtr joint_state = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/ar10/right/servo_positions\");\n\t\n\tfor (int j=0; j < joint_names.size(); j++)\n\t{\n\t\t// std::cout << \"joint_names[\" << j << \"]: \" << joint_names[j] << std::endl;\n\t\tfor (int i=0; i < joint_state->name.size(); i++)\n\t\t{\n\t\t\tif (joint_state->name[i].compare(joint_names[j])==0)\n\t\t {\n\t\t\t joint_order.push_back(i);\n\t\t\t\t// std::cout << \"sliderOrderInjointState: \" << i << std::endl;\t\t\t \t\n\t\t }\n\t\t}\n\t}\n\t// std::cout << \"joint_order[0]: \" << joint_order[0] << std::endl;\n\treturn joint_order;\n}\n\nbool AR10Kinematics::get_thumb_param()\n{\n\n\tthumb.u.resize(2);\n\tthumb.p.resize(2);\n\n\tstd::vector<double> value;\t\n\tvalue.clear();\n\tvalue.resize(3);\n\n\tstd::string paramName=\"thumb_right_u0\";\n\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_u0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.u[0] << value[0], value[1], value[2];\n\n\tparamName=\"thumb_right_u1\";\n\tvalue.clear();\n\tvalue.resize(3);\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_u1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.u[1] << value[0], value[1], value[2];\t\n\n\tparamName=\"thumb_right_p0\";\n\tvalue.clear();\n\tvalue.resize(3);\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_p0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.p[0] << value[0], value[1], value[2];\t\t\n\n\tparamName=\"thumb_right_p1\";\n\tvalue.clear();\n\tvalue.resize(3);\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_p1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.p[1] << value[0], value[1], value[2];\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"thumb_right_frame0\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_frame0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.frame_rot0ToBase_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"thumb_right_frame1\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_frame1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.frame_rot1ToBase_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\t\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"thumb_right_ee_init\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right thumb param: thumb_right_ee_init not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tthumb.finger_ee_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\t\n\n\tthumb.finger_joint_type.clear();\t\t\t\t\t\t\n\tthumb.finger_joint_type.resize(thumb.joint_size);\n\tparamName=\"thumb_right_joint_type\";\n\tif(!ros::param::get(paramName, thumb.finger_joint_type))\n\t{\n\t\tstd::cout << \"right thumb param: finger_joint_type not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tthumb.finger_joint_names.clear();\n\tthumb.finger_joint_names.resize(thumb.joint_size);\n\tparamName=\"thumb_right_joint_names\";\n\tif(!ros::param::get(paramName, thumb.finger_joint_names))\n\t{\n\t\tstd::cout << \"thumb_right_joint_names param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n}\n\nvoid AR10Kinematics::init_thumb()\n{\n\t// define parameters for all joints FROM THE SERVO FEEDBACK\t\n\tthumb.joint_size=2;\n\tthumb.is_thumb= true;\n\tdouble final_displacement, final_slider_cmd;\n\n\tthumb.proximal_phalanx.c=1.186*.01;\n\tthumb.proximal_phalanx.b=5.236*.01;\n\tthumb.proximal_phalanx.init_displacement = 4.246*.01;\n\tfinal_displacement= 5.960*.01;\n\tthumb.proximal_phalanx.total_displacement=(final_displacement - thumb.proximal_phalanx.init_displacement);\n\tfinal_slider_cmd = 2.170;\n\tthumb.proximal_phalanx.init_sliderCmd=0.896;\t\n\tthumb.proximal_phalanx.total_sliderCmd=final_slider_cmd - thumb.proximal_phalanx.init_sliderCmd; \n\n\tthumb.middle_phalanx.c=1.2*.01;\n\tthumb.middle_phalanx.b=4.94*.01;\n\tthumb.middle_phalanx.init_displacement = 4.148*.01;\n\tfinal_displacement= 5.120*.01;\n\tthumb.middle_phalanx.total_displacement=(final_displacement - thumb.middle_phalanx.init_displacement);\n\tfinal_slider_cmd = 1.394;\n\tthumb.middle_phalanx.init_sliderCmd=0.303;\t\n\tthumb.middle_phalanx.total_sliderCmd=final_slider_cmd - thumb.middle_phalanx.init_sliderCmd; \t\n\t\n\tthumb.finger_frame_names.resize(thumb.joint_size+1);\n\tthumb.finger_frame_names[0]=\"ar10_right_mod/thumb/middle_phalanx\";\n\tthumb.finger_frame_names[1]=\"ar10_right_mod/thumb/distal_phalanx\";\n\tthumb.finger_frame_names[2]=\"ar10_right_mod/thumb/thumbTip\";\n\t\n\tif(!get_thumb_param())\n\t\tROS_INFO(\"Thumb params not found.\");\n\tthumb.dq_frames_stack_current.clear();\n\tthumb.dq_frames_stack_init.clear();\n\tthumb.dq_frames_stack_init.push_back(thumb.frame_rot0ToBase_init);\n\tthumb.dq_frames_stack_init.push_back(thumb.frame_rot1ToBase_init);\n\tthumb.dq_frames_stack_init.push_back(thumb.finger_ee_init);\n\tthumb.dq_frames_stack_current = thumb.dq_frames_stack_init; \n\n\tthumb.sliderOrderInjointState=\tgetSlidersList(thumb.finger_joint_names);\n\n\tthumb.q_init.resize(thumb.joint_size);\n\tthumb.q.resize(thumb.joint_size);\n\t\n\tgetThetaFromSlider(thumb.proximal_phalanx);\n\tgetThetaFromSlider(thumb.middle_phalanx);\n\n\tthumb.q_init << thumb.proximal_phalanx.alpha, thumb.middle_phalanx.alpha;\n\tthumb.q = thumb.q_init;\n}\n\nbool AR10Kinematics::get_index_param()\n{\n\tindex_finger.joint_size = 3;\n\tindex_finger.u.resize(3);\n\tindex_finger.p.resize(3);\n\n\tstd::vector<double> value;\t\n\tvalue.clear();\n\tvalue.resize(3);\n\n\tstd::string paramName=\"index_right_u0\";\n\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: thumb_right_u0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.u[0] << value[0], value[1], value[2];\n\t\n\tparamName=\"index_right_u1\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_u1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.u[1] << value[0], value[1], value[2];\n\n\tparamName=\"index_right_u2\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_u2 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.u[2] << value[0], value[1], value[2];\n\n\tparamName=\"index_right_p0\";\n\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: thumb_right_p0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.p[0] << value[0], value[1], value[2];\n\t\n\tparamName=\"index_right_p1\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_p1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.p[1] << value[0], value[1], value[2];\n\n\tparamName=\"index_right_p2\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_p2 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.p[2] << value[0], value[1], value[2];\t\n\n\tindex_finger.q_init.resize(3);\n\tindex_finger.q.resize(3);\n\tparamName=\"index_right_q_init\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_q_init not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.q_init << value[0], value[1], value[2];\n\tindex_finger.q = index_finger.q_init;\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"index_right_frame_0\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_frame_0 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.frame_rot0ToBase_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"index_right_frame_1\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_frame_1 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.frame_rot1ToBase_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"index_right_frame_2\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_frame_2 not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.frame_rot2ToBase_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\t\n\n\tvalue.clear();\n\tvalue.resize(8);\n\tparamName=\"index_right_ee_init\";\n\tif(!ros::param::get(paramName, value))\n\t{\n\t\tstd::cout << \"right index param: index_right_ee_init not found\" << std::endl;\n\t\treturn 0;\n\t}\n\telse\n\t\tindex_finger.finger_ee_init << value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7];\t\t\n\n\n\tindex_finger.finger_joint_type.clear();\t\t\t\t\t\t\n\tindex_finger.finger_joint_type.resize(index_finger.joint_size);\n\tparamName=\"index_right_joint_type\";\n\tif(!ros::param::get(paramName, index_finger.finger_joint_type))\n\t{\n\t\tstd::cout << \"right index param: index_right_joint_type not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tindex_finger.finger_joint_names.clear();\n\tindex_finger.finger_joint_names.resize(2);\n\tparamName=\"index_right_joint_names\";\n\tif(!ros::param::get(paramName, index_finger.finger_joint_names))\n\t{\n\t\tstd::cout << \"right index param: index_right_joint_names param not found\" << std::endl;\n\t\treturn 0;\n\t}\n\t\t// std::cout << \"finger_joint_names[0]: \" << index_finger.finger_joint_names[0] << std::endl;\n\t\t// std::cout << \"finger_joint_names[1]: \" << index_finger.finger_joint_names[1] << std::endl;\n}\nvoid AR10Kinematics::init_index_finger_2()\n{\n\tindex_finger.is_thumb= false;\n\tindex_finger.proximal_phalanx.c=1.3*.01;\n\tindex_finger.proximal_phalanx.b=5.22*.01;\n\tindex_finger.proximal_phalanx.init_displacement=4.2*.01;\n\tdouble final_displacement= 6*.01, final_slider_cmd=1.67;\n\tindex_finger.proximal_phalanx.total_displacement=(final_displacement - index_finger.proximal_phalanx.init_displacement);\n// FROM THE SERVO FEEDBACK\t\n\t// index_finger.proximal_phalanx.total_sliderCmd=1.536;\n \tindex_finger.proximal_phalanx.init_sliderCmd=0.134;\n\tindex_finger.proximal_phalanx.total_sliderCmd= final_slider_cmd - index_finger.proximal_phalanx.init_sliderCmd; \n// FROM GUI COMMAND\t\n\t// index_finger.proximal_phalanx.total_sliderCmd=1.37; \n\t// index_finger.proximal_phalanx.init_sliderCmd=0.2;\t\n\n\tindex_finger.middle_phalanx.c=1.4*.01;\n\tindex_finger.middle_phalanx.b=4.98*.01;\n\tindex_finger.middle_phalanx.init_displacement=4.15*.01;\n\tfinal_displacement= 5.75*.01;\n\tfinal_slider_cmd = 1.604;\n\tindex_finger.middle_phalanx.total_displacement=(final_displacement - index_finger.middle_phalanx.init_displacement);\n\n// FROM THE SERVO FEEDBACK\t\n\t// index_finger.middle_phalanx.total_sliderCmd=1.105; \n\tindex_finger.middle_phalanx.init_sliderCmd = 0.499;\n\tindex_finger.middle_phalanx.total_sliderCmd= final_slider_cmd - index_finger.middle_phalanx.init_sliderCmd;\n// FROM GUI COMMAND\t\n\t// index_finger.middle_phalanx.total_sliderCmd=1.03;\n\t// index_finger.middle_phalanx.init_sliderCmd=0.54;\t\n\n\n\tindex_finger.distal_phalanx.p = 2.97;\n\tindex_finger.distal_phalanx.qq = 3.47;\n\tindex_finger.distal_phalanx.g = 0.84;\n\tindex_finger.distal_phalanx.h = 0.72;\n\tindex_finger.distal_phalanx.theta_init = 3.32939008;\n\tindex_finger.distal_phalanx.theta=index_finger.distal_phalanx.theta_init;\n\n\tif(!get_index_param())\n\t\tROS_INFO(\"index_finger params not found.\");\n\tindex_finger.dq_frames_stack_current.clear();\n\tindex_finger.dq_frames_stack_init.clear();\n\tindex_finger.dq_frames_stack_init.push_back(index_finger.frame_rot0ToBase_init);\n\tindex_finger.dq_frames_stack_init.push_back(index_finger.frame_rot1ToBase_init);\n\tindex_finger.dq_frames_stack_init.push_back(index_finger.frame_rot2ToBase_init);\n\tindex_finger.dq_frames_stack_init.push_back(index_finger.finger_ee_init);\n\tindex_finger.dq_frames_stack_current = index_finger.dq_frames_stack_init; \n\n\tindex_finger.sliderOrderInjointState=\tgetSlidersList(index_finger.finger_joint_names);\n\n\tindex_finger.finger_frame_names.clear();\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_0\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_1\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_2\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/fingerTip\");\n}\n\nvoid AR10Kinematics::init_index_finger()\n{\n\tindex_finger.is_thumb= false;\n\tindex_finger.proximal_phalanx.c=1.3*.01;\n\tindex_finger.proximal_phalanx.b=5.22*.01;\n\tindex_finger.proximal_phalanx.init_displacement=4.2*.01;\n\tdouble final_displacement= 6*.01, final_slider_cmd=1.67;\n\tindex_finger.proximal_phalanx.total_displacement=(final_displacement - index_finger.proximal_phalanx.init_displacement);\n// FROM THE SERVO FEEDBACK\t\n\t// index_finger.proximal_phalanx.total_sliderCmd=1.536;\n \tindex_finger.proximal_phalanx.init_sliderCmd=0.134;\n\tindex_finger.proximal_phalanx.total_sliderCmd= final_slider_cmd - index_finger.proximal_phalanx.init_sliderCmd; \n// FROM GUI COMMAND\t\n\t// index_finger.proximal_phalanx.total_sliderCmd=1.37; \n\t// index_finger.proximal_phalanx.init_sliderCmd=0.2;\t\n\n\tindex_finger.middle_phalanx.c=1.4*.01;\n\tindex_finger.middle_phalanx.b=4.98*.01;\n\tindex_finger.middle_phalanx.init_displacement=4.15*.01;\n\tfinal_displacement= 5.75*.01;\n\tfinal_slider_cmd = 1.604;\n\tindex_finger.middle_phalanx.total_displacement=(final_displacement - index_finger.middle_phalanx.init_displacement);\n\n// FROM THE SERVO FEEDBACK\t\n\t// index_finger.middle_phalanx.total_sliderCmd=1.105; \n\tindex_finger.middle_phalanx.init_sliderCmd = 0.499;\n\tindex_finger.middle_phalanx.total_sliderCmd= final_slider_cmd - index_finger.middle_phalanx.init_sliderCmd;\n// FROM GUI COMMAND\t\n\t// index_finger.middle_phalanx.total_sliderCmd=1.03;\n\t// index_finger.middle_phalanx.init_sliderCmd=0.54;\t\n\n\n\tindex_finger.distal_phalanx.p = 2.97;\n\tindex_finger.distal_phalanx.qq = 3.47;\n\tindex_finger.distal_phalanx.g = 0.84;\n\tindex_finger.distal_phalanx.h = 0.72;\n\tindex_finger.distal_phalanx.theta_init = 3.32939008;\n\tindex_finger.distal_phalanx.theta=index_finger.distal_phalanx.theta_init;\n\n\tindex_finger.q_init.resize(3);\n\tindex_finger.q.resize(3);\n\tindex_finger.u.resize(3);\n\tindex_finger.p.resize(3);\n\n\tindex_finger.q_init << 0.59044489, 0.81437063, 4.1102504;\n\n\tindex_finger.q=index_finger.q_init;\n\t\n\tMatrix4d tf_handBase_circSupport=Matrix4d::Identity(), tf_indexPlanarBase_handBase, tf_h2_h1=Matrix4d::Identity(), tf_h3_h2=Matrix4d::Identity(), tf_h4_h3=Matrix4d::Identity(), tf_h5_h4=Matrix4d::Identity();\n\t\n\ttf_handBase_circSupport(2,3)=-0.0021;\n\n\ttf_indexPlanarBase_handBase << 0, 0, -1, -0.0565,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-1, 0, 0, 0.014,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, 1, 0, 0.08,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, 0, 0, 1;\n\t\n\ttf_h2_h1(0,3) = 0.68*.01;\n\ttf_h2_h1(1,3) = 5.51*.01;\n\ttf_h2_h1(2,3) = 0*.01;\n\n\ttf_h3_h2(0,3) = -0.92*.01;\n\ttf_h3_h2(1,3) = 4.42*.01;\n\ttf_h3_h2(2,3) = 0*.01;\n\n\ttf_h4_h3(0,3) = -1.14*.01;\n\ttf_h4_h3(1,3) = 2.75*.01;\n\ttf_h4_h3(2,3) = 0*.01;\n\n\ttf_h5_h4(0,3) = -2.15*.01;\n\ttf_h5_h4(1,3) = 2.03*.01;\n\ttf_h5_h4(2,3) = -1*.01;\n\n\t// Matrix4d tf_indexPlanarBase_circSupport = tf_handBase_circSupport*tf_indexPlanarBase_handBase;\n\tMatrix4d tf_indexH2_handBase = tf_indexPlanarBase_handBase*tf_h2_h1;\n\t// std::cout << \"frame_rot0ToBase_init:\" << std::endl;\n\t// std::cout << tf_indexH2_handBase << std::endl;\n\tindex_finger.frame_rot0ToBase_init=DQoperations::htm2DQ(tf_indexH2_handBase);\n\n\tMatrix4d tf_indexH3_handBase = tf_indexH2_handBase*tf_h3_h2;\n\t// std::cout << \"frame_rot1ToBase_init:\" << std::endl;\n\t// std::cout << tf_indexH3_handBase << std::endl;\n\tindex_finger.frame_rot1ToBase_init=DQoperations::htm2DQ(tf_indexH3_handBase);\t\n\n\n\tMatrix4d tf_indexH4_handBase = tf_indexH3_handBase*tf_h4_h3;\n\t// std::cout << \"frame_rot2ToBase_init:\" << std::endl;\n\t// std::cout << tf_indexH4_handBase << std::endl;\t\n\tindex_finger.frame_rot2ToBase_init=DQoperations::htm2DQ(tf_indexH4_handBase);\t\t\n\n\tMatrix4d tf_indexH5_handBase = tf_indexH4_handBase*tf_h5_h4;\n\t// std::cout << \"finger_ee_init:\" << std::endl;\n\t// std::cout << tf_indexH5_handBase << std::endl;\n\tindex_finger.finger_ee_init= DQoperations::htm2DQ(tf_indexH5_handBase);\n\n\tindex_finger.finger_joint_type.resize(3);\n\tindex_finger.finger_joint_type[0]=0;\n\tindex_finger.finger_joint_type[1]=0;\n\tindex_finger.finger_joint_type[2]=0;\n\n\tindex_finger.p[0] << tf_indexH2_handBase(0,3), tf_indexH2_handBase(1,3), tf_indexH2_handBase(2,3); \n\tindex_finger.p[1] << tf_indexH3_handBase(0,3), tf_indexH3_handBase(1,3), tf_indexH3_handBase(2,3);\n\tindex_finger.p[2] << tf_indexH4_handBase(0,3), tf_indexH4_handBase(1,3), tf_indexH4_handBase(2,3);\n\n\tindex_finger.u[0] << tf_indexH2_handBase(0,2), tf_indexH2_handBase(1,2), tf_indexH2_handBase(2,2); \n\tindex_finger.u[1] << tf_indexH3_handBase(0,2), tf_indexH3_handBase(1,2), tf_indexH3_handBase(2,2);\n\tindex_finger.u[2] << tf_indexH4_handBase(0,2), tf_indexH4_handBase(1,2), tf_indexH4_handBase(2,2);\n\n\tindex_finger.finger_joint_names.clear();\n\tindex_finger.finger_joint_names.push_back(\"servo8\");\n\tindex_finger.finger_joint_names.push_back(\"servo9\");\n\tindex_finger.sliderOrderInjointState=\tgetSlidersList(index_finger.finger_joint_names);\n\t// std::cout << \"HELLO_sliderOrderInjointState[0]: \" << index_finger.sliderOrderInjointState[0] << std::endl;\n\tindex_finger.finger_frame_names.clear();\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/hand_base\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_base\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_0\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_1\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/planar_rot_2\");\n\tindex_finger.finger_frame_names.push_back(\"ar10_right_mod/indexFinger/fingerTip\");\n\n\tindex_finger.dq_frames_stack_current.clear();\n\tindex_finger.dq_frames_stack_init.clear();\n\tindex_finger.dq_frames_stack_init.push_back(DQoperations::htm2DQ(tf_handBase_circSupport));\n\tindex_finger.dq_frames_stack_init.push_back(DQoperations::htm2DQ(tf_indexPlanarBase_handBase));\n\tindex_finger.dq_frames_stack_init.push_back(DQoperations::htm2DQ(tf_indexH2_handBase));\n\tindex_finger.dq_frames_stack_init.push_back(DQoperations::htm2DQ(tf_indexH3_handBase));\n\tindex_finger.dq_frames_stack_init.push_back(DQoperations::htm2DQ(tf_indexH4_handBase));\n\tindex_finger.dq_frames_stack_init.push_back(index_finger.finger_ee_init);\n\n\tindex_finger.dq_frames_stack_current= index_finger.dq_frames_stack_init;\n}\n\nvoid AR10Kinematics::init_fingers()\n{\n\tif(!getControllerParms())\n\t\tROS_WARN(\"AR10 controller params not found.\");\n\n\tinit_thumb();\n\t// std::cout << \"hello\" << std::endl;\n\tinit_index_finger_2();\n\t// std::cout << \"hello2\" << std::endl;\n}\n\ndouble AR10Kinematics::getSliderFromTheta(slider_params sp)\n{\n\tdouble sliderCmd = sqrt(sp.b*sp.b + sp.c*sp.c - 2*sp.b*sp.c*cos(sp.alpha_cal));\n\tsliderCmd = (sliderCmd - sp.init_displacement)*(sp.total_sliderCmd/sp.total_displacement) + sp.init_sliderCmd;\n\treturn sliderCmd;\n}\n\nvoid AR10Kinematics::getThetaFromSlider(slider_params &sp)\n{\n\tif (sp.current_sliderCmd < sp.init_sliderCmd)\n\t\tsp.current_sliderCmd = sp.init_sliderCmd;\n\n\tdouble current_displacement=(sp.total_displacement/sp.total_sliderCmd)*(sp.current_sliderCmd - sp.init_sliderCmd) + sp.init_displacement;\n\tdouble cosTheta = (sp.c*sp.c + sp.b*sp.b - current_displacement*current_displacement)/(2*sp.b*sp.c);\n\tdouble theta = acos(cosTheta);\n\tsp.alpha=theta;\n}\n\n\nvoid AR10Kinematics::getAlphaFromTheta4Bar(four_bar_params &four_bar)\n{\n\tdouble A = 2*four_bar.p*four_bar.qq*cos(four_bar.theta) - 2*four_bar.g*four_bar.qq;\n\tdouble B = 2*four_bar.p*four_bar.qq*sin(four_bar.theta);\n\tdouble C = four_bar.g*four_bar.g + four_bar.qq*four_bar.qq + four_bar.p*four_bar.p - four_bar.h*four_bar.h - 2*four_bar.p*four_bar.g*cos(four_bar.theta);\n\tfour_bar.psi = atan2(B, A) - acos(C/(sqrt(A*A + B*B)));\n\tfour_bar.psi = (four_bar.psi > 0 ? four_bar.psi : (2*PI + four_bar.psi));\n\n\tfour_bar.alpha = atan2((four_bar.qq*sin(four_bar.psi) - four_bar.p*sin(four_bar.theta)), (four_bar.g + four_bar.qq*cos(four_bar.psi) - four_bar.p*cos(four_bar.theta))) - four_bar.theta;\n\tfour_bar.alpha = (four_bar.alpha > 0 ? four_bar.alpha : (2*PI + four_bar.alpha));\t\n}\n\nvoid AR10Kinematics::getSliderPosition(finger_params &finger)\n{\n\tstd::cout << \"here in getSliderPosition\" << std::endl;\n\t// const sensor_msgs::JointStateConstPtr joint_state = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/ar10_right/joint_states\");\n\tconst sensor_msgs::JointStateConstPtr joint_state = ros::topic::waitForMessage<sensor_msgs::JointState>(\"/ar10/right/servo_positions\");\n\t// std::cout << \"finger.sliderOrderInjointState[0]: \" << finger.sliderOrderInjointState[0] << std::endl;\n\tfinger.proximal_phalanx.current_sliderCmd = joint_state->position[finger.sliderOrderInjointState[0]];\t\t\t\n\t// std::cout << \"finger.proximal_phalanx.current_sliderCmd: \" << finger.proximal_phalanx.current_sliderCmd << std::endl;\n\n\t// std::cout << \"finger.sliderOrderInjointState[1]: \" << finger.sliderOrderInjointState[1] << std::endl;\t\t\n\tfinger.middle_phalanx.current_sliderCmd = joint_state->position[finger.sliderOrderInjointState[1]];\n\t// std::cout << \"finger.middle_phalanx.current_sliderCmd: \" << finger.middle_phalanx.current_sliderCmd << std::endl;\t\t\t\n}\n\nvoid AR10Kinematics::computeJointRotation(finger_params &finger)\n{\n\n\tAR10Kinematics::getThetaFromSlider(finger.proximal_phalanx);\t\n\tfinger.q(0)=finger.proximal_phalanx.alpha - finger.q_init(0);\n\n\tAR10Kinematics::getThetaFromSlider(finger.middle_phalanx);\n\tfinger.q(1)=finger.middle_phalanx.alpha - finger.q_init(1);\n\tif(!finger.is_thumb)\n\t{\n\t\tfinger.distal_phalanx.theta=finger.distal_phalanx.theta_init+finger.q(1);\n\t\tAR10Kinematics::getAlphaFromTheta4Bar(finger.distal_phalanx);\t\n\t\tfinger.q(2)=finger.distal_phalanx.alpha - finger.q_init(2);\n\t\t// std::cout << \"finger.q: \" << finger.q << std::endl;\t\t\t\t\t\n\t}\n\t// else\n\t// \tstd::cout << \"finger.q(1): \" << finger.q(1) << std::endl;\t\t\n}\n\nvoid AR10Kinematics::fkmFinger(finger_params &finger)\n{\n\tfinger.screwDispalcementArray.resize(finger.q.size());\n\tfinger.dq_frames_stack_current.resize(finger.q.size()+1);\n\t// if(finger.is_thumb)\n\t// {\n\t// \tstd::cout << \"finger.u.size(): \" << finger.u.size() << std::endl;\t\t\n\t// \tstd::cout << \"finger.p.size(): \" << finger.p.size() << std::endl;\t\t\n\t// \tstd::cout << \"finger.q.size(): \" << finger.q.size() << std::endl;\t\t\n\t// \tstd::cout << \"finger.finger_joint_type.size(): \" << finger.finger_joint_type.size() << std::endl;\t\t\n\t// }\t\n finger.screwDispalcementArray= DQController::fkmDual(finger.u, finger.p, finger.q /*q is defined as [q1 q2 ...]*/, finger.finger_joint_type);\n\n\tfinger.frame_rot0ToBase_current=finger.screwDispalcementArray[0];\n finger.frame_rot0ToBase_current=DQoperations::mulDQ(finger.frame_rot0ToBase_current, finger.frame_rot0ToBase_init);\n finger.dq_frames_stack_current[0] = finger.frame_rot0ToBase_current;\n\t\n\tfinger.frame_rot1ToBase_current=finger.screwDispalcementArray[1];\n finger.frame_rot1ToBase_current=DQoperations::mulDQ(finger.frame_rot1ToBase_current, finger.frame_rot1ToBase_init);\n\tfinger.dq_frames_stack_current[1] = finger.frame_rot1ToBase_current;\n\n\tif(!finger.is_thumb)\n\t{\n\t\t// std::cout << \"finger.screwDispalcementArray[2]:\" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(finger.screwDispalcementArray[2]) << std::endl;\n\t\t\n\t\tfinger.frame_rot2ToBase_current=finger.screwDispalcementArray[2];\n\t finger.frame_rot2ToBase_current=DQoperations::mulDQ(finger.frame_rot2ToBase_current, finger.frame_rot2ToBase_init);\n\t\tfinger.dq_frames_stack_current[2]= finger.frame_rot2ToBase_current; \n\n\t finger.finger_ee_current=finger.screwDispalcementArray[2];\n\t finger.finger_ee_current=DQoperations::mulDQ(finger.finger_ee_current, finger.finger_ee_init);\n\t\tfinger.dq_frames_stack_current[3]= finger.finger_ee_current; \t\t\n\t}\t\n\telse\n\t{\n\t finger.finger_ee_current=finger.screwDispalcementArray[1];\n\t finger.finger_ee_current=DQoperations::mulDQ(finger.finger_ee_current, finger.finger_ee_init);\n\t finger.dq_frames_stack_current[2] = finger.finger_ee_current;\n\t}\n\n\t// std::cout << \"ee_dq\" << std::endl;\n\t// std::cout << finger.finger_ee_current.transpose() << std::endl;\n}\n\n\nvoid AR10Kinematics::Ar10KinematicsLoop_finger(finger_params &finger)\n{\n\tros::Rate r(10); \t\n\n\tstatic_transformStamped_array.clear();\n\tgetSliderPosition(finger);\n\tcomputeJointRotation(finger);\n\tfkmFinger(finger)\t;\n\tpublishFramesAsTf(finger, static_transformStamped_array);\t\n\n\tstatic_broadcaster.sendTransform(static_transformStamped_array);\n ros::spinOnce();\n r.sleep();\n}\n\nbool AR10Kinematics::updateFingerVariables(std::string finger_name)\n{\n\t// std::cout << \"Here 16\" << std::endl;\n\tAr10KinematicsLoop();\n\t// std::cout << \"Here 17\" << std::endl;\n\tif(!finger_name.compare(\"index_right\"))\n\t{\n\t\t// std::cout << \"Here 18\" << std::endl;\n\t\t// std::cout << \"ar10_here_0\" << std::endl;\n\t\tgetJacobianCoupled(index_finger);\n\t\treturn 1;\n\t}\n\telse if(!finger_name.compare(\"thumb_right\"))\n\t{\n\t\t\t// std::cout << \"ar10_here_2\" << std::endl;\n\t\tthumb.finger_jacobian_simple= DQController::jacobianDual(thumb.u, thumb.p, thumb.finger_ee_init, thumb.finger_joint_type, thumb.screwDispalcementArray);\n\t\tthumb.finger_jacobian_simple= DQController::jacobianDual_8d(thumb.p.size(), thumb.finger_jacobian_simple);\n\t\treturn 1;\t\n\t}\n\telse return 0;\n}\n\nbool AR10Kinematics::importHandState(std::string finger_name, Matrix<double,8,1>& pe_init, Matrix<double,8,1>& pe_now, MatrixXd& jacobian, RowVectorXd& q, RowVectorXd& q_init)\n{\n\tif(!finger_name.compare(\"index_right\"))\n\t{\n\t\tpe_init = index_finger.finger_ee_init;\n\t\tpe_now = index_finger.finger_ee_current;\n\t\tq = index_finger.q;\n\t\tq_init = index_finger.q_init;\n\t\tjacobian = index_finger.finger_jacobian_coupled;\n\t\treturn 1;\t\n\t}\n\tif(!finger_name.compare(\"thumb_right\"))\n\t{\n\t\tpe_init = thumb.finger_ee_init;\n\t\tpe_now = thumb.finger_ee_current;\n\t\tq = thumb.q;\n\t\tq_init = thumb.q_init;\n\t\tjacobian = thumb.finger_jacobian_simple;\n\t\treturn 1;\t\n\t}\n\telse return 0;\n}\n\nvoid AR10Kinematics::Ar10KinematicsLoop()\n{\n\n\tAr10KinematicsLoop_finger(index_finger);\n\tAr10KinematicsLoop_finger(thumb);\n\n\n\t// static_transformStamped_array.clear();\t\n\t// getSliderPosition(thumb);\n\t// computeJointRotation(thumb);\n\t// fkmFinger(thumb);\n\t// publishFramesAsTf(thumb, static_transformStamped_array);\n\n\t// static_broadcaster.sendTransform(static_transformStamped_array);\n // ros::spinOnce();\n // r.sleep(); \n}\n\n\nvoid AR10Kinematics::publishFramesAsTf(finger_params &finger, std::vector<geometry_msgs::TransformStamped> &static_transformStamped_array)\n{\n\t\n\tstatic_transformStamped_array.push_back(hand_base_static_transformStamped);\t\n\n\n\t// static_transformStamped_array.clear();\n\tgeometry_msgs::TransformStamped static_transformStamped;\n\tMatrix4d mat=Matrix4d::Identity();\n\t///////////////////////////////////////////////////////////////////////////////////////////////////\n\t//Make an isolated transform for hand_base wrt circuit_support\n\t\n\n\t///////////////////////////////////////////////////////////////////////////////////////////////////\n static_transformStamped.header.frame_id = \"ar10_right_mod/hand_base\"; \n for(int i=0; i<(finger.finger_frame_names.size()); i++)\n {\n \t// std::cout << \"is_thumb: \" << finger.is_thumb << std::endl;\n \t// std::cout << \"child_frame_id[\" << i << \"]: \" << finger.finger_frame_names[i] << std::endl;\n\t\tstatic_transformStamped.child_frame_id= finger.finger_frame_names[i];\n\t\tmat= DQoperations::dq2HTM(finger.dq_frames_stack_current[i]);\n\t\tstatic_transformStamped.transform.translation.x=mat(0,3);\n\t\tstatic_transformStamped.transform.translation.y=mat(1,3);\n\t\tstatic_transformStamped.transform.translation.z=mat(2,3);\n\t static_transformStamped.transform.rotation.x = finger.dq_frames_stack_current[i](1);\n\t static_transformStamped.transform.rotation.y = finger.dq_frames_stack_current[i](2);\n\t static_transformStamped.transform.rotation.z = finger.dq_frames_stack_current[i](3);\n\t static_transformStamped.transform.rotation.w = finger.dq_frames_stack_current[i](0);\t\t\n\t static_transformStamped_array.push_back(static_transformStamped);\n }\n // std::cout << \"ee_mat:\" << std::endl;\n // std::cout << mat << std::endl; \n\n}\n\nvoid AR10Kinematics::init_AR10IKService()\n{\n\tfinger_ik_service=n.advertiseService(\"/ar10_right/finger_ik_sever\", &AR10Kinematics::computeHandIKCallback, this);\n}\n\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"ar10_kinematics\");\n\tros::NodeHandle nh;\n\tAR10Kinematics* ar10= new AR10Kinematics();\n\tar10->init_AR10Kinematics();\n\tros::Rate loop_rate(100);\n\tar10->init_fingers();\n\tar10->init_AR10IKService();\n\twhile (ros::ok())\n\t{\n\t\tar10->Ar10KinematicsLoop();\n\t\tros::spinOnce();\n\t\tloop_rate.sleep();\n\t}\n\treturn 0;\n}" }, { "alpha_fraction": 0.7098663449287415, "alphanum_fraction": 0.7214335799217224, "avg_line_length": 39.338897705078125, "blob_id": "1345166f3d1c68229029780807eb9dbcc66d2b69", "content_id": "98de1d7d0eff62e7f3986901660abb6aabfe790c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 48326, "license_type": "no_license", "max_line_length": 366, "num_lines": 1198, "path": "/dq_robotics/src/baxter_poseControl_server.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "// #include <dq_robotics/baxter_poseControl_server.h>\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/baxter_poseControl_server.h>\nusing namespace Eigen;\n\n\ntemplate<typename _Matrix_Type_>\n\t_Matrix_Type_ pseudoInverse(const _Matrix_Type_ &a, double epsilon = std::numeric_limits<double>::epsilon())\n\t{\n\t Eigen::JacobiSVD< _Matrix_Type_ > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t double tolerance = epsilon * std::max(a.cols(), a.rows()) *svd.singularValues().array().abs()(0);\n\t return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n\t}\n\n\n\nBaxterPoseControlServer::BaxterPoseControlServer(){}\n\nBaxterPoseControlServer::~BaxterPoseControlServer(){}\n\nvoid BaxterPoseControlServer::resetTime()\n{\n\ttime_now=0;\n\ttime_last=0;\t\n}\n\n\ndq_robotics::BaxterControl::Response BaxterPoseControlServer::rightArmControl(dq_robotics::BaxterControl::Request baxterControl_req)\n{\n\tBaxterPoseControlServer::update_right();\n\tMatrix<double,8,1> desiredAbsPose, desiredAbsVelocity;\n\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose);\n\tDQoperations::doubleToDQ(desiredAbsVelocity, baxterControl_req.desiredAbsVelocity);\n\n\n\tdq_robotics::BaxterControl::Response res;\n\tif (baxterControl_req.useVisualPose_single==true)\n\t\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose_vision);\n\tRowVectorXd q_dot= BaxterPoseControlServer::jointVelocity4velocityControl(Kp, mu, u_right, p_right, pose_now_right, pe_init_right, joint_type_right, desiredAbsPose, desiredAbsVelocity, fkm_matrix_right, norm_error_right);\n\t\n\t// MatrixXd htm_right_current;\n\t// htm_right_current= DQoperations::dq2HTM(pose_now_right);\n\t// std::cout << \"htm_right_current: \" << htm_right_current << std::endl;\n\n\t// MatrixXd htm_right_desired;\n\t// htm_right_desired= DQoperations::dq2HTM(desiredAbsPose);\n\t// std::cout << \"htm_right_desired: \" << htm_right_desired << std::endl;\n\tstd::vector<double> jointCmds;\n\tif (baxterControl_req.velocity_control==true)\n\t{\n\t\tq_dot=DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_right);\t\t\n\t\tDQoperations::dqEigenToDQdouble(q_dot, jointCmds);\n\t}\n\telse\n\t{\n\t\tRowVectorXd q(q_dot.size());\n\t\tq=q_right+q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::vector<double> jointPositionCmds;\n\t\tDQoperations::dqEigenToDQdouble(q, jointCmds);\n\t}\n\t// pose_error_abs=DQoperations::mulDQ(pose_now_right, DQoperations::classicConjDQ(desiredAbsPose));\n\tremapJointCmds4RightArm(jointCmds);\n\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 1, sleepTimeout, baxterControl_req.velocity_control);\n\t\n\n\ttime_last=current_time.toSec();\n\tBaxterPoseControlServer::update_manipulator();\n\tBaxterPoseControlServer::update_right();\n\ttime_now=current_time.toSec();\n\n\tres.timeNow= time_now;\n\tres.timeLast=time_last;\n\tres.timeStamp=current_time;\n\tres.currentAbsPose = DQoperations::DQToDouble(pose_now_right);\n\tres.normError=norm_error_right;\n\treturn res;\n}\n\nvoid BaxterPoseControlServer::sendBaxterVelocityCmds(std::string hand, std::vector<double> jointCmds)\n{\n\tbool velocity_control =1; \n\tif (!hand.compare(\"right\"))\n\t{\n\t\tremapJointCmds4RightArm(jointCmds);\n\t\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 1, sleepTimeout, velocity_control);\n\t}\n\telse if(!hand.compare(\"combined\"))\n\t{\n\t\tstd::vector<double> jointCmds_new ;\n\t\tfor (int i=0; i<14; i++)\n\t\t{\n\t\t\tjointCmds_new.push_back(jointCmds[i]);\n\t\t}\n\t\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds_new, 3, sleepTimeout, velocity_control);\n\t}\n}\n\nvoid BaxterPoseControlServer::sendBaxterJointCmds(std::string hand, std::vector<double> jointCmds, bool velocity_control)\n{\n\t// bool velocity_control =1; \n\tif (!hand.compare(\"right\"))\n\t{\n\t\tremapJointCmds4RightArm(jointCmds);\n\t\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 1, sleepTimeout, velocity_control);\n\t}\n\telse if(!hand.compare(\"combined\"))\n\t{\n\t\tstd::vector<double> jointCmds_new ;\n\t\tfor (int i=0; i<14; i++)\n\t\t{\n\t\t\tjointCmds_new.push_back(jointCmds[i]);\n\t\t}\n\t\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds_new, 3, sleepTimeout, velocity_control);\n\t}\n}\n\ndq_robotics::BaxterControl::Response BaxterPoseControlServer::leftArmControl(dq_robotics::BaxterControl::Request baxterControl_req)\n{\n\tBaxterPoseControlServer::update_left();\t\n\tMatrix<double,8,1> desiredAbsPose, desiredAbsVelocity;\n\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose);\n\tDQoperations::doubleToDQ(desiredAbsVelocity, baxterControl_req.desiredAbsVelocity);\n \n\tdq_robotics::BaxterControl::Response res;\n\n\tif (baxterControl_req.useVisualPose_single==true)\n\t\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose_vision);\n\tRowVectorXd q_dot= BaxterPoseControlServer::jointVelocity4velocityControl(Kp, mu, u_left, p_left, pose_now_left, pe_init_left, joint_type_left, desiredAbsPose, desiredAbsVelocity, fkm_matrix_left, norm_error_left);\n\n\tstd::vector<double> jointCmds;\n\tif (baxterControl_req.velocity_control==true)\n\t{\n\t\tq_dot=DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_left);\t\t\n\t\tDQoperations::dqEigenToDQdouble(q_dot, jointCmds);\n\t}\n\telse\n\t{\n\t\tRowVectorXd q(q_dot.size());\n\t\tq=q_left+q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::vector<double> jointPositionCmds;\n\t\tDQoperations::dqEigenToDQdouble(q, jointCmds);\n\t}\n\t\n\tremapJointCmds4LeftArm(jointCmds);\n\t\n\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 2, sleepTimeout, baxterControl_req.velocity_control);\n\t\n\n\ttime_last=current_time.toSec();\n\tBaxterPoseControlServer::update_manipulator();\n\tBaxterPoseControlServer::update_left();\n\ttime_now=current_time.toSec();\n\n\tres.timeNow= time_now;\n\tres.timeLast=time_last;\n\tres.timeStamp=current_time;\n\tres.currentAbsPose = DQoperations::DQToDouble(pose_now_left);\n\tres.normError=norm_error_left;\n\treturn res;\n}\n\ndq_robotics::BaxterControl::Response BaxterPoseControlServer::relativeArmControl(dq_robotics::BaxterControl::Request baxterControl_req)\n{\n\tROS_INFO (\"Are we in relative!\");\n\tBaxterPoseControlServer::update_relative();\t\n\tMatrix<double,8,1> desiredRelPose, desiredRelVelocity;\n\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose);\n\tDQoperations::doubleToDQ(desiredRelVelocity, baxterControl_req.desiredRelVelocity);\n \n\tdq_robotics::BaxterControl::Response res;\n\tif (baxterControl_req.useVisualPose_relative==true)\n\t\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose_vision);\n\tRowVectorXd q_dot= BaxterPoseControlServer::jointVelocity4velocityControl(Kp, mu, u_relative, p_relative, pose_now_relative, pe_init_relative, joint_type_relative, desiredRelPose, desiredRelVelocity, fkm_matrix_relative, norm_error_relative);\n\n\tstd::vector<double> jointCmds;\n\tif (baxterControl_req.velocity_control==true)\n\t{\n\t\tq_dot=DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_relative);\t\t\n\t\tDQoperations::dqEigenToDQdouble(q_dot, jointCmds);\n\t}\n\telse\n\t{\n\t\tRowVectorXd q(q_dot.size());\n\t\tq=q_relative+q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::vector<double> jointPositionCmds;\n\t\tDQoperations::dqEigenToDQdouble(q, jointCmds);\n\t}\n\t\n\tremapJointCmds4RelativeArm(jointCmds);\n\t\n\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 3, sleepTimeout, baxterControl_req.velocity_control);\n\t\n\n\ttime_last=current_time.toSec();\n\tBaxterPoseControlServer::update_manipulator();\n\tBaxterPoseControlServer::update_relative();\n\ttime_now=current_time.toSec();\n\n\tres.timeNow= time_now;\n\tres.timeLast=time_last;\n\tres.timeStamp=current_time;\n\tres.currentRelPose = DQoperations::DQToDouble(pose_now_relative);\n\tres.normError=norm_error_relative;\n\treturn res;\t\n}\n\ndq_robotics::BaxterControl::Response BaxterPoseControlServer::rightOrientationRelativeArmControl(dq_robotics::BaxterControl::Request baxterControl_req)\n{\n\t// ROS_INFO (\"Are we in rightRelative!\");\n\tBaxterPoseControlServer::update_rightRelative();\t\n\tMatrix<double,8,1> desiredRelPose, desiredRelVelocity, desiredAbsPose, desiredAbsVelocity;\n\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose);\n\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose);\n\tdesiredAbsPose=DQoperations::classicConjDQ(desiredAbsPose);\n\tDQoperations::doubleToDQ(desiredRelVelocity, baxterControl_req.desiredRelVelocity);\n\tDQoperations::doubleToDQ(desiredAbsVelocity, baxterControl_req.desiredAbsVelocity);\n \n\tdq_robotics::BaxterControl::Response res;\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\tpe_init_rightRelative_relative=pe_init_relative;\n\tpe_init_rightRelative_right=DQoperations::classicConjDQ(pe_init_right);\n\n\tif (baxterControl_req.useVisualPose_relative==true)\n\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose_vision);\n\n\tif (baxterControl_req.useVisualPose_single==true)\n\t{\n\t\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose_vision);\n\t\tdesiredAbsPose= DQoperations::classicConjDQ(desiredAbsPose);\t\t\n\t}\n\n\tpe_init_rightRelative_right=DQoperations::classicConjDQ(pe_init_right);\n\tMatrixXd jacobian_8d_rightRelative_relative, jacobian_8d_rightRelative_right;\n\tjacobian_8d_rightRelative_relative= DQController::jacobianDual(u_rightRelative_relative, p_rightRelative_relative, pe_init_rightRelative_relative, joint_type_rightRelative_relative, fkm_matrix_rightRelative_relative);\t\n\tjacobian_8d_rightRelative_relative= DQController::jacobianDual_8d(joint_size_rightRelative_relative, jacobian_8d_rightRelative_relative);\t\n\n\t// ROS_INFO(\"jacobian_8d_rightRelative_relative: rows: %d, cols: %d\", jacobian_8d_rightRelative_relative.rows(), jacobian_8d_rightRelative_relative.cols());\n\n\tjacobian_8d_rightRelative_right= MatrixXd::Zero(8,joint_size_rightRelative_right);\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjacobian_8d_rightRelative_right.col(i)=jacobian_8d_rightRelative_relative.col(i);\n\t}\n\t// std::cout << \"jacobian_8d: \" << std::endl;\n\t// std::cout << jacobian_8d << std::endl;\n\tRowVectorXd screw_error_rightRelative_relative, screw_error_rightRelative_right; \n\tscrew_error_rightRelative_relative= DQController::getScrewError_8d(pose_now_rightRelative_relative, desiredRelPose);\n\tscrew_error_rightRelative_right= DQController::getScrewError_8d(pose_now_rightRelative_right, desiredAbsPose);\n\n\tnorm_error=(screw_error_rightRelative_relative.norm()+screw_error_rightRelative_right.norm())/2;\n\n\tMatrixXd combined_jacobian_8d= MatrixXd::Zero(12,joint_size_rightRelative_relative);\n\tcombined_jacobian_8d.block(0, 0, jacobian_8d_rightRelative_relative.rows(), jacobian_8d_rightRelative_relative.cols())=jacobian_8d_rightRelative_relative;\n\tcombined_jacobian_8d.block(jacobian_8d_rightRelative_relative.rows(), 0, 4, jacobian_8d_rightRelative_right.cols())=jacobian_8d_rightRelative_right.block(4,0, 4, jacobian_8d_rightRelative_right.cols());\n\n\tRowVectorXd combined_screw_error =RowVectorXd::Zero(screw_error_rightRelative_relative.cols()+4);\n\t// ROS_INFO(\"1\");\n\t// std::cout << \"screw_error_rel.size: \" << screw_error_rel.rows() << \":\" << screw_error_rel.cols() << std::endl; \n\t// std::cout << \"screw_error_right.size: \" << screw_error_right.rows() << \":\" << screw_error_right.cols() << std::endl; \n\tcombined_screw_error << screw_error_rightRelative_relative.row(0), screw_error_rightRelative_right(4), screw_error_rightRelative_right(5), screw_error_rightRelative_right(6), screw_error_rightRelative_right(7);\n\t\n\tRowVectorXd q_dot= DQController::calculateControlVel(Kp, mu, combined_screw_error, combined_jacobian_8d, joint_size_rightRelative_relative);\n\n\tstd::vector<double> jointCmds;\n\tif (baxterControl_req.velocity_control==true)\n\t{\n\t\tq_dot=DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_rightRelative_relative);\t\t\n\t\tDQoperations::dqEigenToDQdouble(q_dot, jointCmds);\n\t}\n\telse\n\t{\n\t\tRowVectorXd q(q_dot.size());\n\t\tq=q_rightRelative_relative+q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tstd::vector<double> jointPositionCmds;\n\t\tDQoperations::dqEigenToDQdouble(q, jointCmds);\n\t}\n\t\n\tremapJointCmds4RelativeArm(jointCmds);\n\t\n\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 5, sleepTimeout, baxterControl_req.velocity_control);\t\n\n\ttime_last=current_time.toSec();\n\tBaxterPoseControlServer::update_manipulator();\n\tBaxterPoseControlServer::update_rightRelative();\n\ttime_now=current_time.toSec();\n\n\tres.timeNow= time_now;\n\tres.timeLast=time_last;\n\tres.timeStamp=current_time;\n\tres.currentRelPose = DQoperations::DQToDouble(pose_now_rightRelative_relative);\n\tres.currentAbsPose = DQoperations::DQToDouble(DQoperations::classicConjDQ(pose_now_rightRelative_right));\n\tres.normError=norm_error;\n\treturn res;\t\n}\n\ndq_robotics::BaxterControl::Response BaxterPoseControlServer::rightRelativeArmControl(dq_robotics::BaxterControl::Request baxterControl_req)\n{\n\t// ROS_INFO (\"Are we in rightRelative!\");\n\tBaxterPoseControlServer::update_rightRelative();\t\n\tMatrix<double,8,1> desiredRelPose, desiredRelVelocity, desiredAbsPose, desiredAbsVelocity;\n\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose);\n\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose);\n\tdesiredAbsPose=DQoperations::classicConjDQ(desiredAbsPose);\n\tDQoperations::doubleToDQ(desiredRelVelocity, baxterControl_req.desiredRelVelocity);\n\tDQoperations::doubleToDQ(desiredAbsVelocity, baxterControl_req.desiredAbsVelocity);\n \n\tdq_robotics::BaxterControl::Response res;\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\tpe_init_rightRelative_relative=pe_init_relative;\n\tpe_init_rightRelative_right=DQoperations::classicConjDQ(pe_init_right);\n\n\tif (baxterControl_req.useVisualPose_relative==true)\n\t\tDQoperations::doubleToDQ(desiredRelPose, baxterControl_req.desiredRelPose_vision);\n\n\tif (baxterControl_req.useVisualPose_single==true)\n\t{\n\t\tDQoperations::doubleToDQ(desiredAbsPose, baxterControl_req.desiredAbsPose_vision);\n\t\tdesiredAbsPose= DQoperations::classicConjDQ(desiredAbsPose);\t\t\n\t}\n\n\tpe_init_rightRelative_right=DQoperations::classicConjDQ(pe_init_right);\n\tMatrixXd jacobian_8d_rightRelative_relative, jacobian_8d_rightRelative_right;\n\tjacobian_8d_rightRelative_relative= DQController::jacobianDual(u_rightRelative_relative, p_rightRelative_relative, pe_init_rightRelative_relative, joint_type_rightRelative_relative, fkm_matrix_rightRelative_relative);\t\n\tjacobian_8d_rightRelative_relative= DQController::jacobianDual_8d(joint_size_rightRelative_relative, jacobian_8d_rightRelative_relative);\t\n\n\t// ROS_INFO(\"jacobian_8d_rightRelative_relative: rows: %d, cols: %d\", jacobian_8d_rightRelative_relative.rows(), jacobian_8d_rightRelative_relative.cols());\n\n\tjacobian_8d_rightRelative_right= MatrixXd::Zero(8,joint_size_rightRelative_right);\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjacobian_8d_rightRelative_right.col(i)=jacobian_8d_rightRelative_relative.col(i);\n\t}\n\t// std::cout << \"jacobian_8d: \" << std::endl;\n\t// std::cout << jacobian_8d << std::endl;\n\tRowVectorXd screw_error_rightRelative_relative, screw_error_rightRelative_right; \n\tscrew_error_rightRelative_relative= DQController::getScrewError_8d(pose_now_rightRelative_relative, desiredRelPose);\n\tscrew_error_rightRelative_right= DQController::getScrewError_8d(pose_now_rightRelative_right, desiredAbsPose);\n\n\tnorm_error=(screw_error_rightRelative_relative.norm()+screw_error_rightRelative_right.norm())/2;\n\n\tMatrixXd combined_jacobian_8d= MatrixXd::Zero(16,joint_size_rightRelative_relative);\n\tcombined_jacobian_8d.block(0, 0, jacobian_8d_rightRelative_relative.rows(), jacobian_8d_rightRelative_relative.cols())=jacobian_8d_rightRelative_relative;\n\tcombined_jacobian_8d.block(jacobian_8d_rightRelative_relative.rows(), 0, jacobian_8d_rightRelative_right.rows(), jacobian_8d_rightRelative_right.cols())=jacobian_8d_rightRelative_right;\n\n\tRowVectorXd combined_screw_error =RowVectorXd::Zero(screw_error_rightRelative_relative.cols()+screw_error_rightRelative_right.cols());\n\t// ROS_INFO(\"1\");\n\t// std::cout << \"screw_error_rel.size: \" << screw_error_rel.rows() << \":\" << screw_error_rel.cols() << std::endl; \n\t// std::cout << \"screw_error_right.size: \" << screw_error_right.rows() << \":\" << screw_error_right.cols() << std::endl; \n\tcombined_screw_error << screw_error_rightRelative_relative.row(0), screw_error_rightRelative_right.row(0);\n\t\n\tRowVectorXd q_dot= DQController::calculateControlVel(Kp, mu, combined_screw_error, combined_jacobian_8d, joint_size_rightRelative_relative);\n\n\tstd::vector<double> jointCmds;\n\tif (baxterControl_req.velocity_control==true)\n\t{\n\t\tq_dot=DQController::normalizeControlVelocity( q_dot, joint_velocity_limit_rightRelative_relative);\t\t\n\t\tDQoperations::dqEigenToDQdouble(q_dot, jointCmds);\n\t}\n\telse\n\t{\n\t\tRowVectorXd q(q_dot.size());\n\t\tq=q_rightRelative_relative+q_dot*timeStep; // HERE YOU CAN USE (time_now-time_last) in place of timeStep\n\t\tDQoperations::dqEigenToDQdouble(q, jointCmds);\n\t}\n\t\n\tremapJointCmds4RelativeArm(jointCmds);\n\t\n\tbaxter->ManipulatorModDQ::sendJointCommandBaxter(jointCmds, 4, sleepTimeout, baxterControl_req.velocity_control);\t\n\t\n\ttime_last=current_time.toSec();\n\tBaxterPoseControlServer::update_manipulator();\n\tBaxterPoseControlServer::update_rightRelative();\n\ttime_now=current_time.toSec();\n\n\tres.timeNow= time_now;\n\tres.timeLast=time_last;\n\tres.timeStamp=current_time;\n\tres.currentRelPose = DQoperations::DQToDouble(pose_now_rightRelative_relative);\n\tres.currentAbsPose = DQoperations::DQToDouble(DQoperations::classicConjDQ(pose_now_rightRelative_right));\n\tres.normError=norm_error;\n\treturn res;\t\n}\n\nvoid BaxterPoseControlServer::remapJointCmds4RightArm(std::vector<double> &jointCmds)\n{\n\tstd::vector<double> jointCmds_new ;\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjointCmds_new.push_back(jointCmds[i]);\n\t}\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjointCmds_new.push_back(0.0);\n\t}\n\tjointCmds.clear();\n\tjointCmds.resize(14);\n\tjointCmds=jointCmds_new;\n}\n\nvoid BaxterPoseControlServer::remapJointCmds4LeftArm(std::vector<double> &jointCmds)\n{\n\tstd::vector<double> jointCmds_new ;\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjointCmds_new.push_back(0.0);\n\t}\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjointCmds_new.push_back(jointCmds[i]);\n\t}\n\tjointCmds.clear();\n\tjointCmds.resize(14);\n\tjointCmds=jointCmds_new;\n}\n\nvoid BaxterPoseControlServer::remapJointCmds4RelativeArm(std::vector<double> &jointCmds)\n{\n\tstd::vector<double> jointCmds_new ;\n\tjointCmds_new.clear();\n\tfor (int i=0; i<14; i++)\n\t{\n\t\tjointCmds_new.push_back(0.0);\n\t}\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tjointCmds_new[i] =-jointCmds[6-i];\t\n\t\tjointCmds_new[i+7]=jointCmds[i+7];\n\t}\n\tjointCmds.clear();\n\tjointCmds.resize(14);\n\tjointCmds=jointCmds_new;\n}\n\nRowVectorXd BaxterPoseControlServer::jointVelocity4velocityControl(double Kp, double mu, std::vector<RowVector3d> u, std::vector<RowVector3d> p, Matrix<double,8,1> pose_now, Matrix<double,8,1> pe_init, std::vector<int> joint_type, Matrix<double,8,1> pose_desired, Matrix<double,8,1> cart_vel_desired, std::vector<Matrix<double,8,1> > fkm_matrix, double& norm_error)\n{\n\t\n\tint joint_size=u.size();\n\t// std::cout << \"fkm_matrix: \" << std::endl;\n\n\t// for (int i=0; i<u.size(); i++)\n\t// {\n\t// \tstd::cout << fkm_matrix[i] << std::endl;\n\t// \tstd::cout << \"u_left[i]: \" << u[i] << std::endl;\n\t// \tstd::cout << \"p_left[i]: \" << p[i] << std::endl;\t\t\n\t// }\n\n// std::cout << \"pose_now: \" << pose_now << std::endl;\n// std::cout << \"pose_desired: \" << pose_desired << std::endl;\n// std::cout << \"pe_init: \" << pe_init << std::endl;\n\tMatrixXd jacobian_8d;\n\tjacobian_8d= DQController::jacobianDual(u, p, pe_init, joint_type, fkm_matrix);\t\n\tjacobian_8d= DQController::jacobianDual_8d(joint_size, jacobian_8d);\n\t// std::cout << \"jacobian_8d: \" << std::endl;\n\t// std::cout << jacobian_8d << std::endl;\n\tRowVectorXd screw_error= DQController::getScrewError_8d(pose_now, pose_desired);\n\n\tnorm_error=screw_error.norm();\n\t// RowVectorXd q_dot= DQController::calculateControlVel_velcityFF(Kp, mu, screw_error, jacobian_8d, joint_size, cart_vel_desired);\n\tRowVectorXd q_dot= DQController::calculateControlVel(Kp, mu, screw_error, jacobian_8d, joint_size);\n\t// std::cout << \"q_dot: \" << q_dot << std::endl;\n\treturn q_dot;\n\n}\n\n\nbool BaxterPoseControlServer::baxterControlServerCallback(dq_robotics::BaxterControl::Request& baxterControl_req, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dq_robotics::BaxterControl::Response& baxterControl_res)\n{\t\n\tBaxterPoseControlServer::update_manipulator();\n\tbool request_manipulator_infoService = baxterControl_req.request_manipulator_infoService;\n\tif(request_manipulator_infoService)\n\t{\n\t\tint infoService_mode=baxterControl_req.infoService_mode;\n\t\tswitch(infoService_mode)\n\t\t{\n\t\t\tcase 1: \n\t\t\t\tupdate_right();\n\t\t\t\tbaxterControl_res.currentAbsPose = DQoperations::DQToDouble(pose_now_right);\n\t\t\t\tbreak;\n\t\t\tcase 2: \n\t\t\t\tupdate_left();\n\t\t\t\tbaxterControl_res.currentAbsPose = DQoperations::DQToDouble(pose_now_left);\t\t\t\n\t\t\t\tbreak;\n\t\t\tcase 3: \n\t\t\t\tupdate_relative();\n\t\t\t\tbaxterControl_res.currentRelPose = DQoperations::DQToDouble(pose_now_relative);\n\t\t\t\tbreak;\n\t\t\tcase 4: \n\t\t\t\tupdate_rightRelative();\n\t\t\t\tbaxterControl_res.currentAbsPose=DQoperations::DQToDouble(DQoperations::classicConjDQ(pose_now_right));\n\t\t\t\tbaxterControl_res.currentRelPose = DQoperations::DQToDouble(pose_now_relative);\n\t\t\t\tbreak;\n\t\t\tcase 5: \n\t\t\t\tupdate_rightRelative();\n\t\t\t\tbaxterControl_res.currentAbsPose=DQoperations::DQToDouble(DQoperations::classicConjDQ(pose_now_right));\n\t\t\t\tbaxterControl_res.currentRelPose = DQoperations::DQToDouble(pose_now_relative);\n\t\t\t\tbreak;\t\t\t\n\t\t\tcase 6: \n\t\t\t\tresetTime();\n\t\t\t\tbreak;\t\t\t\t\t\t\t\n\t\t}\n\t\tbaxterControl_res.timeNow= time_now;\n\t\tbaxterControl_res.timeLast=time_last;\n\t\tbaxterControl_res.timeStamp=current_time;\n\t\treturn 1;\t\n\t}\n\n\tint controllerMode = baxterControl_req.controlMode;\n\tswitch(controllerMode)\n\t{\n\t\tcase 1: baxterControl_res = rightArmControl(baxterControl_req);\n\t\t\tbreak;\n\t\tcase 2: baxterControl_res = leftArmControl(baxterControl_req);\n\t\t\tbreak;\n\t\tcase 3: baxterControl_res = relativeArmControl(baxterControl_req);\n\t\t\tbreak;\n\t\tcase 4: baxterControl_res = rightRelativeArmControl(baxterControl_req);\n\t\t\tbreak;\n\t\tcase 5: baxterControl_res = rightOrientationRelativeArmControl(baxterControl_req);\n\t\t\tbreak;\t\t\t\n\t}\n\treturn 1;\n}\n\nbool BaxterPoseControlServer::initializeController()\n{\n\tif (BaxterPoseControlServer::getControllerParams())\n\t{\n\t\tbaxter= new ManipulatorModDQ();\n\t\tbaxter->ManipulatorModDQ::initialize_baxter();\n\t\tbaxter->ManipulatorModDQ::robotParams(u_baxter, p_baxter, pe_init_left, pe_init_right, joint_high_limit_baxter, joint_low_limit_baxter, velocity_limit_baxter, max_safe_baxter, min_safe_baxter, joint_names_baxter, joint_type_baxter);\n\t\tBaxterPoseControlServer::intializeMode_right();\n\t\tBaxterPoseControlServer::intializeMode_left();\n\t\tBaxterPoseControlServer::intializeMode_relative();\n\t\tBaxterPoseControlServer::intializeMode_rightRelative();\n\t\t// controllerService = rh.advertiseService(\"baxterControlService\", &BaxterPoseControlServer::baxterControlServerCallback, this);\n\t\treturn 1;\n\t}\n\telse return 0;\n}\n\nbool BaxterPoseControlServer::getControllerParams()\n{\n\tdt_total=0;\n\tuse_VM=false;\n\n\tstd::string paramName=\"Kp\";\n\tif(!ros::param::get(paramName, Kp))\n\t{\n\t\tstd::cout << \"controller param Kp not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"Kp_position\";\n\tif(!ros::param::get(paramName, Kp_position))\n\t{\n\t\tstd::cout << \"controller param Kp_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"timeStep\";\n\tif(!ros::param::get(paramName, timeStep))\n\t{\n\t\tstd::cout << \"controller param timeStep not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl\";\n\tif(!ros::param::get(paramName, K_jl))\n\t{\n\t\tstd::cout << \"controller param K_jl not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"K_jl_position\";\n\tif(!ros::param::get(paramName, K_jl_position))\n\t{\n\t\tstd::cout << \"controller param K_jl_position not found\" << std::endl;\n\t\treturn 0;\n\t}\t\n\n\tparamName=\"mu\";\n\tif(!ros::param::get(paramName, mu))\n\t{\n\t\tstd::cout << \"controller param mu not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"use_VM\";\n\tint value;\n\tif(ros::param::get(paramName, value))\n\t{\n\t\tif(value)\n\t\t\tuse_VM=true;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"controller param use_VM not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"dualArm\";\n\tif(ros::param::get(paramName, value))\n\t{\n\t\tif(value)\n\t\t\tdualArm=true;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"controller param dualArm not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\n\tparamName=\"sleepTimeout\";\n\tif(!ros::param::get(paramName, sleepTimeout))\n\t{\n\t\tstd::cout << \"controller param sleepTimeout not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tparamName=\"norm_error_const\";\n\tif(!ros::param::get(paramName, norm_error_const))\n\t{\n\t\tstd::cout << \"controller param norm_error_const not found\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tROS_INFO(\"Controller parameters loaded\");\n\treturn 1;\n}\n\nvoid BaxterPoseControlServer::intializeMode_right()\n{\n\tjoint_size_right=7;\t\n\tu_right.resize(7);\n\tp_right.resize(7);\n\tjoint_velocity_limit_right.resize(7);\n\tjoint_high_limit_right.resize(7);\n\tjoint_low_limit_right.resize(7);\n\tjoint_max_safe_limit_right.resize(7);\n\tjoint_min_safe_limit_right.resize(7);\n\tjoint_names_right.resize(7);\n\tjoint_type_right.resize(7);\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tu_right[i] =u_baxter[i];\t\n\t\tp_right[i] =p_baxter[i];\n\t\tjoint_velocity_limit_right[i] =velocity_limit_baxter[i];\n\t\tjoint_high_limit_right[i] =joint_high_limit_baxter[i];\n\t\tjoint_low_limit_right[i] =joint_low_limit_baxter[i];\n\t\tjoint_max_safe_limit_right[i] =max_safe_baxter[i];\n\t\tjoint_min_safe_limit_right[i] =min_safe_baxter[i];\n\t\tjoint_names_right[i] =joint_names_baxter[i];\n\t\tjoint_type_right[i] =joint_type_baxter[i];\n\t}\n\tfkm_matrix_right.resize(joint_size_right);\n}\n\n\nvoid BaxterPoseControlServer::intializeMode_left()\n{\n\tjoint_size_left=7;\n\tu_left.resize(7);\n\tp_left.resize(7);\n\tjoint_velocity_limit_left.resize(7);\n\tjoint_high_limit_left.resize(7);\n\tjoint_low_limit_left.resize(7);\n\tjoint_max_safe_limit_left.resize(7);\n\tjoint_min_safe_limit_left.resize(7);\n\tjoint_names_left.resize(7);\n\tjoint_type_left.resize(7);\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tu_left[i] =u_baxter[i+7];\t\n\t\tp_left[i] =p_baxter[i+7];\n\t\tjoint_velocity_limit_left[i] =velocity_limit_baxter[i+7];\n\t\tjoint_high_limit_left[i] =joint_high_limit_baxter[i+7];\n\t\tjoint_low_limit_left[i] =joint_low_limit_baxter[i+7];\n\t\tjoint_max_safe_limit_left[i] =max_safe_baxter[i+7];\n\t\tjoint_min_safe_limit_left[i] =min_safe_baxter[i+7];\n\t\tjoint_names_left[i] =joint_names_baxter[i+7];\n\t\tjoint_type_left[i] =joint_type_baxter[i+7];\n\t}\n\tfkm_matrix_left.resize(joint_size_left);\n}\n\n\nvoid BaxterPoseControlServer::intializeMode_relative()\n{\n\tMatrix<double,8,1> transform_base2Right= DQoperations::classicConjDQ(pe_init_right);\n\tpe_init_relative= DQoperations::mulDQ(transform_base2Right, pe_init_left);\n\t// std::cout << \"pe_init_relative:\" << pe_init_relative.transpose() << std::endl;\n\t// MatrixXd htm_relative;\n\t// htm_relative= DQoperations::dq2HTM(pe_init_relative);\n\t// std::cout << \"htm_relative: \" << htm_relative << std::endl;\n\t\n\tjoint_size_relative=14;\n\tu_relative.resize(14);\n\tp_relative.resize(14);\n\tjoint_velocity_limit_relative.resize(14);\n\tjoint_high_limit_relative.resize(14);\n\tjoint_low_limit_relative.resize(14);\n\tjoint_max_safe_limit_relative.resize(14);\n\tjoint_min_safe_limit_relative.resize(14);\n\tjoint_names_relative.resize(14);\n\tjoint_type_relative.resize(14);\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tu_relative[i] =u_baxter[6-i];\t\n\t\tu_relative[i+7] =u_baxter[i+7];\t\n\n\t\tp_relative[i] =p_baxter[6-i];\n\t\tp_relative[i+7] =p_baxter[i+7];\t\n\t\t\n\t\tjoint_velocity_limit_relative[i] =velocity_limit_baxter[6-i];\n\t\tjoint_velocity_limit_relative[i+7] =velocity_limit_baxter[i+7];\n\t\t\n\t\tjoint_high_limit_relative[i] =-joint_low_limit_baxter[6-i];\n\t\tjoint_high_limit_relative[i+7] =joint_high_limit_baxter[i+7];\n\t\t\n\t\tjoint_low_limit_relative[i] =-joint_high_limit_baxter[6-i];\n\t\tjoint_low_limit_relative[i+7] =joint_low_limit_baxter[i+7];\n\t\t\n\t\tjoint_max_safe_limit_relative[i] =-min_safe_baxter[6-i];\n\t\tjoint_max_safe_limit_relative[i+7] =max_safe_baxter[i+7];\n\t\t\n\t\tjoint_min_safe_limit_relative[i] =-max_safe_baxter[6-i];\n\t\tjoint_min_safe_limit_relative[i+7] =min_safe_baxter[i+7];\n\t\t\n\t\tjoint_names_relative[i] =joint_names_baxter[6-i];\n\t\tjoint_names_relative[i+7] =joint_names_baxter[i+7];\n\t\t\n\t\tjoint_type_relative[i] =joint_type_baxter[6-i];\n\t\tjoint_type_relative[i+7] =joint_type_baxter[i+7];\n\n\t}\n\n\n\tfor (int i=0; i<14; i++)\n\t{\n\t\tu_relative[i]= DQoperations::transformLineVector(u_relative[i], transform_base2Right);\n\t\t// std::cout << \"u_relative[\" << i << \"]:\" << u_relative[i] << std::endl;\t\t\n\t\tp_relative[i]= DQoperations::transformPoint(p_relative[i], transform_base2Right);\n\t\t// std::cout << \"p_relative[\" << i << \"]:\" << p_relative[i] << std::endl;\n\t}\t\n\n\tfkm_matrix_relative.resize(joint_size_relative);\n}\n\nvoid BaxterPoseControlServer::intializeMode_rightRelative()\n{\n\tjoint_size_rightRelative_relative=14;\n\tjoint_size_rightRelative_right=7;\n\tpe_init_rightRelative_relative=pe_init_relative;\n\tpe_init_rightRelative_right=DQoperations::classicConjDQ(pe_init_right);\n\n\n\tu_rightRelative_relative.resize(14);\n\tp_rightRelative_relative.resize(14);\t\n\tjoint_velocity_limit_rightRelative_relative.resize(14);\n\tjoint_high_limit_rightRelative_relative.resize(14);\n\tjoint_low_limit_rightRelative_relative.resize(14);\n\tjoint_max_safe_limit_rightRelative_relative.resize(14);\n\tjoint_min_safe_limit_rightRelative_relative.resize(14);\n\tjoint_names_rightRelative_relative.resize(14);\n\tjoint_type_rightRelative_relative.resize(14);\n\n\tu_rightRelative_right.resize(7);\n\tp_rightRelative_right.resize(7);\t\n\tjoint_velocity_limit_rightRelative_right.resize(7);\n\tjoint_high_limit_rightRelative_right.resize(7);\n\tjoint_low_limit_rightRelative_right.resize(7);\n\tjoint_max_safe_limit_rightRelative_right.resize(7);\n\tjoint_min_safe_limit_rightRelative_right.resize(7);\n\tjoint_names_rightRelative_right.resize(7);\n\tjoint_type_rightRelative_right.resize(7);\n\n\tu_rightRelative_relative = u_relative;\n\tp_rightRelative_relative = p_relative;\t\n\tjoint_velocity_limit_rightRelative_relative = joint_velocity_limit_relative;\n\tjoint_high_limit_rightRelative_relative = joint_high_limit_relative;\n\tjoint_low_limit_rightRelative_relative = joint_low_limit_relative;\n\tjoint_max_safe_limit_rightRelative_relative = joint_max_safe_limit_relative;\n\tjoint_min_safe_limit_rightRelative_relative = joint_min_safe_limit_relative;\n\tjoint_names_rightRelative_relative = joint_names_relative;\n\tjoint_type_rightRelative_relative = joint_type_relative;\n\n\tfor (int i=0; i<7; i++)\n\t{\n\t\tu_rightRelative_right[i] = u_relative[i];\n\t\tp_rightRelative_right[i] = p_relative[i];\t\n\t\tjoint_velocity_limit_rightRelative_right[i] = joint_velocity_limit_relative[i];\n\t\tjoint_high_limit_rightRelative_right[i] = joint_high_limit_relative[i];\n\t\tjoint_low_limit_rightRelative_right[i] = joint_low_limit_relative[i];\n\t\tjoint_max_safe_limit_rightRelative_right[i] = joint_max_safe_limit_relative[i];\n\t\tjoint_min_safe_limit_rightRelative_right[i] = joint_min_safe_limit_relative[i];\n\t\tjoint_names_rightRelative_right[i] = joint_names_relative[i];\n\t\tjoint_type_rightRelative_right[i] = joint_type_relative[i];\n\t}\n\tfkm_matrix_rightRelative_relative.resize(joint_size_rightRelative_relative);\n\tfkm_matrix_rightRelative_right.resize(joint_size_rightRelative_right);\n}\n\nvoid BaxterPoseControlServer::update_manipulator()\n{\n\tbaxter->ManipulatorModDQ::getCurrentJointState_baxter();\n\tbaxter->ManipulatorModDQ::currentRobotState(current_time, q_baxter, q_vel_baxter);\n}\n\n// std::vector<Matrix<double,8,1> > DQController::fkmDual(std::vector<RowVector3d> u,std::vector<RowVector3d> p, RowVectorXd q, std::vector<int> joint_type)\n// {\n// \tint joint_size=joint_type.size();\n// // ROS_INFO(\"joint_size=%d\", joint_size);\n// \tRowVectorXd q_dual;\t\n// \tq_dual=RowVectorXd::Zero(joint_size*2);\n// // ROS_INFO(\"11\");\n// \tfor (int j=0; j< joint_size; j++)\n// \t{\n// \t\tif(joint_type[j]==0)\n// \t\t\tq_dual(2*j)=q(j);\n// \t\telse\n// \t\t\tq_dual(2*j+1)=q(j);\n// \t\t// ROS_INFO(\"j=%d\", j);\n// \t}\n// // ROS_INFO(\"00\");\n// \tstd::vector<Matrix<double,8,1> > fkm_current;\n// \tfkm_current.clear();\n// \tfkm_current.resize(joint_size);\n// // ROS_INFO(\"22\");\n// \tfor (int i=0;i<joint_size; i++)\n// \t{\n// \t\tdouble theta_i=q_dual[2*i];\n// \t\tRowVector3d u_i=u[i];\n// \t\tRowVector3d p_i=p[i];\n// \t\tdouble d_i=q_dual[2*i+1];\n// \t\tMatrix<double,8,1> screwDispalcementArray_i;\n// \t\tscrewDispalcementArray_i= DQoperations::screw2DQ(theta_i, u_i, d_i, p_i.cross(u_i));\n// \t\t// std::cout << \"screwDispalcementArray_\" << i << \": \" << screwDispalcementArray_i.transpose() << std::endl;\n// \t\tif (i==0)\n// \t\t\tfkm_current[i]=screwDispalcementArray_i;\n// \t\telse\n// \t\t\tfkm_current[i]=DQoperations::mulDQ(fkm_current[i-1],screwDispalcementArray_i);\n// \t\t// ROS_INFO(\"i=%d\",i);\n// \t\t// std::cout << \"fkm_current_source_\" << i << \": \" << fkm_current[i].transpose() << std::endl;\n// \t}\n\n// \treturn fkm_current;\n// }\n\n\n\nvoid BaxterPoseControlServer::update_rightAcc()\n{\n\t// update_manipulator();\n\tq_right=q_baxter.head(7);\n\tq_vel_right=q_vel_baxter.head(7);\n\tfkm_matrix_right=DQController::fkmDual(u_right, p_right, q_right, joint_type_right);\n\tpose_now_right=DQoperations::mulDQ(fkm_matrix_right[joint_size_right-1], pe_init_right);\n\tjacobian_8d_right= DQController::jacobianDual(u_right, p_right, pe_init_right, joint_type_right, fkm_matrix_right);\t\n\tjacobian_8d_right= DQController::jacobianDual_8d(joint_size_right, jacobian_8d_right);\t\n\n\tjacobian_6d_right = MatrixXd::Zero(6, jacobian_8d_right.cols());\n\tjacobian_6d_right.block(0, 0, 3, jacobian_8d_right.cols()) = jacobian_8d_right.block(5, 0, 3, jacobian_8d_right.cols());\n\tjacobian_6d_right.block(3, 0, 3, jacobian_8d_right.cols()) = jacobian_8d_right.block(1, 0, 3, jacobian_8d_right.cols());\t\n\tlink_velocity_right = DQController::linkVelocites(jacobian_6d_right, q_vel_right);\n\tjacobian_6d_dot_right = DQController::getJacobianDot(link_velocity_right, jacobian_6d_right);\n}\n\nvoid BaxterPoseControlServer::update_right()\n{\n\tq_right=q_baxter.head(7);\n\n\tq_vel_right=q_vel_baxter.head(7);\n\t\t// ROS_INFO(\"3\");\t\n\t// ros::WallTime fkm_time_start = ros::WallTime::now();\n\tfkm_matrix_right=DQController::fkmDual(u_right, p_right, q_right, joint_type_right);\n\t\t// ROS_INFO(\"4\");\n\n\tpose_now_right=DQoperations::mulDQ(fkm_matrix_right[joint_size_right-1], pe_init_right);\n\t// ros::WallTime fkm_time_end = ros::WallTime::now();\n\t// ros::WallDuration fkm_time_dur = fkm_time_end - fkm_time_start;\n\t// std::cout << \"fkm duration_server: \" << fkm_time_dur.toSec() << std::endl;\t\n\t\t\t// ROS_INFO(\"5\");\n\n\t// MatrixXd htm_right;\n\t// htm_right= DQoperations::dq2HTM(pose_now_right);\n\t// std::cout << \"htm_right: \" << htm_right << std::endl;\n} \n\nvoid BaxterPoseControlServer::update_leftAcc()\n{\n\tupdate_manipulator();\n\tq_left=q_baxter.tail(7);\n\tq_vel_left=q_vel_baxter.tail(7);\n\tfkm_matrix_left=DQController::fkmDual(u_left, p_left, q_left, joint_type_left);\n\tpose_now_left=DQoperations::mulDQ(fkm_matrix_left[joint_size_left-1], pe_init_left);\n\tjacobian_8d_left= DQController::jacobianDual(u_left, p_left, pe_init_left, joint_type_left, fkm_matrix_left);\t\n\tjacobian_8d_left= DQController::jacobianDual_8d(joint_size_left, jacobian_8d_left);\t\n\n\tjacobian_6d_left = MatrixXd::Zero(6, jacobian_8d_left.cols());\n\tjacobian_6d_left.block(0, 0, 3, jacobian_8d_left.cols()) = jacobian_8d_left.block(5, 0, 3, jacobian_8d_left.cols());\n\tjacobian_6d_left.block(3, 0, 3, jacobian_8d_left.cols()) = jacobian_8d_left.block(1, 0, 3, jacobian_8d_left.cols());\t\n\tlink_velocity_left = DQController::linkVelocites(jacobian_6d_left, q_vel_left);\n\tjacobian_6d_dot_left = DQController::getJacobianDot(link_velocity_left, jacobian_6d_left);\n}\n\n\nvoid BaxterPoseControlServer::update_left()\n{\n\tq_left=q_baxter.tail(7);\n\tq_vel_left=q_vel_baxter.tail(7);\n\t// std::cout << \"q_left: \" << q_left << std::endl;\n\t// std::cout << \"q_vel_left: \" << q_vel_left << std::endl;\t\n\t// std::vector<Matrix<double,8,1> > fkm_matrix_left;\n\n\tfkm_matrix_left=DQController::fkmDual(u_left, p_left, q_left, joint_type_left);\n\tpose_now_left=DQoperations::mulDQ(fkm_matrix_left[joint_size_left-1], pe_init_left);\n\t// MatrixXd htm_left;\n\t// htm_left= DQoperations::dq2HTM(pose_now_left);\n\t// std::cout << \"htm_left: \" << htm_left << std::endl;\n\n}\n\nvoid BaxterPoseControlServer::update_relative()\n{\n\tRowVectorXd q_temp;\n\n\tq_relative.resize(14);\t\n\tq_temp = q_baxter.head(7);\n\tq_relative << -q_temp.reverse() , q_baxter.tail(7);\n\t// std::cout << \"q_relative: \" << q_relative << std::endl;\n\n\tq_vel_relative.resize(14);\n\tq_temp = q_vel_baxter.head(7);\n\tq_vel_relative << -q_temp.reverse() , q_vel_baxter.tail(7);\n\t// std::cout << \"q_left: \" << q_left << std::endl;\n\t// std::cout << \"q_vel_left: \" << q_vel_left << std::endl;\t\n\t// std::vector<Matrix<double,8,1> > fkm_matrix_left;\n\n\tfkm_matrix_relative=DQController::fkmDual(u_relative, p_relative, q_relative, joint_type_relative);\n\tpose_now_relative=DQoperations::mulDQ(fkm_matrix_relative[joint_size_relative-1], pe_init_relative);\n\t// MatrixXd htm_left;\n\t// htm_left= DQoperations::dq2HTM(pose_now_left);\n\t// std::cout << \"htm_left: \" << htm_left << std::endl;\n\n}\n\nvoid BaxterPoseControlServer::update_rightRelative()\n{\n\tRowVectorXd q_temp;\n\n\tq_rightRelative_relative.resize(14);\t\n\tq_rightRelative_right.resize(7);\n\n\tq_temp = q_baxter.head(7);\n\tq_rightRelative_relative << -q_temp.reverse() , q_baxter.tail(7);\n\tq_rightRelative_right << -q_temp.reverse();\n\t// std::cout << \"q_relative: \" << q_relative << std::endl;\n\n\tq_vel_rightRelative_relative.resize(14);\n\tq_vel_rightRelative_right.resize(7);\n\n\tq_temp = q_vel_baxter.head(7);\n\tq_vel_rightRelative_relative << -q_temp.reverse() , q_vel_baxter.tail(7);\n\tq_vel_rightRelative_right << -q_temp.reverse();\n\t// std::cout << \"q_left: \" << q_left << std::endl;\n\t// std::cout << \"q_vel_left: \" << q_vel_left << std::endl;\t\n\t// std::vector<Matrix<double,8,1> > fkm_matrix_left;\n\n\n\tfkm_matrix_rightRelative_right=DQController::fkmDual(u_rightRelative_right, p_rightRelative_right, q_rightRelative_right, joint_type_rightRelative_right);\n\tpose_now_rightRelative_right=DQoperations::mulDQ(fkm_matrix_rightRelative_right[joint_size_rightRelative_right-1], pe_init_rightRelative_right);\n\n\tfkm_matrix_rightRelative_relative=DQController::fkmDual(u_rightRelative_relative, p_rightRelative_relative, q_rightRelative_relative, joint_type_rightRelative_relative);\n\tpose_now_rightRelative_relative=DQoperations::mulDQ(fkm_matrix_rightRelative_relative[joint_size_rightRelative_relative-1], pe_init_rightRelative_relative);\n\n\t// MatrixXd htm_left;\n\t// htm_left= DQoperations::dq2HTM(pose_now_left);\n\t// std::cout << \"htm_left: \" << htm_left << std::endl;\n\n}\n\nbool BaxterPoseControlServer::updateManipulatorVariables(std::string arm)\n{\n\t// std::cout << \"Here 5\" << std::endl;\n\t// ros::WallTime robotStat_time_start = ros::WallTime::now();\n\tros::WallTime jacobReal_time_start = ros::WallTime::now();\n\tupdate_manipulator();\n\t// ros::WallTime robotStat_time_end = ros::WallTime::now();\n\t// ros::WallDuration robotStat_time_dur = robotStat_time_end - robotStat_time_start;\n\t// std::cout << \"robotStat duration_server: \" << robotStat_time_dur.toSec() << std::endl; \t\n\tif(!arm.compare(\"all\"))\n\t{\n\t\t// ros::WallTime jacobReal_time_start = ros::WallTime::now();\n\t\tupdate_right();\t\t\n\t\tjacobian_8d_right= DQController::jacobianDual(u_right, p_right, pe_init_right, joint_type_right, fkm_matrix_right);\t\n\t\tjacobian_8d_right= DQController::jacobianDual_8d(joint_size_right, jacobian_8d_right);\t\n\t\tros::WallTime jacobReal_time_end = ros::WallTime::now();\n\t\tros::WallDuration jacobReal_time_dur = jacobReal_time_end - jacobReal_time_start;\n\t\t// jacobReal_time_start = ros::WallTime::now();\t\t\n\t\tstd::cout << \"jacobReal_time_dur duration_server_RIGHT: \" << jacobReal_time_dur.toSec() << std::endl; \t\t\n\t\t\n\t\t// jacobReal_time_start = ros::WallTime::now();\t\t\t\n\t\tupdate_left();\t\t\n\t\tjacobian_8d_left= DQController::jacobianDual(u_left, p_left, pe_init_left, joint_type_left, fkm_matrix_left);\t\n\t\tjacobian_8d_left= DQController::jacobianDual_8d(joint_size_left, jacobian_8d_left);\t\t\n\t\tjacobReal_time_end = ros::WallTime::now();\n\t\tjacobReal_time_dur = jacobReal_time_end - jacobReal_time_start;\n\t\tstd::cout << \"jacobReal_time_dur duration_server_TOTAL: \" << jacobReal_time_dur.toSec() << std::endl; \t\t\t\t\t\n\t\t\n\t\treturn 1;\n\t}\n\t// std::cout << \"Here 6\" << std::endl;\n\tif(!arm.compare(\"right\"))\n\t{\n\t\t// std::cout << \"Here 7\" << std::endl;\n\t\t// ros::WallTime manipUpdate_time_start = ros::WallTime::now();\n\t\tupdate_right();\t\t\n\t\t// ros::WallTime manipUpdate_time_end = ros::WallTime::now();\n\t\t// ros::WallDuration manipUpdate_time_dur = manipUpdate_time_end - manipUpdate_time_start;\n\t\t// std::cout << \"manipUpdate duration_server: \" << manipUpdate_time_dur.toSec() << std::endl;\t\t\n\t\t// std::cout << \"Here 8\" << std::endl;\n\t\tros::WallTime jacobSingle_time_start = ros::WallTime::now();\t\t\n\t\tjacobian_8d_right= DQController::jacobianDual(u_right, p_right, pe_init_right, joint_type_right, fkm_matrix_right);\t\n\t\tjacobian_8d_right= DQController::jacobianDual_8d(joint_size_right, jacobian_8d_right);\n\t\tros::WallTime jacobSingle_time_end = ros::WallTime::now();\n\t\tros::WallDuration jacobSingle_time_dur = jacobSingle_time_end - jacobSingle_time_start;\n\t\tstd::cout << \"jacobSingle duration_server: \" << jacobSingle_time_dur.toSec() << std::endl; \t\t\n\t\treturn 1;\n\t}\n\tif(!arm.compare(\"left\"))\n\t{\n\t\t// std::cout << \"Here 9\" << std::endl;\n\t\tupdate_left();\t\t\n\t\tjacobian_8d_left= DQController::jacobianDual(u_left, p_left, pe_init_left, joint_type_left, fkm_matrix_left);\t\n\t\tjacobian_8d_left= DQController::jacobianDual_8d(joint_size_left, jacobian_8d_left);\n\t\treturn 1;\n\t}\n\telse return 0;\n}\n\nvoid BaxterPoseControlServer::initializeBaxterIKService()\n{\n\tcontrollerService = rh.advertiseService(\"baxterControlService\", &BaxterPoseControlServer::baxterControlServerCallback, this);\t\n}\n\nbool BaxterPoseControlServer::importJointLimits(std::string arm, RowVectorXd &joint_high_limit, RowVectorXd &joint_low_limit, RowVectorXd &joint_max_safe_limit, RowVectorXd &joint_min_safe_limit)\n{\t\n\tif(!arm.compare(\"right\"))\n\t{\n\t\tfor (int i=0; i<7; i++)\n\t\t{\n\t\t\tjoint_min_safe_limit(i) = this->joint_min_safe_limit_right[i];\n\t\t\tjoint_max_safe_limit(i) = this->joint_max_safe_limit_right[i];\n\t\t\tjoint_low_limit(i) = this->joint_low_limit_right[i];\n\t\t\tjoint_high_limit(i)= this->joint_high_limit_right[i];\t\t\t\n\t\t}\n\t\treturn true;\t\t\n\t}\n\treturn false;\n} \n\nbool BaxterPoseControlServer::importManipulatorState_accControl(std::string arm, Matrix<double,8,1>& pe_init, Matrix<double,8,1>& pe_now, RowVectorXd& q, RowVectorXd& q_vel, MatrixXd& jacobian_6d, MatrixXd& jacobian_6d_dot)\n{\n\t// update_manipulator();\n\t// updateManipulatorVariables(arm);\t\n\tif(!arm.compare(\"right\"))\n\t{\n\t\tupdate_rightAcc();\n\t\tpe_init= this->pe_init_right;\n\t\tpe_now= this->pose_now_right;\n\t\tjacobian_6d = this->jacobian_6d_right;\n\t\tq = this-> q_right;\n\t\tq_vel = this-> q_vel_right;\n\t\tjacobian_6d_dot = this->jacobian_6d_dot_right;\n\t\treturn 1;\n\t}\n\telse if(!arm.compare(\"left\"))\n\t{\n\t\tupdate_leftAcc();\n\t\tpe_init= this->pe_init_left;\n\t\tpe_now= this->pose_now_left;\n\t\tjacobian_6d = this->jacobian_6d_left;\n\t\tq = this-> q_left;\n\t\tq_vel = this-> q_vel_left;\n\t\tjacobian_6d_dot = this->jacobian_6d_dot_left;\n\t\treturn 1;\n\t}\n\telse return 0;\n}\n\n\n\nbool BaxterPoseControlServer::importManipulatorState(std::string arm, Matrix<double,8,1>& pe_init, Matrix<double,8,1>& pe_now, MatrixXd& jacobian, RowVectorXd& q, std::vector<double> joint_velocity_limit)\n{\n\t// updateManipulatorVariables(arm);\t\n\tif(!arm.compare(\"right\"))\n\t{\n\t\tpe_init= this->pe_init_right;\n\t\tpe_now= this->pose_now_right;\n\t\tjacobian = this->jacobian_8d_right;\n\t\tq = this-> q_right;\n\t\tjoint_velocity_limit = this->joint_velocity_limit_right;\n\t\treturn 1;\n\t}\n\telse if(!arm.compare(\"left\"))\n\t{\n\t\tpe_init= this->pe_init_left;\n\t\tpe_now= this->pose_now_left;\n\t\tjacobian = this->jacobian_8d_left;\n\t\tq = this-> q_left;\n\t\tjoint_velocity_limit = this->joint_velocity_limit_left;\n\t\treturn 1;\n\t}\n\telse return 0;\n}\n\nvoid BaxterPoseControlServer::Run()\n{\t\n\tROS_INFO(\"BaxterPoseControlServer...spinning\");\n ros::spin();\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"baxter_controller\");\n\tros::NodeHandle n;\n\tBaxterPoseControlServer* baxter_controller= new BaxterPoseControlServer();\n\tif (!baxter_controller->BaxterPoseControlServer::initializeController())\n\t{\n\t\tROS_ERROR(\"The robot can not be initialized.\");\n\t\treturn 0;\n\t}\n\tbaxter_controller->initializeBaxterIKService();\n\tbaxter_controller->BaxterPoseControlServer::Run();\n\treturn 1;\n\t// ros::ServiceServer controllerService = n.advertiseService(\"baxterControlService\", &BaxterPoseControlServer::baxterControlServerCallback, baxter_controller);\n\t// baxter_controller->BaxterPoseControlServer::update_manipulator();\n}\n\n\t// using_rel=1;\n\t// using_right=1;\n\t// manipulator_right->ManipulatorDQ::updateManipulator_right();\n\t// // dt=manipulator_right->ManipulatorDQ::getSamplingTime();\n\t// pose_now_right= manipulator_right->ManipulatorDQ::poseNow();\t\n\t// jacobian_8d_right=manipulator_right->ManipulatorDQ::jacobian_dq_8d();\t\n\t// screw_error_right = DQPositionController::getScrewError(pose_now_right, pose_desired_right);\n\n\t// manipulator_rel->ManipulatorDQ::updateManipulator_dualArm();\n\t// q_now=manipulator_rel->ManipulatorDQ::currentJointPosition();\t\n\t// q_dot_now=manipulator_rel->ManipulatorDQ::currentJointVelocity();\t\t\n\t// dt=manipulator_rel->ManipulatorDQ::getSamplingTime();\n\t// pose_now_rel= manipulator_rel->ManipulatorDQ::poseNow();\t\n\t// jacobian_8d_rel=manipulator_rel->ManipulatorDQ::jacobian_dq_8d();\t\n\t// screw_error_rel = DQPositionController::getScrewError(pose_now_rel, pose_desired_rel);\n\n\t// RowVectorXd combined_screw_error =RowVectorXd::Zero(screw_error_rel.cols()+screw_error_right.cols());\n\t// // ROS_INFO(\"1\");\n\t// // std::cout << \"screw_error_rel.size: \" << screw_error_rel.rows() << \":\" << screw_error_rel.cols() << std::endl; \n\t// // std::cout << \"screw_error_right.size: \" << screw_error_right.rows() << \":\" << screw_error_right.cols() << std::endl; \n\t// combined_screw_error << screw_error_rel.row(0), screw_error_right.row(0);\n\t// norm_error=combined_screw_error.norm();\n\t// // ROS_INFO(\"2\");\n\t// MatrixXd combined_jacobian_8d =MatrixXd::Zero((jacobian_8d_rel.rows()+jacobian_8d_right.rows()), (jacobian_8d_rel.cols()));\n\n\t// // ROS_INFO(\"3\");\n\t// combined_jacobian_8d.block(0, 0, jacobian_8d_rel.rows(), jacobian_8d_rel.cols())=jacobian_8d_rel;\n\t// combined_jacobian_8d.block(jacobian_8d_rel.rows(), 0, jacobian_8d_right.rows(), jacobian_8d_right.cols())=jacobian_8d_right;\n\t// jacobian_8d_control=combined_jacobian_8d;\n\t// joint_size_control=joint_size_rel;\n\t// screw_error_control=combined_screw_error;\n\t// getControllerParam\n\t// initialize_controller();\n\t// std::vector<RowVector3d> u, p;\n\t// Matrix<double,8,1> pe_init_left, pe_init_right, pe_init_leftRef, pe_init_torsoRef;\n\t// std::vector<double> joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names;\n\t// std::vector<std::string> joint_names;\n\t// std::vector<int> joint_type;\n\t// ros::Time current_time, last_time;\n\t// RowVectorXd q, q_vel;\n\t// std::vector<Matrix<double,8,1> > fkm_matrix;\n\t// baxter->ManipulatorModDQ::robotParams(u, p, pe_init_left, pe_init_right, joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names, joint_type);\n\n\t// intialize_right(u, p, joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names, joint_type);\n\t// intialize_left(u, p, joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names, joint_type);\n\t// intialize_rel(u, p, pe_init_left, pe_init_right, joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names, joint_type);\n\t// intialize_rightRelative(u, p, pe_init_left, pe_init_right, joint_high_limit, joint_low_limit, velocity_limit, max_safe, min_safe, joint_names, joint_type);\n\n\t// // dq_robotics::BaxterControl::Request baxterControl_req; \n\t// // dq_robotics::BaxterControl::Response baxterControl_res; \n\n\t// ros::ServiceServer service = n.advertiseService(\"baxterControlService\", baxterControlService_process);\n\t// ROS_INFO(\"Ready to take cartesian poses for BaxterControl.\");\n" }, { "alpha_fraction": 0.5681536793708801, "alphanum_fraction": 0.6047087907791138, "avg_line_length": 54.68965530395508, "blob_id": "9d7ea48b2ffe773a7f0180ec0138ad0005816a09", "content_id": "18661611f6ecff50044f800f75347a65410ac6d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 107, "num_lines": 29, "path": "/dq_robotics/config/acc_control_params_kdl.cfg", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nPACKAGE = \"dq_robotics\"\nimport math\nmath.pi\nfrom dynamic_reconfigure.parameter_generator_catkin import *\n\ngen = ParameterGenerator()\n\ngen.add(\"start_controller\", bool_t, 0, \"start control\", False)\ngen.add(\"accCntrl_K_p\", double_t, 0, \"proportional gain\", 430, 0, 600)\ngen.add(\"accCntrl_K_i\", double_t, 0, \"integral gain\", 0, 0, 20)\ngen.add(\"accCntrl_K_d\", double_t, 0, \"derivative gain\", 300, 0, 400)\ngen.add(\"accCntrl_total_time\", double_t, 0, \"simulation time\", 10, 0, 200)\ngen.add(\"accCntrl_frequency\", double_t, 0, \"desired frequecy of controller\", 1000, 0, 2000)\ngen.add(\"accCntrl_theta_init\", double_t, 0, \"theta_init for rotation task\", 0, 0, math.pi)\ngen.add(\"accCntrl_theta_final\", double_t, 0, \"theta_final for rotation task\", math.pi/2, 0, math.pi)\n# gen.add(\"double_param\", double_t, 0, \"A double parameter\", .5, 0, 1)\n# gen.add(\"str_param\", str_t, 0, \"A string parameter\", \"Hello World\")\n# gen.add(\"bool_param\", bool_t, 0, \"A Boolean parameter\", True)\n\n# size_enum = gen.enum([ gen.const(\"Small\", int_t, 0, \"A small constant\"),\n# gen.const(\"Medium\", int_t, 1, \"A medium constant\"),\n# gen.const(\"Large\", int_t, 2, \"A large constant\"),\n# gen.const(\"ExtraLarge\", int_t, 3, \"An extra large constant\")],\n# \"An enum to set size\")\n\n# gen.add(\"size\", int_t, 0, \"A size parameter which is edited via an enum\", 1, 0, 3, edit_method=size_enum)\n\nexit(gen.generate(PACKAGE, \"dq_robotics\", \"kdl_convntnl_controller\"))" }, { "alpha_fraction": 0.6679999828338623, "alphanum_fraction": 0.7095000147819519, "avg_line_length": 27.16901397705078, "blob_id": "63ee69a9f76aee6b1f2463b020b5df91ef853428", "content_id": "b18c00e9b941df9c731a1209bf4762317caa7289", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2000, "license_type": "no_license", "max_line_length": 105, "num_lines": 71, "path": "/dq_robotics/src/test/fake_ar10_jointStates.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#define _USE_MATH_DEFINES\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <stdexcept> //for range_error\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n#include <complex>\n#include <cmath>\n#include <vector>\n#include <cstddef>\n#include <Eigen/SVD>\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <dq_robotics/dq_controller.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <cstdio>\n#include <tf2/LinearMath/Quaternion.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_msgs/MultiArrayDimension.h>\n#include <dq_robotics/IkHand.h>\n#include <ros/package.h>\n\nros::Publisher jointState_pub;\nsensor_msgs::JointState ar10_JointState;\n\nvoid ar10_jointStateCallback(const sensor_msgs::JointState::ConstPtr& msg)\n{\n\tfor (int j=0; j < ar10_JointState.name.size(); j++)\n\t{\n\t\t// std::cout << \"joint_names[\" << j << \"]: \" << joint_names[j] << std::endl;\n\t\tfor (int i=0; i < msg->name.size(); i++)\n\t\t{\n\t\t\tif(msg->name[i].compare(ar10_JointState.name[j])==0)\n\t\t\t{\n\t\t\t\tar10_JointState.position[j]=msg->position[i];\t\n\t\t\t}\n\t\t}\n\t}\n\tjointState_pub.publish(ar10_JointState);\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"fake_ar10_kinematics\");\n\tros::NodeHandle n;\n\n\tar10_JointState.name.clear();\n\tar10_JointState.name.push_back(\"servo0\");\n\tar10_JointState.name.push_back(\"servo1\");\n\tar10_JointState.name.push_back(\"servo8\");\n\tar10_JointState.name.push_back(\"servo9\");\n\n\tar10_JointState.position.clear();\n\tar10_JointState.position.push_back(0.896);\n\tar10_JointState.position.push_back(0.303);\n\tar10_JointState.position.push_back(0.134);\n\tar10_JointState.position.push_back(0.499);\n\n jointState_pub = n.advertise<sensor_msgs::JointState>(\"/ar10/right/servo_positions\", 1000);\n\tros::Subscriber sub = n.subscribe(\"/ar10_right/ar10/right/joint_states\", 1000, ar10_jointStateCallback);\n\tros::Rate hz(100);\n\twhile(ros::ok())\n\t{\n\t\tjointState_pub.publish(ar10_JointState);\n\t\tros::spinOnce();\n\t\thz.sleep();\t\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5540657639503479, "alphanum_fraction": 0.6812283992767334, "avg_line_length": 36.86885070800781, "blob_id": "12d80cb2a31d852f0056cf21c8ebcdafd7f502ea", "content_id": "a71bb6ece76eed12a2962f191df7ae2ada2020dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2312, "license_type": "no_license", "max_line_length": 126, "num_lines": 61, "path": "/dq_robotics/src/test/grasp_client_test.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n#include <visualization_msgs/Marker.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <dq_robotics/Grasp.h>\n\nint main( int argc, char** argv )\n{\n ros::init(argc, argv, \"grasp_client\");\n ros::NodeHandle n;\n ros::ServiceClient client = n.serviceClient<dq_robotics::Grasp>(\"baxterAR10/grasp_service\");\n\n dq_robotics::Grasp::Request grasp_req;\n const geometry_msgs::PoseStampedConstPtr pen_pose = ros::topic::waitForMessage<geometry_msgs::PoseStamped>(\"pen_pose\");\n Matrix<double,8,1> pen_pose_dq, graspPoint_thumb, graspPoint_index, pre_grasp_pose;\n Matrix4d htm_pen_pose = DQoperations::htmFromGeometryMsgPose(pen_pose->pose);\n\n\tMatrix4d htm=Matrix4d::Identity();\n\thtm(0, 1) = -0.15;\n\tpre_grasp_pose = DQoperations::htm2DQ(htm_pen_pose*htm);\n grasp_req.pre_grasp_distance = -0.15;\n\n htm=Matrix4d::Identity();\n htm(0,3) = (0.05/2);\n // graspPoint_index << 0.678793, -0.19809, -0.678793, 0.19809, 0.00859172, 0.0318088, 0.0178029, 0.0633727;\n graspPoint_index << 0.518857, -0.716394, 0.462388, 0.061353, 0.515372, 0.137927, -0.351655, -0.0976784;\n\n\n // graspPoint_thumb << 0.827847, 0.428926, 0.258896, 0.252319, -0.00695001, -0.0392131, 0.0601057, 0.0277899; \n graspPoint_thumb << 0.960477, 0.235529, 0.122626, -0.0835014, 0.0014986, -0.02179, 0.0518687, 0.0319472; \n\n // grasp_req.grasp_pose_index = DQoperations::DQToDouble(DQoperations::htm2DQ(htm_pen_pose*htm));\n grasp_req.grasp_pose_index = DQoperations::DQToDouble(graspPoint_index);\n\n // Matrix4d htm_test=Matrix4d::Identity();\n // htm_test(0,3)= 0.709;\n // htm_test(1,3)= -0.862;\n // htm_test(2,3)= 0.310;\n // grasp_req.grasp_pose_index = DQoperations::DQToDouble(DQoperations::htm2DQ(htm_test));\n\n\n htm=Matrix4d::Identity();\n htm(0,3) = (-0.05/2);\n // grasp_req.grasp_pose_thumb = DQoperations::DQToDouble(DQoperations::htm2DQ(htm_pen_pose*htm));\n grasp_req.grasp_pose_thumb = DQoperations::DQToDouble(graspPoint_thumb);\n\n dq_robotics::Grasp grasp;\n grasp.request = grasp_req;\n ROS_INFO(\"here 1\"); \n if (client.call(grasp))\n {\n ROS_INFO(\"normError: %f\", grasp.response.normError);\n }\n else\n {\n ROS_ERROR(\"Failed to call service grasp_service\");\n return 1;\n }\n return 0;\n\n} \n\n" }, { "alpha_fraction": 0.7746666669845581, "alphanum_fraction": 0.781333327293396, "avg_line_length": 34.761905670166016, "blob_id": "e76fa3abf7ba51c68d21d21eadf44ce57bf9d80e", "content_id": "656748ebe6dea299266dfb045690ce6082ef72d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 750, "license_type": "no_license", "max_line_length": 234, "num_lines": 21, "path": "/dq_robotics/include/dq_robotics/baxter_poseControl_server_2.h", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/baxter_poseControl_server.h>\n#include <dq_robotics/ar10_kinematics.h>\n\nclass BaxterPoseControlServer_2 \n{\nprivate:\n\tMatrixXd arm_jacobian_right, arm_jacobian_left, index_jacobian_right, thumb_jacobian_right, armThumb_jacobian_right, armIndex_jacobian_right, index_jacobian_left, thumb_jacobian_left, armThumb_jacobian_left, armIndex_jacobian_left; \npublic:\n// intialize arm and hand \n\tbool initialize_handArmController();\n\tvoid update_handArm();\n\tvoid jacobian_right_armHand();\n\tBaxterPoseControlServer_2();\n\t~BaxterPoseControlServer_2();\n// get right_arm_jacobian\n// get right_hand_index_jacobian\n// get right_hand_thumb_jacobian\n// make task jacobian\n// get desired poses \n// send controller cmds to respective controllers\n};" }, { "alpha_fraction": 0.6600935459136963, "alphanum_fraction": 0.6852390766143799, "avg_line_length": 39.049468994140625, "blob_id": "f2994a8151e0c06c7baaa170cac3f0db3677e26b", "content_id": "692ae3a1d2086646e278d45dcc148be4dc595775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22668, "license_type": "no_license", "max_line_length": 362, "num_lines": 566, "path": "/dq_robotics/src/manipulation_task_controller.cpp", "repo_name": "rohitChan/ifacWC2020", "src_encoding": "UTF-8", "text": "#include <dq_robotics/manipulation_task_controller.h>\n\nusing namespace Eigen;\n\nManipulationTaskController::ManipulationTaskController()\n{\n}\nManipulationTaskController::~ManipulationTaskController(){}\n// ManipulationTaskController::doRotationOrTranslation(false, pre_grasp_pose, axis, 0, 0.1, 0.02, controller_mode, use_velocity_control)\nbool ManipulationTaskController::doRotationOrTranslation(bool rotation, Matrix<double,8,1> initial_pose, RowVectorXd axis, double initial_vm_jp, double final_vm_jp, double vm_velocity, int controller_mode, bool use_velocity_control, Matrix<double,8,1> pose_right, Matrix<double,8,1> pose_relative, bool vm_relative, Matrix<double,8,1>& final_pose_commanded)\n{\n\tMatrix<double,8,1> next_pose;\n\tdq_robotics::BaxterControl::Request motion_request;\n\tdouble normError=1;\n std::vector<RowVector3d> u_abs, p_abs;\n std::vector<int> joint_type_abs;\n RowVectorXd q_vm_abs, q_init_abs;\n u_abs.resize(1);\n p_abs.resize(1);\n q_init_abs.resize(1);\n q_vm_abs.resize(1);\n joint_type_abs.resize(1);\n\tstd::vector<Matrix<double,8,1> > fkm_matrix_abs;\n\tfkm_matrix_abs.resize(1);\t \n\n u_abs[0]<< axis(0), axis(1), axis(2);\n p_abs[0]<< axis(3), axis(4), axis(5);\n if (rotation)\n\t joint_type_abs[0]=0;\n\telse\n\t\tjoint_type_abs[0]=1;\n\n q_init_abs[0]=initial_vm_jp;\n\n\tdouble time_now=0, time_begin=0, time_last=0, time_diff=0;\n ros::Duration(0.5).sleep();\n time_begin=ros::Time::now().toSec();\n ros::Duration(0.5).sleep();\n time_begin=ros::Time::now().toSec();\n // std::cout << \"time_begin: \" << time_begin << std::endl; \n time_last=ros::Time::now().toSec()-time_begin; \n\n\tmotion_request.velocity_control=use_velocity_control;\n\tmotion_request.useVisualPose_single=false;\n\tmotion_request.useVisualPose_relative=false; \n\tmotion_request.controlMode=controller_mode;\n q_vm_abs[0]=initial_vm_jp;\n // ROS_INFO(\"doRotationOrTranslation\");\n // double time_begin=ros::Time::now().toSec();\n while (q_vm_abs[0] < final_vm_jp)\n {\n \ttime_now=ros::Time::now().toSec()-time_begin; \t\n \tstd::cout << \"q_vm_abs[0]: \" << q_vm_abs[0] << std::endl; \n \t// std::cout << \"final_vm_jp: \" << final_vm_jp << std::endl; \n\t\t// time_now=ros::Time::now().toSec(); \t\n q_vm_abs[0]=vm_velocity*time_diff+q_init_abs[0];\n fkm_matrix_abs=DQController::fkmDual(u_abs, p_abs, q_vm_abs, joint_type_abs);\n next_pose=DQoperations::mulDQ(fkm_matrix_abs[p_abs.size()-1], initial_pose);\n std::cout << \"htm_next_pose: \" << std::endl;\n std::cout << DQoperations::dq2HTM(next_pose) << std::endl;\n motion_request.desiredAbsPose= DQoperations::DQToDouble(pose_right);\t \t\n if(vm_relative )\n\t\t{\n\t\t\tmotion_request.desiredRelPose= DQoperations::DQToDouble(next_pose);\n\t\t\tmotion_request.desiredAbsPose= DQoperations::DQToDouble(pose_right);\n\t\t}\t \n\t\telse\n\t\t{\n\t\t\tmotion_request.desiredRelPose= DQoperations::DQToDouble(pose_relative);\n\t\t\tmotion_request.desiredAbsPose= DQoperations::DQToDouble(next_pose);\t\t\t\n\t\t}\n srv.request=motion_request; \n if (pose_control_client.call(srv))\n {\n ROS_INFO(\"normError: %f\", srv.response.normError);\n normError=srv.response.normError;\n // prepareMsg();\n // controller_error_publisher.publish(controlOutputMsg); \n }\n else\n {\n ROS_ERROR(\"Failed to call service baxterControlService\");\n return 0;\n }\n time_diff=time_diff+(time_now - time_last) ; \t \n\n\t\t// std::cout << \"time_diff: \" << time_diff << std::endl; \n\t\t// std::cout << \"time_last: \" << time_last << std::endl; \n\t\t// std::cout << \"time_now2: \" << time_now << std::endl; \n\n time_last=time_now;\t\t\n }\n final_pose_commanded=next_pose; \t\n return 1;\n}\n\nvoid ManipulationTaskController::publishPose2Rviz(float rate, Matrix<double,8,1> pose, std::string ref_frame)\n{\n\tgeometry_msgs::PoseStamped rviz_pose;\n rviz_pose.pose=DQoperations::DQ2geometry_msgsPose(pose);\n rviz_pose.header.frame_id=\"base\";\n rviz_pose.header.stamp=ros::Time::now();\n ros::Rate loop_rate(rate);\n while(ros::ok())\n\t{ \n\t\trviz_pub.publish(rviz_pose);\n\t\tloop_rate.sleep();\n\t}\t\n}\n\n\n\nbool ManipulationTaskController::ToPreGraspToGrasp(Matrix<double,8,1> grasp_location, std::string reference_frame, double distance, RowVectorXd approach_direction, int controller_mode, bool use_velocity_control)\n{\n ROS_INFO(\"ToPreGraspToGrasp\");\n\n dq_robotics::BaxterControl::Request go2pregrasp_req;\n double pre_grasp_distance=0.1, q_vel_vm=0;\n RowVectorXd axis(6);\n\tstd::cout << \"grasp_location: \" << std::endl;\n\tstd::cout << DQoperations::dq2HTM(grasp_location) << std::endl;\n\tRowVector3d grasp_position, grasp_axis_vector;\n\tgrasp_axis_vector << approach_direction(0), approach_direction(1), approach_direction(2);\n\tgrasp_position << approach_direction(3), approach_direction(4), approach_direction(5);\n\tgrasp_position = grasp_position.cross(grasp_axis_vector);\n axis << grasp_axis_vector, grasp_position;\n\tstd::cout << \"axis_before: \" << axis << std::endl;\n\taxis= DQoperations::transformLine6dVector(axis, grasp_location);\n std::cout << \"axis_after: \" << axis << std::endl;\n // std::string ref_frame=\"/base\";\n\tboost::thread thr1(boost::bind(&ManipulationTaskController::publishPose2Rviz, this, 10, grasp_location, reference_frame));\n\t// ros::Duration(5).sleep();\n Matrix<double,8,1> pre_grasp_pose= DQoperations::preGraspFromGraspPose(grasp_location, distance, grasp_axis_vector);\n Matrix<double,8,1> pose_desired_rel;\n\n\tboost::thread thr2(boost::bind(&ManipulationTaskController::publishPose2Rviz, this, 10, pre_grasp_pose, reference_frame));\n\t// thr.join();\n // ManipulationTaskController::publishPose2Rviz(10, pre_grasp_pose, ref_frame);\n\n // boost::thread thr = new boost::thread(boost::bind(&ManipulationTaskController::publishPose2Rviz, this));\n // rviz_pose.pose=DQoperations::DQ2geometry_msgsPose(pre_grasp_pose);\n // rviz_pose.header.frame_id=\"base\";\n // rviz_pose.header.stamp=ros::Time::now();\n // ros::Rate loop_rate(10);\n // while(ros::ok())\n\t// { \n\t// \trviz_pub.publish(rviz_pose);\n\t// \tloop_rate.sleep();\n\t// }\n\t// if(ManipulationTaskController::go2Pose_constVelocity(pre_grasp_pose, pose_desired_rel, 1, 50, false))\n\tROS_INFO(\"Rough approach starts...\");\n\tif(!ManipulationTaskController::go2Pose_withPrecision(pre_grasp_pose, pose_desired_rel, 0.5, controller_mode, true))\n\t\treturn 0; \n\tROS_INFO(\"Rough approach over\");\n\tROS_INFO(\"Precise approach starts...\");\n\tif(!ManipulationTaskController::go2Pose_withPrecision(pre_grasp_pose, pose_desired_rel, 0.25, controller_mode, true))\n\t\treturn 0;\t\n\telse\tROS_INFO(\"Precise approach Over. Pre-grasp to grasp start will start now.\"); \n\t\t// std::cout << \"pre_grasp_pose: \" << std::endl;\n\t\t// std::cout << DQoperations::dq2HTM(pre_grasp_pose) << std::endl;\n\t\t// publish2Rviz(\"base\", pre_grasp_pose)\n\t // std::cout << DQoperations::dq2HTM(pre_grasp_pose) << std::endl;\n\tdistance=distance+0.05;\n\tMatrix<double,8,1> final_pose_commanded;\n\tif (!ManipulationTaskController::doRotationOrTranslation(false, pre_grasp_pose, axis, 0, distance, 0.02, controller_mode, use_velocity_control, pre_grasp_pose, pre_grasp_pose, false, final_pose_commanded))\n\treturn 0;\n\telse ROS_INFO(\"Grasp position achieved.\"); \n\n\treturn 1; \n}\n\n\nbool ManipulationTaskController::go2Pose_withPrecision(Matrix<double,8,1> pose_desired_abs, Matrix<double,8,1> pose_desired_rel, double error_threshold, int controller_mode, bool use_velocity_control)\n{\n\tdq_robotics::BaxterControl::Request controllerServ_req;\n controllerServ_req.velocity_control=use_velocity_control;\n controllerServ_req.useVisualPose_single=false;\n controllerServ_req.useVisualPose_relative=false; \n controllerServ_req.controlMode=controller_mode;\n controllerServ_req.desiredAbsPose= DQoperations::DQToDouble(pose_desired_abs); \n controllerServ_req.desiredRelPose= DQoperations::DQToDouble(pose_desired_rel);\n srv.request=controllerServ_req;\n double normError=1;\n // ROS_INFO(\"Home to pre-grasp: BEGIN\");\n while (normError>error_threshold)\n {\n if (pose_control_client.call(srv))\n {\n ROS_INFO(\"normError: %f\", srv.response.normError);\n normError=srv.response.normError;\n // prepareMsg();\n // controller_error_publisher.publish(controlOutputMsg);\n }\n else\n {\n ROS_ERROR(\"Failed to call service baxterControlService\");\n return 0;\n }\n }\n return 1; \n}\n\nbool ManipulationTaskController::go2Pose_constVelocity(Matrix<double,8,1> pose_desired_abs , Matrix<double,8,1> pose_desired_rel, int controller_mode, int total_time, bool use_velocity_control)\n{\n // std::cout << \"time: \" << std::endl;\n dq_robotics::BaxterControl::Request inforServ_req, controllerServ_req;\n double normError=1;\n inforServ_req.request_manipulator_infoService=true;\n inforServ_req.infoService_mode=controller_mode;\n Matrix<double,8,1> pose_current_rel, pose_current_abs;\n srv.request=inforServ_req;\n\n if (pose_control_client.call(srv))\n {\n pose_current_abs=DQoperations::returnDoubleToDQ(srv.response.currentAbsPose);\n if (controller_mode!=1 && controller_mode!=2)\n { \n pose_current_rel=DQoperations::returnDoubleToDQ(srv.response.currentRelPose);\n }\n } \n else\n {\n ROS_ERROR(\"Failed to get manipulator info from baxterControlService service.\");\n return 1;\n } \n\n controllerServ_req.velocity_control=use_velocity_control;\n controllerServ_req.useVisualPose_single=false;\n controllerServ_req.useVisualPose_relative=false; \n controllerServ_req.controlMode=controller_mode;\n\n double time_now=0, time_begin=0, time_last=0, time_diff=0;\n time_begin=ros::Time::now().toSec();\n ros::Duration(0.5).sleep();\n time_begin=ros::Time::now().toSec();\n // std::cout << \"time_begin: \" << time_begin << std::endl; \n time_last=ros::Time::now().toSec()-time_begin; \t\n // time_last=time_now;\n while (time_diff<total_time)\n {\n\t\t// std::cout << \"ros::Time::now().toSec(): \" << ros::Time::now().toSec() << std::endl; \n\t\t// std::cout << \"time_begin: \" << time_begin << std::endl; \n time_now=ros::Time::now().toSec()-time_begin; \t\n\t\t// std::cout << \"time_now1: \" << time_now << std::endl; \n double tau=(time_diff/total_time);\n Matrix<double,8,1> pose_desired_abs_i;\n Matrix<double,8,1> velocity_abs= DQoperations::sclerp(pose_current_abs, pose_desired_abs_i, pose_desired_abs, tau);\n // publish2Rviz(\"base\", pose_desired_abs_i);\n controllerServ_req.desiredAbsPose= DQoperations::DQToDouble(pose_desired_abs_i); \n controllerServ_req.desiredAbsVelocity= DQoperations::DQToDouble(velocity_abs); \t\n if (controller_mode!=1 && controller_mode!=2)\n { \n Matrix<double,8,1> pose_desired_rel_i;\n\t\t\tMatrix<double,8,1> velocity_rel= DQoperations::sclerp(pose_current_rel, pose_desired_rel_i, pose_desired_rel, tau); \t\n // publish2Rviz(\"/right_arm\", \"/left_arm\");\n controllerServ_req.desiredRelPose= DQoperations::DQToDouble(pose_desired_rel_i); \n controllerServ_req.desiredRelVelocity= DQoperations::DQToDouble(velocity_rel); \n }\n srv.request=controllerServ_req;\n if (pose_control_client.call(srv))\n {\n ROS_INFO(\"normError: %f\", srv.response.normError);\n normError=srv.response.normError;\n // std::cout << \"time: \" << time_diff << std::endl;\n // prepareMsg();\n // controller_error_publisher.publish(controlOutputMsg);\n }\n // std::cout << \"time: \" << time_diff << std::endl;\n else\n {\n ROS_ERROR(\"Failed to call position controller service baxterControlService\");\n return 1;\n }\n time_diff=time_diff+(time_now - time_last) ; \t \n\n\t\tstd::cout << \"time_diff: \" << time_diff << std::endl; \n\t\tstd::cout << \"time_last: \" << time_last << std::endl; \n\t\tstd::cout << \"time_now2: \" << time_now << std::endl; \n\n time_last=time_now;\t\t\n } \n}\n\nvoid ManipulationTaskController::getHTMfromTFTransform(Matrix4d &htm, tf::StampedTransform transform)\n{\n tf::Quaternion quat=transform.getRotation();\n Eigen::Quaterniond q;\n q.x()=-quat.x();\n q.y()=-quat.y();\n q.z()=-quat.z();\n q.w()=-quat.w();\n Eigen::Matrix3d rot = q.normalized().toRotationMatrix();\n\n tf::Vector3 trans=transform.getOrigin();\n Eigen::RowVector4d translation;\n translation << trans.getX(), trans.getY(), trans.getZ(), 1;\n\n htm.setIdentity();\n htm.block<3,3>(0,0) = rot;\n htm.rightCols<1>() =translation ;\n}\n\nbool ManipulationTaskController::bimanual_pouringTask()\n{\n\thand_cmds_msg.shortcutCmds=1;\n\thand_cmds_msg.hand=0;\n\tROS_INFO(\"opening right hand\");\n\tdouble count=0;\n\twhile(count<2)\n\t{\n\t\thand_cmds_publisher.publish(hand_cmds_msg);\n\t\tcount=count+1;\n\t\tros::Duration(.4).sleep();\t\n\t}\t\n\tros::Duration(3).sleep();\t\n\tROS_INFO(\"right hand should be open\");\n\n\thand_cmds_msg.shortcutCmds=1;\n\thand_cmds_msg.hand=1;\n\tROS_INFO(\"opening left hand\");\n\tcount =0;\n\twhile(count<2)\n\t{\n\t\thand_cmds_publisher.publish(hand_cmds_msg);\n\t\tcount=count+1;\n\t\tros::Duration(.4).sleep();\t\n\t}\n\tros::Duration(3).sleep();\t\t\n\tROS_INFO(\"left hand should be open\");\n\tMatrix4d right_object=Matrix4d::Identity(), left_object=Matrix4d::Identity(), rel_pose_rotation=Matrix4d::Identity();\n\tMatrix4d htm_right=Matrix4d::Identity(), htm_left=Matrix4d::Identity() ;\n Matrix<double,8,1> right_grasp_location, left_grasp_location;\n tf::TransformListener listener;\n\ttf::StampedTransform transform;\n try{\n ros::Time now = ros::Time(0);\n listener.waitForTransform(\"base\", \"/bottle_0_ft1\",\n now, ros::Duration(4.0));\n listener.lookupTransform(\"base\", \"/bottle_0_ft1\",\n now, transform);\n }\n catch (tf::TransformException& ex)\n {\n ROS_ERROR(\"%s\",ex.what());\n ros::Duration(1.0).sleep();\n return false;\n }\n getHTMfromTFTransform(htm_right, transform);\n htm_right(0,3)=htm_right(0,3)-0.03;\n htm_right(1,3)=htm_right(1,3)-0.03;\n htm_right(2,3)=htm_right(2,3)+0.04;\n\n right_grasp_location= DQoperations::htm2DQ(htm_right);\n std::cout << \"right_grasp_location:\" << std::endl;\n std::cout << right_grasp_location << std::endl;\n\n\tRowVectorXd right_lift_axis(6), left_lift_axis(6);\n\tright_lift_axis << 0, 0, 1, htm_right(0, 3), htm_right(1, 3), htm_right(2, 3); \n\tdouble lift_distance=0.3, lift_velocity=0.03;\n\n\ttry{\n ros::Time now = ros::Time(0);\n listener.waitForTransform(\"base\", \"/glass_0_ft2\",\n now, ros::Duration(4.0));\n listener.lookupTransform(\"base\", \"/glass_0_ft2\",\n now, transform);\n }\n catch (tf::TransformException& ex)\n {\n ROS_ERROR(\"%s\",ex.what());\n ros::Duration(1.0).sleep();\n return false;\n }\n getHTMfromTFTransform(htm_left, transform);\n\n htm_left(0,3)=htm_left(0,3)-0.05; \n htm_left(1,3)=htm_left(1,3)+0.01; \n htm_left(2,3)=htm_left(2,3)+0.03; \n\n \tleft_grasp_location= DQoperations::htm2DQ(htm_left);\n std::cout << \"left_grasp_location:\" << std::endl;\n std::cout << left_grasp_location << std::endl; \t\n\n\tleft_lift_axis << 0, 0, 1, htm_left(0, 3), htm_left(1, 3), htm_left(2, 3); \n\n\tstd::string reference_frame=\"base\";\n\tdouble distance=0.1;\n\tRowVectorXd approach_direction(6);\n\tapproach_direction << 0, 1, 0, htm_right(0, 3), htm_right(1, 3), htm_right(2, 3);\n\tint controller_mode=1;\n\tbool use_velocity_control=false;\n\n\tif (ManipulationTaskController::ToPreGraspToGrasp(right_grasp_location, reference_frame, distance, approach_direction, controller_mode, use_velocity_control))\n\t{\n\t\tROS_INFO(\"Right Grasp configuration achieved.\");\t\n\t}\n\telse return 0;\n\thand_cmds_msg.shortcutCmds=2;\n\thand_cmds_msg.hand=0;\n\tcount =0;\n\tROS_INFO(\"Closing right hand... \");\n\twhile(count<2)\n\t{\n\t\thand_cmds_publisher.publish(hand_cmds_msg);\n\t\tcount=count+1;\n\t\tros::Duration(.4).sleep();\t\n\t}\t\n\tros::Duration(3).sleep();\t\t\n\tROS_INFO(\"Right hand should be closed\");\n\tMatrix<double,8,1> final_pose_commanded_right, final_pose_commanded_left;\n\tif(ManipulationTaskController::doRotationOrTranslation(false, right_grasp_location, right_lift_axis, 0, lift_distance, lift_velocity, controller_mode, false, right_grasp_location, right_grasp_location, false, final_pose_commanded_right))\n\t\tROS_INFO(\"Right glass lift completed.\");\n\telse return 0;\n\n\tapproach_direction << 0, 1, 0, htm_left(0, 3), htm_left(1, 3), htm_left(2, 3);\n\tcontroller_mode=2;\n\tif (ManipulationTaskController::ToPreGraspToGrasp(left_grasp_location, reference_frame, distance, approach_direction, controller_mode, use_velocity_control))\n\t{\n\t\tROS_INFO(\"Left Grasp configuration achieved.\");\t\n\t}\n\telse return 0;\n\n\thand_cmds_msg.shortcutCmds=2;\n\thand_cmds_msg.hand=1;\t\n\tcount =0;\n\tROS_INFO(\"Closing left hand... \");\n\twhile(count<2)\n\t{\n\t\thand_cmds_publisher.publish(hand_cmds_msg);\n\t\tcount=count+1;\n\t\tros::Duration(.4).sleep();\t\n\t}\t\n\tros::Duration(3).sleep();\t\t\t\n\tROS_INFO(\"Left hand should be closed\");\n// return 0;\n\tif(ManipulationTaskController::doRotationOrTranslation(false, left_grasp_location, left_lift_axis, 0, lift_distance, lift_velocity, controller_mode, false, left_grasp_location, right_grasp_location, false, final_pose_commanded_left ))\n\t\tROS_INFO(\"Left glass lift completed.\");\n\telse return 0;\n\n\t// right_lift_axis.resize(6);\n\t// right_lift_axis << -1, 0, 0, 0, 0, 0;\n\t// controller_mode=1;\n\t// if (!ManipulationTaskController::doRotationOrTranslation(false, final_pose_commanded_right, right_lift_axis, 0, 0.1, 0.02, controller_mode, false, final_pose_commanded_right, final_pose_commanded_right, false, final_pose_commanded_right))\n\t// \treturn 0;\n\n\t// left_lift_axis.resize(6);\n\t// left_lift_axis << 0, 1, 0, 0, 0, 0;\n\t// controller_mode=2;\n\t// if (!ManipulationTaskController::doRotationOrTranslation(false, final_pose_commanded_left, left_lift_axis, 0, 0.1, 0.02, controller_mode, false, final_pose_commanded_left, final_pose_commanded_left, false, final_pose_commanded_left))\n\t// \treturn 0;\n\n\n\tMatrix4d htm_right_desired;\n\thtm_right_desired << \t\t0, -1, 0, 0.679,\n\t\t\t\t\t\t\t\t\t\t\t\t\t0, 0, 1, -0.05,\n\t\t\t\t\t\t\t\t\t\t\t\t\t-1, 0, 0, 0.387,\n\t\t\t\t\t\t\t\t\t\t\t\t\t0, 0, 0, 1;\n\t// htm_right_desired << \t\t0, -1, 0, 0.479,\n\t// \t\t\t\t\t\t\t\t\t\t\t\t0, 0, 1, -0.146,\n\t// \t\t\t\t\t\t\t\t\t\t\t\t-1, 0, 0, 0.387,\n\t// \t\t\t\t\t\t\t\t\t\t\t\t0, 0, 0, 1;\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\n\tMatrix<double,8,1> dq_right_desired=DQoperations::htm2DQ(htm_right_desired);\n\tcontroller_mode=1;\n if (!ManipulationTaskController::go2Pose_withPrecision(dq_right_desired, dq_right_desired, 0.2, controller_mode, true))\n \treturn 0;\n\n\tMatrix4d htm_relative_desired;\n\thtm_relative_desired << -1, 0, 0, -0.15,\n\t\t\t\t\t\t\t\t\t\t\t\t\t0, 1, 0, -0.09,\n\t\t\t\t\t\t\t\t\t\t\t\t\t0, 0, -1, 0.073,\n\t\t\t\t\t\t\t\t\t\t\t\t\t0, 0, 0, 1;\n\tMatrix<double,8,1> dq_relative_desired=DQoperations::htm2DQ(htm_relative_desired);\n\t// controller_mode=4;\n // if (!ManipulationTaskController::go2Pose_withPrecision(dq_right_desired, dq_relative_desired, 0.5, controller_mode, true))\n // \treturn 0;\n\tcontroller_mode=4;\n if (!ManipulationTaskController::go2Pose_withPrecision(dq_right_desired, dq_relative_desired, 0.15, controller_mode, false))\n \treturn 0;\n\tleft_lift_axis.resize(6);\n\tleft_lift_axis << 0, 0, -1, -0.15, -0.09, 0.073;\n\t\n\n\t// bool ManipulationTaskController::doRotationOrTranslation(bool rotation, Matrix<double,8,1> initial_pose, RowVectorXd axis, double initial_vm_jp, double final_vm_jp, double vm_velocity, int controller_mode, bool use_velocity_control, Matrix<double,8,1> pose_right, Matrix<double,8,1> pose_relative, bool vm_relative, Matrix<double,8,1>& final_pose_commanded)\n\tcontroller_mode=4;\n\tif (!ManipulationTaskController::doRotationOrTranslation(true, dq_relative_desired, left_lift_axis, 0, 2.4, 0.2, controller_mode, false, dq_right_desired, dq_relative_desired, true, final_pose_commanded_left))\n\t\treturn 0;\n\n\tROS_INFO(\"Rotating back\");\n\tleft_lift_axis << 0, 0, 1, -0.15, -0.09, 0.073;\n\tif (!ManipulationTaskController::doRotationOrTranslation(true, final_pose_commanded_left, left_lift_axis, 0, 2.4, 0.2, controller_mode, false, dq_right_desired, dq_relative_desired, true, final_pose_commanded_left))\n\t\treturn 0;\n\n\n // hand_cmds_msg.shortcutCmds=1;\n\t// hand_cmds_msg.hand=0;\n\t// ROS_INFO(\"opening right hand\");\n\t// count=0;\n\t// while(count<2)\n\t// {\n\t// \thand_cmds_publisher.publish(hand_cmds_msg);\n\t// \tcount=count+1;\n\t// \tros::Duration(.4).sleep();\t\n\t// }\t\n\t// ros::Duration(3).sleep();\t\n\t// ROS_INFO(\"right hand should be open\");\n\n\t// hand_cmds_msg.shortcutCmds=1;\n\t// hand_cmds_msg.hand=1;\n\t// ROS_INFO(\"opening left hand\");\n\t// count =0;\n\t// while(count<2)\n\t// {\n\t// \thand_cmds_publisher.publish(hand_cmds_msg);\n\t// \tcount=count+1;\n\t// \tros::Duration(.4).sleep();\t\n\t// }\n\t// ros::Duration(3).sleep();\t\t\n\t// ROS_INFO(\"left hand should be open\");\n\t// bool ManipulationTaskController::go2Pose_withPrecision(Matrix<double,8,1> pose_desired_abs, Matrix<double,8,1> pose_desired_rel, double error_threshold, int controller_mode, bool use_velocity_control)\n\n\t// reference_frame=\"/right_hand\";\n\t// controller_mode=4;\n\t// // bool ManipulationTaskController::go2Pose_withPrecision(right_grasp_location, rel_pose_4rotation, 0.08, controller_mode, use_velocity_control)\n\t// if (ManipulationTaskController::go2Pose_withPrecision(right_grasp_location, rel_pose_4rotation, 0.1, controller_mode, use_velocity_control))\n\t// {\n\t// \tROS_INFO(\"Relative pre-rotation configuration achieved.\");\t\n\t// }\t\n\t// else return 0;\n\n\t// controller_mode=5;\n\t// RowVectorXd axis(6);\n\t// axis << -1, 0, 0, 0, 0.4, 0.2;\n\t// if (ManipulationTaskController::doRotationOrTranslation(true, rel_pose_4rotation, axis, 0.0, 1.6, 0.2, controller_mode, false, right_grasp_location, rel_pose_4rotation, true))\n\t\t// if (!ManipulationTaskController::doRotationOrTranslation(true, dq_relative_desired, left_lift_axis, 0, 1.6, 0.02, controller_mode, false, final_pose_commanded_right, dq_relative_desired, true, final_pose_commanded_left))\n\t// \tROS_INFO(\"Rotation achieved.\");\n\t// else return 0;\n\treturn 1;\n}\n\n// void setDesirePoseRelative(int controller_mode, std::string object_name, std::string ref_frame)\n// {\n\n// }\n\nvoid ManipulationTaskController::init_task_controller()\n{\n\tpose_control_client = nh.serviceClient<dq_robotics::BaxterControl>(\"baxterControlService\");\n\trviz_pub = nh.advertise<geometry_msgs::PoseStamped>( \"/rviz_pub\", 0 );\n\thand_cmds_publisher = nh.advertise<ar10_local::ar10_joint_cmds>( \"ar10/desired_joint_cmds\", 0 );\n}\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"baxter_controller\");\n\tros::NodeHandle n;\n\tManipulationTaskController* baxter_task_controller= new ManipulationTaskController();\n\tbaxter_task_controller->ManipulationTaskController::init_task_controller();\n\t\n\tif (baxter_task_controller->ManipulationTaskController::bimanual_pouringTask())\n\t\tROS_INFO(\"bimanual_pouringTask done!\");\n\treturn 1;\n\t// ros::ServiceServer controllerService = n.advertiseService(\"baxterControlService\", &BaxterPoseControlServer::baxterControlServerCallback, baxter_controller);\n\t// baxter_controller->BaxterPoseControlServer::update_manipulator();\n}\n" } ]
32
marvin939/ZombiePygame
https://github.com/marvin939/ZombiePygame
1b49faf46426dd542064924aeda7774a8ce8e656
69ea916918da4a1ea176f73e378c71867de70c1c
27e05ff5915dcc60b821336d69dec80d366ae6dc
refs/heads/master
2021-08-15T21:31:19.744176
2017-11-18T09:25:52
2017-11-18T09:25:52
108,816,977
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5938697457313538, "alphanum_fraction": 0.6045976877212524, "avg_line_length": 36.28571319580078, "blob_id": "7213926244f03daf0e1a3be045ae0352e3994e49", "content_id": "097dcd6145ecc5d50dd06a58145f67d5fc104a17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 77, "num_lines": 35, "path": "/tests/test_utilities.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import math\nimport unittest\nimport utilities\n\n\nclass UtilitiesTestCase(unittest.TestCase):\n def test_unit_circle_angle(self):\n angles = list(range(-20, 20))\n hypotenuse = 5\n assumed_angles = {}\n for angle in angles:\n opposite = hypotenuse * math.sin(angle)\n assumed_angles[angle] = opposite\n\n for angle in angles:\n with self.subTest(angle=angle):\n converted_angle = utilities.unit_angle(angle)\n self.assertLessEqual(converted_angle, math.pi * 2)\n self.assertGreaterEqual(converted_angle, 0)\n opposite = hypotenuse * math.sin(converted_angle)\n self.assertAlmostEqual(assumed_angles[angle], opposite, 10)\n\n def test_unit_circle_angle_bounds(self):\n hypotenuse = 10\n angles = (0, math.pi * 2)\n\n for angle in angles:\n with self.subTest(angle=angle):\n expected_adjacent = hypotenuse\n adjacent = hypotenuse * math.cos(utilities.unit_angle(angle))\n self.assertAlmostEqual(adjacent, expected_adjacent)\n\n expected_opposite = 0\n opposite = hypotenuse * math.sin(utilities.unit_angle(angle))\n self.assertAlmostEqual(opposite, expected_opposite)\n" }, { "alpha_fraction": 0.6263013482093811, "alphanum_fraction": 0.6389040946960449, "avg_line_length": 35.5, "blob_id": "2d6cd83f5381763914442fe0d39d97af4266ae06", "content_id": "f44d7cefaf915cf799bc54bb400fd19dbb38dc47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1825, "license_type": "no_license", "max_line_length": 102, "num_lines": 50, "path": "/tests/test_weapon.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import unittest\nimport utilities\nfrom weapon import *\nfrom game import *\n\n\nclass WeaponSimplifiedTestCase(unittest.TestCase):\n def setUp(self):\n self.fire_rate = 3 # bullets per second\n self.world = World()\n self.owner_location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.owner = GameEntity(self.world, 'dummy', None, self.owner_location)\n self.ammo = 9999\n self.damage = 10\n self.weapon = WeaponSimplified(self.world, self.owner, self.fire_rate, self.damage, self.ammo)\n\n def test_ammunition_decrease_1tick(self):\n self.weapon.process(TICK_SECOND)\n self.weapon.fire()\n self.assertEqual(self.weapon.ammo, self.ammo - 1)\n\n # def test_ammunition_decrease_2sec(self):\n # seconds = 2\n # self.weapon.process(seconds)\n # self.assertEqual(self.weapon.ammo, self.ammo - self.fire_rate * seconds)\n def test_after_2seconds_ready_to_fire(self):\n self.weapon.fire()\n self.assertFalse(self.weapon.ready_to_fire)\n self.weapon.process(2)\n self.weapon.ready_to_fire = True\n pass\n\n def test_bullets_spawned_on_fire(self):\n self.weapon.process(1)\n self.weapon.fire()\n self.assertGreater(self.world.entity_count(), 0)\n\n def test_bullets_damage(self):\n self.weapon.process(1)\n bullets = (e for e in self.world.entities.values() if e.name == 'bullet')\n for b in bullets:\n with self.subTest(bullet=b):\n self.assertEqual(b.damage, self.weapon.damage)\n\n def test_no_ammo(self):\n self.weapon.ammo = 0\n self.weapon.process(TICK_SECOND)\n self.weapon.fire()\n self.assertEqual(self.weapon.ammo, 0)\n self.assertEqual(self.weapon.accumulator, 0) # accumulator = 0, since there is no more ammo\n" }, { "alpha_fraction": 0.5872713327407837, "alphanum_fraction": 0.6009908318519592, "avg_line_length": 29.172412872314453, "blob_id": "1500b532ae5e60faf022bdd159d2064aa2ade47d", "content_id": "eb7bb914e0ceb799a8016e433a8f2918904cc3c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2624, "license_type": "no_license", "max_line_length": 108, "num_lines": 87, "path": "/run.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import pygame\nfrom pygame.locals import *\nfrom game import *\nimport sys\nimport mobs\nfrom manager import ImageManager\nfrom random import randint\n\nimage_dude = None\nTITLE = 'Zombie Defence v0.0.0'\n\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode(SCREEN_SIZE)\n pygame.display.set_caption(TITLE)\n clock = pygame.time.Clock()\n world = World()\n global image_dude\n image_dude = ImageManager('data/images/')\n setup_world(world)\n\n time_passed = 0\n while True:\n if time_passed > 0:\n pygame.display.set_caption('{title} {fps:>.0f} FPS'.format(title=TITLE, fps=1000 / time_passed))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n quit_game()\n\n # Dirty way of attacking the enemy\n lmb, mmb, rmb = pygame.mouse.get_pressed()\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if lmb:\n e = world.get_close_entity('zombie', Vector2(mouse_x, mouse_y), radius=32)\n if e is not None:\n print('zombie found @ {}; state: {}'.format(e.location, e.brain.active_state.name))\n e.hp -= 1\n\n world.process(time_passed)\n\n screen.fill(BLACK)\n world.render(screen)\n\n pygame.display.update()\n time_passed = clock.tick(FPS)\n\ndef quit_game():\n pygame.quit()\n sys.exit()\n\ndef setup_world(world):\n # Create RED sprite for zombie\n zombie_surf = image_dude['zombie.png']\n\n for i in range(20):\n z_width, z_height = zombie_surf.get_size()\n randx = randint(z_width / 2, SCREEN_WIDTH - z_width / 2)\n randy = randint(z_height / 2, SCREEN_HEIGHT - z_height / 2)\n z_location = Vector2(randx, randy)\n zombie = mobs.Zombie(world, zombie_surf, z_location)\n world.add_entity(zombie)\n\n survivor_surf = pygame.Surface((32, 32)).convert()\n survivor_surf.fill(GREEN)\n for i in range(5):\n s_width, s_height = survivor_surf.get_size()\n randx = randint(s_width / 2, SCREEN_WIDTH - s_width / 2)\n randy = randint(s_height / 2, SCREEN_HEIGHT - s_height / 2)\n s_location = Vector2(randx, randy)\n survivor = mobs.Survivor(world, survivor_surf, s_location)\n world.add_entity(survivor)\n\n sentry_gun_surf = image_dude['sentrygun.png']\n w, h = sentry_gun_surf.get_size()\n for i in range(1, 2):\n x, y = (SCREEN_WIDTH * i / 3, SCREEN_HEIGHT / 2)\n sentry_gun = mobs.SentryGun(world, sentry_gun_surf, Vector2(x, y))\n world.add_entity(sentry_gun)\n\n for e in world.entities.values():\n print(e)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6219512224197388, "alphanum_fraction": 0.6355534791946411, "avg_line_length": 31.815383911132812, "blob_id": "4c194d825f727916a62048f12b9b0ed816865d3d", "content_id": "82b3493484d3ac56b8cb3db531e3b38e7f445e3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2132, "license_type": "no_license", "max_line_length": 115, "num_lines": 65, "path": "/demo/demo_turret_rotate.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from encodings.punycode import selective_find\n\nimport pygame\nfrom manager import ImageManager\nfrom game import *\nfrom pygame.locals import *\nfrom pygame.math import Vector2\nfrom mobs import *\n\nimage_manager = None\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode(SCREEN_SIZE)\n clock = pygame.time.Clock()\n global image_manager\n image_manager = ImageManager('../data/images')\n\n world = World()\n sentry_gun = SentryGun(world, image_manager['sentrygun.png'], Vector2(SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0))\n '''\n zombie = Zombie(world, image_manager['zombie.png'], Vector2(*pygame.mouse.get_pos()))\n zombie.hp = math.inf\n zombie.brain = StateMachine() # Reset brain to 0\n '''\n world.add_entity(sentry_gun)\n #world.add_entity(zombie)\n #sentry_gun.target = zombie\n\n time_passed = 0\n while True:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n return\n\n screen.fill((0, 0, 0))\n world.process(time_passed)\n\n mouse_x, mouse_y = mouse_pos = pygame.mouse.get_pos()\n mouse_location = Vector2(mouse_pos)\n #zombie.location = mouse_location\n if any(pygame.mouse.get_pressed()):\n spawn_zombie(world, mouse_location)\n\n # Draw center cross-hair lines:\n pygame.draw.line(screen, (255, 0, 0), (0, SCREEN_HEIGHT/2), (SCREEN_WIDTH, SCREEN_HEIGHT/2))\n pygame.draw.line(screen, (255, 0, 0), (SCREEN_WIDTH / 2, 0), (SCREEN_WIDTH / 2, SCREEN_HEIGHT))\n\n world.render(screen)\n #print(sentry_gun.brain.active_state.name)\n #print('Entity count:', len(world.entities.keys()))\n #print(sentry_gun.turret_angle)\n #print(GameEntity.get_angle(sentry_gun.location, zombie.location))\n pygame.display.update()\n time_passed = clock.tick(FPS)\n\ndef spawn_zombie(world, mouse_location):\n zombie = Zombie(world, image_manager['zombie.png'], mouse_location)\n world.add_entity(zombie)\n print('There are {} entities in this world.'.format(len(world.entities.keys())))\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5391458868980408, "alphanum_fraction": 0.5729537606239319, "avg_line_length": 24.590909957885742, "blob_id": "070263eb9e0eb59f625bb7a625dbfd947081bcb9", "content_id": "b346804ae015179eda2b28e8ebc7350bf4dcfa29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 562, "license_type": "no_license", "max_line_length": 68, "num_lines": 22, "path": "/utilities.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import math\n\n'''\ndef unit_angle(angle):\n \"\"\"Convert radians to unit circle radians' range of 0 to 6.28\"\"\"\n one_rev = math.pi * 2\n if angle > 0:\n return divmod(angle, math.pi * 2)[1]\n if angle < 0:\n angle = divmod(angle, one_rev)[1]\n if angle < 0:\n return angle + one_rev\n return angle\n'''\n\ndef unit_angle(angle):\n \"\"\"Convert radians to unit circle radians' range of 0 to 6.28\"\"\"\n one_rev = math.pi * 2\n angle = divmod(angle, math.pi * 2)[1]\n if angle < 0:\n return angle + one_rev\n return angle" }, { "alpha_fraction": 0.62342768907547, "alphanum_fraction": 0.6297169923782349, "avg_line_length": 23.01886749267578, "blob_id": "600ed937c78e5c6a31251ae28abd7b1369ac43a2", "content_id": "45637ff34b64c700b1a0d13adf58ae72b7b0eea3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1272, "license_type": "no_license", "max_line_length": 85, "num_lines": 53, "path": "/demo/demo_projectile.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import sys\nimport pygame\nfrom pygame.math import Vector2\nfrom game import *\nfrom pygame.locals import *\nfrom weapon import Projectile\n\npygame.init()\nscreen = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption('Projectile object demonstration')\nclock = pygame.time.Clock()\nworld = World()\nCENTER_VEC = Vector2(SCREEN_CENTER)\n\n\ndef main():\n time_passed = 0\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n elif event.type == MOUSEBUTTONDOWN:\n spawn_projectile(CENTER_VEC, event.pos)\n print(world.entity_count())\n\n lmb, mmb, rmb = pygame.mouse.get_pressed()\n if lmb:\n spawn_projectile(CENTER_VEC, event.pos)\n\n world.process(time_passed)\n\n screen.fill(BLACK)\n world.render(screen)\n\n pygame.display.update()\n time_passed = clock.tick(FPS)\n pass\n\n\ndef spawn_projectile(from_pos, to_pos):\n direction = (Vector2(to_pos) - Vector2(from_pos)).normalize()\n print('dir', direction)\n proj = Projectile(world, 'bullet', None, CENTER_VEC, direction, max_distance=100)\n world.add_entity(proj)\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.596433162689209, "alphanum_fraction": 0.605190098285675, "avg_line_length": 31.85614013671875, "blob_id": "b4428d51681f17c1cd1aec0226ad7ebdeb258a7f", "content_id": "e07c406792d4bf368871dc2db4aba0377504a159", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9364, "license_type": "no_license", "max_line_length": 132, "num_lines": 285, "path": "/mobs.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from random import randint\nfrom entity import *\nfrom game import *\nfrom pygame.math import Vector2\nimport math\nimport utilities\nfrom effects import *\nfrom weapon import WeaponSimplified\n\n\nclass Zombie(SentientEntity):\n \"\"\"A Zombie wandering aimlessly\"\"\"\n NAME = 'zombie'\n\n def __init__(self, world, image, location):\n super().__init__(world, self.NAME, image, location)\n self.brain.add_state(ZombieExploreState(self))\n self.brain.add_state(ZombieAttackState(self))\n self.brain.set_state('explore')\n self.MAX_HP = 80\n self.hp = self.MAX_HP\n self.speed = 50\n self.sight = 50\n #self.enemies = [SentryGun.NAME, Survivor.NAME]\n\n def process(self, seconds_passed):\n super().process(seconds_passed)\n\n bullet_entity = self.world.get_close_entity('bullet', self.location, self.rect.width / 2)\n if bullet_entity is not None and bullet_entity.owner.name == SentryGun.NAME:\n self.hp -= bullet_entity.damage\n self.world.remove_entity(bullet_entity)\n\n if self.hp <= 0:\n self.world.remove_entity(self)\n\n def shot(self):\n pass\n\n\nclass ZombieExploreState(State):\n def __init__(self, zombie):\n super().__init__('explore')\n self.entity = zombie\n\n def do_actions(self):\n # Change directions at least every 10th frame\n if randint(0, 100) == 1:\n self.random_destination()\n\n def check_conditions(self):\n if self.entity.hp < self.entity.MAX_HP:\n return 'attack'\n return None\n\n def random_destination(self):\n lower_x_boundary = int(self.entity.image.get_width() / 2)\n lower_y_boundary = int(self.entity.image.get_height() / 2)\n upper_x_boundary = int(SCREEN_WIDTH - lower_x_boundary)\n upper_y_boundary = int(SCREEN_HEIGHT - lower_y_boundary)\n x = randint(lower_x_boundary, upper_x_boundary)\n y = randint(lower_y_boundary, upper_y_boundary)\n self.entity.destination = Vector2(x, y)\n\n\nclass ZombieAttackState(ZombieExploreState):\n \"\"\"Select a random survivor to attack until either is dead.\"\"\"\n\n def __init__(self, zombie):\n super().__init__(zombie)\n self.name = 'attack'\n self.zombie = zombie\n self.has_killed = False\n self.target = None\n self.original_speed = -1\n self.reset_state()\n\n def entry_actions(self):\n #print('entering attack state...')\n self.original_speed = self.zombie.speed\n self.zombie.speed = 200\n self.acquire_target()\n\n def acquire_target(self):\n if self.target is not None:\n return\n target = self.zombie.world.get_close_entity('survivor', self.zombie.location, radius=self.zombie.sight)\n if target is not None:\n self.target = target\n\n def do_actions(self):\n # Keep wandering until a target is found\n if self.target is None:\n if randint(1, 10) == 1:\n self.random_destination()\n self.acquire_target()\n return\n\n self.zombie.destination = self.target.location\n if self.zombie.location.distance_to(self.target.location) < 5:\n self.target.hp -= 1\n if self.target.hp <= 0:\n self.has_killed = True\n\n def check_conditions(self):\n if self.has_killed:\n return 'explore'\n return None\n\n def exit_actions(self):\n self.zombie.hp = self.zombie.MAX_HP # replenish zombie health\n self.reset_state()\n\n def reset_state(self):\n self.zombie.speed = self.original_speed\n self.has_killed = False\n self.target = None\n\n\nclass Survivor(SentientEntity):\n \"\"\"A survivor shooting at zombies\"\"\"\n NAME = 'survivor'\n\n def __init__(self, world, image, location):\n super().__init__(world, self.NAME, image, location)\n self.brain.add_state(SurvivorExploreState(self))\n self.brain.add_state(SurvivorPanicState(self))\n self.brain.set_state('explore')\n self.MAX_HP = 20\n self.hp = self.MAX_HP\n self.speed = 50\n\n def process(self, seconds_passed):\n super().process(seconds_passed)\n if self.hp <= 0:\n self.world.remove_entity(self)\n\n def shot(self):\n pass\n\n\nclass SurvivorExploreState(ZombieExploreState):\n def __init__(self, survivor):\n super().__init__(survivor)\n\n def do_actions(self):\n # Change directions at least every 100th frame\n if randint(0, 100) == 1:\n self.random_destination()\n\n def check_conditions(self):\n zombies = tuple(self.entity.world.entities_with_name('zombie'))\n if self.entity.hp < self.entity.MAX_HP and len(zombies) > 0:\n return 'panic'\n return None\n\n\nclass SurvivorPanicState(SurvivorExploreState):\n def __init__(self, survivor):\n super().__init__(survivor)\n self.name = 'panic'\n self.original_speed = self.entity.speed\n\n def entry_actions(self):\n self.original_speed = self.entity.speed\n self.entity.speed = 300\n\n def do_actions(self):\n # Change directions frequently\n if randint(0, 10) == 1:\n self.random_destination()\n\n def check_conditions(self):\n # Survivor should stop panicking once there are no more zombies...\n zombies = tuple(self.entity.world.entities_with_name('zombie'))\n\n #if not any(zombies):\n if len(zombies) <= 0:\n return 'explore'\n return None\n\n def exit_actions(self):\n self.entity.speed = self.original_speed\n\n\nclass SentryGun(SentientEntity):\n NAME = 'sentry_gun'\n\n def __init__(self, world, image, location):\n super().__init__(world, self.NAME, image, location)\n self.TURRET_ROTATION_RATE_DEGREES = 180\n self.turret_rotation_rate = math.radians(self.TURRET_ROTATION_RATE_DEGREES) # radians per second\n self.__turret_angle = 0\n self.speed = 0\n self.target = None\n self.CONE_OF_VISION_DEGREES = 60\n self.cone_of_vision = math.radians(self.CONE_OF_VISION_DEGREES) # radians\n\n self.brain.add_state(self.ScanEnvironment(self))\n self.brain.add_state(self.AttackTargetState(self))\n self.brain.set_state('scan')\n\n self.weapon = WeaponSimplified(self.world, self, 10, 10, math.inf, spread=10)\n\n def process(self, seconds_passed):\n super().process(seconds_passed)\n if self.target is None:\n self.turret_angle += self.turret_rotation_rate * seconds_passed\n return\n\n self.weapon.process(seconds_passed)\n # # Rotate towards the target\n # angle = SentientEntity.get_angle(self.location, self.target.location)\n # self.turret_angle = angle\n # # attack target\n # self.target.hp -= 1\n #self.world.add_entity(BulletTravelEffect(self.world, self.location, self.target.location, speed=2000, color=(128, 0, 255)))\n\n\n def render(self, surface):\n rotated_image = pygame.transform.rotate(self.image, math.degrees(self.turret_angle))\n x, y = self.location\n w, h = rotated_image.get_size()\n surface.blit(rotated_image, (x - w / 2, y - h / 2))\n\n if self.target is not None:\n pygame.draw.aaline(surface, VIOLET, self.location, self.target.location)\n\n def turret_face_entity(self, entity):\n angle = SentientEntity.get_angle(self.location, entity.location)\n self.turret_angle = angle\n\n @property\n def turret_angle(self):\n return utilities.unit_angle(self.__turret_angle)\n\n @turret_angle.setter\n def turret_angle(self, angle):\n self.__turret_angle = utilities.unit_angle(angle)\n\n class ScanEnvironment(State):\n def __init__(self, turret):\n super().__init__('scan')\n self.turret = turret\n\n def entry_actions(self):\n #self.turret.target = None\n pass\n\n def check_conditions(self):\n \"\"\"Scan surroundings by scanning all enemies around\"\"\"\n half_cone = self.turret.cone_of_vision / 2\n turret_angle = utilities.unit_angle(self.turret.turret_angle)\n\n def is_zombie(entity):\n return entity.name == 'zombie'\n zombies = filter(is_zombie, self.turret.world.entities.values())\n\n for zombie in zombies:\n angle = SentientEntity.get_angle(self.turret.location, zombie.location)\n if turret_angle - half_cone < angle <= turret_angle + half_cone:\n self.turret.target = zombie\n #print('New target:', zombie)\n return 'attack'\n\n class AttackTargetState(State):\n def __init__(self, turret):\n super().__init__('attack')\n self.turret = turret\n\n def do_actions(self):\n # Rotate towards the target\n angle = SentientEntity.get_angle(self.turret.location, self.turret.target.location)\n self.turret.turret_angle = angle\n # attack target\n #self.turret.target.hp -= 1\n self.turret.weapon.fire()\n\n def check_conditions(self):\n if self.turret.target.hp > 0 and self.turret.target is not None:\n return\n return 'scan'\n\n def exit_actions(self):\n self.turret.target = None\n" }, { "alpha_fraction": 0.5680525302886963, "alphanum_fraction": 0.6008752584457397, "avg_line_length": 29.479999542236328, "blob_id": "f22072b3c4329100c4a33524e742a92d9dc8401f", "content_id": "174f6e38840c31eb40bf10af3dea070066b16afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 78, "num_lines": 75, "path": "/game.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import copy\nimport math\nimport pygame\nfrom pygame.math import Vector2\n\nFPS = 60\nSCREEN_WIDTH, SCREEN_HEIGHT = SCREEN_SIZE = (640, 480)\nSCREEN_CENTER = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\nTICK_SECOND = 1000 / FPS / 1000\n\n# Colors\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nVIOLET = (128, 0, 255)\n\n\nclass World:\n def __init__(self):\n self.entities = {}\n self.entity_id = 0\n self.background = pygame.Surface(SCREEN_SIZE) #.convert()\n self.background.fill(BLACK, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))\n\n def add_entity(self, entity):\n \"\"\"Store an entity, give it an id and advance the current entity_id\"\"\"\n self.entities[self.entity_id] = entity\n entity.id = self.entity_id\n self.entity_id += 1\n\n def remove_entity(self, entity):\n if entity.id in self.entities.keys():\n del self.entities[entity.id]\n\n def get(self, entity_id):\n \"\"\"Retrieve an entity by id\"\"\"\n if entity_id in self.entities:\n return self.entities[entity_id]\n else:\n return None\n\n def process(self, time_passed):\n \"\"\"Update every entity in the world\"\"\"\n seconds_passed = time_passed / 1000.0\n entities_copy = copy.copy(self.entities)\n for entity in entities_copy.values():\n entity.process(seconds_passed)\n\n def render(self, surface):\n \"\"\"Draw the background and all the entities\"\"\"\n surface.blit(self.background, (0, 0))\n for entity in self.entities.values():\n entity.render(surface)\n\n def get_close_entity(self, name, location, radius=100):\n \"\"\"Find an entity within the radius of a location\"\"\"\n location = Vector2(*location)\n for entity in self.entities.values():\n if not entity.name == name:\n continue\n distance = location.distance_to(entity.location)\n if distance < radius:\n return entity\n return None\n\n def entities_with_name(self, name):\n def is_entity(entity):\n return entity.name == name\n return filter(is_entity, self.entities.values())\n\n def entity_count(self):\n return len(self.entities.values())" }, { "alpha_fraction": 0.6183696389198303, "alphanum_fraction": 0.623115599155426, "avg_line_length": 37.94565200805664, "blob_id": "437369e313bdd5b960a88da01d76eb5e495ff04b", "content_id": "b9d10d13caf0ed653717fe2aa3176e4bd55c9bd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3582, "license_type": "no_license", "max_line_length": 144, "num_lines": 92, "path": "/effects.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "\"\"\"This is where effects go. eg. Explosions, bullet effects, etc. that disappear in time\"\"\"\n\nfrom entity import GameEntity\nfrom game import *\nimport math\n\n\nclass BulletTravelEffect(GameEntity):\n\n def __init__(self, world, origin, destination, color=YELLOW, speed=1000, length=50, duration=math.inf):\n super().__init__(world, 'bullet_travel', None, origin, destination)\n self.color = color\n self.DURATION = duration\n self.remaining_time = self.DURATION\n self.fx_head = Vector2(self.location)\n self.fx_tail = Vector2(self.location)\n self.fx_length = length\n self.fx_heading = (self.destination - self.location).normalize()\n self.fx_speed = speed\n self.stop_fx_head = False\n\n @property\n def fx_speed(self):\n return self.speed\n\n @fx_speed.setter\n def fx_speed(self, new_value):\n self.speed = new_value\n\n def process(self, seconds_passed):\n if self.fx_head != self.destination:\n head_to_destination_vec = self.destination - self.fx_head\n head_heading = head_to_destination_vec.normalize()\n distance = min(self.speed * seconds_passed, head_to_destination_vec.length())\n self.fx_head += head_heading * distance\n\n if self.fx_tail != self.destination and (self.fx_head.distance_to(self.location) >= self.fx_length or self.fx_head == self.destination):\n tail_to_destination_vec = self.destination - self.fx_tail\n tail_heading = tail_to_destination_vec.normalize()\n distance = min(tail_to_destination_vec.length(), self.speed * seconds_passed)\n self.fx_tail += tail_heading * distance\n\n self.remaining_time -= seconds_passed\n if self.remaining_time <= 0 or (self.fx_tail == self.fx_head == self.destination):\n self.world.remove_entity(self)\n\n def render(self, surface):\n pygame.draw.aaline(surface, self.color, self.fx_tail, self.fx_head)\n\n\nclass ExplosionEffect(GameEntity):\n def __init__(self, world, location, radius, color=YELLOW):\n super().__init__(world, 'explosion_effect', None, location)\n if type(radius) not in (float, int):\n raise TypeError('radius argument must be a float or int!')\n if radius <= 0:\n raise ValueError('radius value must be greater than 0.')\n if type(color) not in (pygame.Color, tuple, list):\n raise TypeError('color argument must be type tuple or pygame.Color!')\n else:\n if type(color) in (tuple, list) and len(color) != 3:\n raise ValueError('color tuple/list must have 3 values (R, G, B)')\n\n self.RADIUS = radius\n self.radius = radius\n self.color = color\n # self.DURATION = duration\n # self.remaining_time = duration\n\n def process(self, seconds_passed):\n self.radius -= seconds_passed * self.RADIUS * 2\n\n # if self.remaining_time <= 0 or self.radius <= 0:\n if self.radius <= 0:\n self.world.remove_entity(self)\n return\n #self.remaining_time -= seconds_passed\n\n def render(self, surface):\n print('surface:', surface)\n print('color:', self.color)\n print('location:', self.location)\n print('radius:', self.radius)\n x = int(self.location.x)\n y = int(self.location.y)\n pygame.draw.circle(surface, self.color, (x, y), int(self.radius))\n\n #pygame.draw.circle(surface, self.color, self.location, int(self.radius))\n #pygame.draw.circle()\n\nclass ShockwaveEffect(GameEntity):\n pass" }, { "alpha_fraction": 0.6312193274497986, "alphanum_fraction": 0.6418962478637695, "avg_line_length": 39.008548736572266, "blob_id": "8a99c40dd172e3f5c3e949a5304bf069e6689e53", "content_id": "426f9489597029d424920cbecf7c92d421ae09a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4683, "license_type": "no_license", "max_line_length": 111, "num_lines": 117, "path": "/tests/test_mobs.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom manager import ImageManager\nimport time\nfrom mobs import *\nfrom game import *\nfrom pygame.math import Vector2\n\n\nclass SentryGunTestCase(unittest.TestCase):\n def setUp(self):\n pygame.init()\n self.screen = pygame.display.set_mode(SCREEN_SIZE)\n self.image_manager = ImageManager('../data/images/')\n self.sentry_gun_image = self.image_manager['sentrygun.png']\n self.world = World()\n self.TICK_SECOND = 33 / 1000\n\n # Create the sentry gun\n x = SCREEN_WIDTH / 2\n y = SCREEN_HEIGHT / 2\n self.sentry_gun = SentryGun(self.world, self.sentry_gun_image, (x, y))\n self.world.add_entity(self.sentry_gun)\n\n # Add a couple of zombies\n '''\n for i in range(10):\n zombie_image = self.image_manager['zombie.png']\n zombie = Zombie(self.world, zombie_image, (randint(0, SCREEN_WIDTH), randint(0, SCREEN_HEIGHT)))\n self.world.add_entity(zombie)\n '''\n\n # Main zombie\n self.zombie = Zombie(self.world, self.image_manager['zombie.png'], (100, 100))\n self.world.add_entity(self.zombie)\n\n self.world.render(self.screen)\n pygame.display.update()\n\n def test_turret_face_target(self):\n self.sentry_gun.turret_face_entity(self.zombie)\n self.sentry_gun.brain.think()\n self.assertEqual(self.sentry_gun.target, self.zombie)\n\n def test_target_acquire(self):\n # Make the turret face the zombie\n angle = SentientEntity.get_angle(self.sentry_gun.location, self.zombie.location)\n self.sentry_gun.turret_angle = angle\n self.sentry_gun.brain.think() # Switch states from scan to face\n print(self.sentry_gun.brain.active_state.name)\n self.assertEqual(self.sentry_gun.target, self.zombie)\n\n @unittest.skip\n def test_rotate_to_target(self):\n self.sentry_gun.target = self.zombie\n self.sentry_gun.brain.set_state('face')\n # Do a loop that will repeatedly call think\n\n '''\n prev_angle = self.sentry_gun.turret_angle\n for i in range(100):\n self.screen.fill((0, 0, 0))\n #with self.subTest(i=i):\n self.sentry_gun.process(self.TICK_SECOND)\n #self.assertNotEqual(self.sentry_gun.turret_angle, prev_angle)\n print('angle:',self.sentry_gun.turret_angle)\n\n #angle_diff = self.sentry_gun.turret_angle - prev_angle\n #self.assertAlmostEqual(angle_diff, self.sentry_gun.turret_rotation_rate * self.TICK_SECOND, 4)\n\n prev_angle = self.sentry_gun.turret_angle\n self.world.render(self.screen)\n pygame.display.update()\n '''\n\n def test_turret_angle(self):\n self.assertAlmostEqual(self.sentry_gun.turret_angle,utilities.unit_angle(self.sentry_gun.turret_angle))\n new_angle = 100\n self.sentry_gun.turret_angle = new_angle\n angle = self.sentry_gun.turret_angle\n self.assertEqual(angle, utilities.unit_angle(new_angle))\n\n def test_entity_angle(self):\n self.assertAlmostEqual(self.sentry_gun.angle, utilities.unit_angle(self.sentry_gun.angle))\n new_angle = 100\n self.sentry_gun.angle = new_angle\n angle = self.sentry_gun.angle\n self.assertEqual(angle, utilities.unit_angle(new_angle))\n\n def test_attack_target(self):\n #self.sentry_gun.face_entity(self.zombie)\n self.sentry_gun.turret_angle = SentientEntity.get_angle(self.sentry_gun.location, self.zombie.location)\n for i in range(10):\n self.sentry_gun.brain.think()\n current_state_name = self.sentry_gun.brain.active_state.name\n #self.assertEqual(current_state_name, 'attack')\n self.assertEqual(self.sentry_gun.target, self.zombie)\n\n # Kill target and check if it returns to scan mode\n self.zombie.hp -= 10000\n self.sentry_gun.brain.think()\n current_state_name = self.sentry_gun.brain.active_state.name\n self.assertEqual(current_state_name, 'scan')\n self.assertIsNone(self.sentry_gun.target) # it should no longer target dead zombie\n\n self.sentry_gun.target = None\n\n # Move the zombie somewhere it cannot be seen by the turret\n self.zombie.hp = 10\n x = self.sentry_gun.location.x + 100\n y = self.sentry_gun.location.y + 100\n self.zombie.location = Vector2(x, y)\n for i in range(10):\n self.sentry_gun.brain.think()\n self.assertIsNone(self.sentry_gun.target) # No target since zombie is behind turret\n current_state_name = self.sentry_gun.brain.active_state.name\n self.assertEqual(current_state_name, 'scan')\n\n\n" }, { "alpha_fraction": 0.6414602398872375, "alphanum_fraction": 0.6536288857460022, "avg_line_length": 43.824676513671875, "blob_id": "8d2f19e00879c41a45ae91b8ac6c67beb0e17e1c", "content_id": "bc950eed2515239ee8295ac1ce8140570bedb8c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6903, "license_type": "no_license", "max_line_length": 116, "num_lines": 154, "path": "/tests/test_entity.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import unittest\nfrom pygame.math import Vector2\nfrom game import *\nfrom entity import *\n\n\nclass GameEntityTestCase(unittest.TestCase):\n def setUp(self):\n self.world = World()\n self.ENTITY_WIDTH, self.ENTITY_HEIGHT = self.ENTITY_SIZE = (32, 32)\n self.entity_image = pygame.Surface(self.ENTITY_SIZE)\n\n x = SCREEN_WIDTH / 2\n y = SCREEN_HEIGHT / 2\n self.entityA = SentientEntity(self.world, 'dummy', self.entity_image, location=Vector2(x, y))\n\n x = SCREEN_WIDTH * 3 / 4\n y = SCREEN_HEIGHT * 3 / 4\n self.entityB = SentientEntity(self.world, 'dummy', self.entity_image, location=Vector2(x, y))\n\n def test_face_entity(self):\n rotation_a = self.entityA.face_entity(self.entityB)\n\n # Manually calculate rotation\n vec_diff = self.entityB.location - self.entityA.location\n angle = utilities.unit_angle(-math.atan2(vec_diff.y, vec_diff.x))\n\n self.assertAlmostEqual(angle, rotation_a, 4)\n self.assertAlmostEqual(angle, self.entityA.angle, 4)\n\n def test_face_vector(self):\n # Do face_vector version:\n rotation_a = self.entityA.face_vector(self.entityB.location)\n\n # Manually calculate rotation\n vec_diff = self.entityB.location - self.entityA.location\n angle = utilities.unit_angle(-math.atan2(vec_diff.y, vec_diff.x))\n\n self.assertAlmostEqual(angle, rotation_a, 4)\n self.assertAlmostEqual(angle, self.entityA.angle, 4)\n\n def test_get_angle(self):\n angle = SentientEntity.get_angle(self.entityA.location, self.entityB.location)\n\n # Manually calculate angle\n vec_diff = self.entityB.location - self.entityA.location\n calc_angle = utilities.unit_angle(-math.atan2(vec_diff.y, vec_diff.x))\n\n self.assertAlmostEqual(calc_angle, angle, 4)\n\n\nclass GameEntityBoundaryRectTestCase(unittest.TestCase):\n def setUp(self):\n self.dummy_surf = pygame.Surface((32, 32))\n self.location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.world = World()\n self.entity = GameEntity(self.world, 'dummy', self.dummy_surf, self.location)\n self.world.add_entity(self.entity)\n\n # What we're interested in:\n self.rect_width = 16 # surface may have 32px width, but entity should really be 16px when performing things\n self.rect_height = 32\n self.boundary_rect = pygame.Rect((0, 0), (self.rect_width, self.rect_height)) # note: x/y don't matter\n self.boundary_rect_offset = Vector2(-self.rect_width / 2, -self.rect_height) # Offset from entity.location\n\n def test_set_boundary_rect(self):\n self.entity.set_rect(self.boundary_rect) # Should ignore rect x and y...\n self.assertEqual(self.entity._GameEntity__rect.width, self.boundary_rect.width)\n self.assertEqual(self.entity._GameEntity__rect.height, self.boundary_rect.height)\n\n def test_set_boundary_rect_with_offset(self):\n self.entity.set_rect(self.boundary_rect, self.boundary_rect_offset) # Should ignore rect x and y...\n self.assertEqual(self.entity._GameEntity__rect, self.boundary_rect)\n self.assertEqual(self.entity._GameEntity__rect_offset, self.boundary_rect_offset)\n\n def test_get_boundary_rect(self):\n self.entity.set_rect(self.boundary_rect)\n rect = self.entity.get_rect()\n\n self.assertEqual(self.entity._GameEntity__rect.width, rect.width)\n self.assertEqual(self.entity._GameEntity__rect.height, rect.height)\n # Because there is no offset, the rect will be centered to location\n self.assertEqual(rect.x, self.entity.location.x - rect.width / 2)\n self.assertEqual(rect.y, self.entity.location.y - rect.height / 2)\n\n def test_get_boundary_rect_with_offsets(self):\n self.entity.set_rect(self.boundary_rect, self.boundary_rect_offset)\n rect = self.entity.get_rect()\n loc = self.entity.location\n brect = self.boundary_rect\n\n self.assertEqual(rect.x, loc.x - brect.width / 2 + self.boundary_rect_offset.x)\n self.assertEqual(rect.y, loc.y - brect.height / 2 + self.boundary_rect_offset.y)\n\n def test_get_boundary_rect_no_rect_height_width_only(self):\n \"\"\"Test the get_rect() method to return the entity's image rect instead of rect when there is none assigned.\n This test will not concern the entity's rectangle's X/Y coordinates.\"\"\"\n rect = self.entity.get_rect()\n image_rect = self.entity.image.get_rect()\n\n self.assertEqual(rect.width, image_rect.width)\n self.assertEqual(rect.height, image_rect.height)\n\n def test_get_boundary_rect_no_rect(self):\n \"\"\"Continuation of above, but considers x and y attributes\"\"\"\n rect = self.entity.get_rect()\n image_rect = self.entity.image.get_rect()\n\n self.assertEqual(rect.x, self.location.x - image_rect.width / 2)\n self.assertEqual(rect.y, self.location.y - image_rect.height / 2)\n\n\nclass SentientEntitySidesTestCase(unittest.TestCase):\n def setUp(self):\n self.world = World()\n self.good_guy_name = 'good_guy'\n self.bad_guy_name = 'bad_fuy'\n self.other_bad_guy_name = 'bad_man'\n\n self.good_guy = SentientEntity(self.world, self.good_guy_name, None, Vector2(100, 100), speed=0,\n enemies=[self.bad_guy_name, self.other_bad_guy_name])\n self.bad_guy = SentientEntity(self.world, self.bad_guy_name, None, Vector2(150, 140), speed=0,\n enemies=[self.good_guy_name])\n self.bad_guy2 = SentientEntity(self.world, self.other_bad_guy_name, None,\n Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2), speed=0,\n enemies=[self.good_guy_name])\n self.world.add_entity(self.good_guy)\n self.world.add_entity(self.bad_guy)\n self.world.add_entity(self.bad_guy2)\n\n def test_get_enemy_entity(self):\n enemy = self.good_guy.get_close_enemy(radius=100)\n self.assertIsNotNone(enemy)\n self.assertIn(enemy.name, self.good_guy.enemies)\n\n def test_get_enemy_entity_other_bad_guy(self):\n\n # Replace other bad guy's location with first bad guys', and put the first far away\n temp_loc = self.bad_guy.location\n self.bad_guy.location = Vector2(*SCREEN_SIZE)\n self.bad_guy2.location = temp_loc\n\n enemy = self.good_guy.get_close_enemy(radius=100)\n self.assertIsNotNone(enemy)\n self.assertIn(enemy.name, self.good_guy.enemies)\n self.assertEqual(enemy.name, self.other_bad_guy_name)\n\n def test_get_enemy_entity_beyond_radius(self):\n self.good_guy.location = (0, 0)\n self.bad_guy.location = Vector2(*SCREEN_SIZE)\n self.bad_guy2.location = Vector2(*SCREEN_SIZE)\n\n enemy = self.good_guy.get_close_enemy(radius=100)\n self.assertIsNone(enemy)\n" }, { "alpha_fraction": 0.7374830842018127, "alphanum_fraction": 0.748308539390564, "avg_line_length": 28.600000381469727, "blob_id": "6abcc699a86aa0dee8ef88d1e9029b2c30192829", "content_id": "8ff2e90011787ba0c9886cd0849c0131a769b3c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 739, "license_type": "no_license", "max_line_length": 127, "num_lines": 25, "path": "/readme.md", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "# Zombie Pygame\nMy attempt at creating a top down zombie shooter game, test driven development style!\n\n### Current features\n* State machine implementation (with help from Will McGugan's pygame book)\n* Basic laser effects (used demo folder)\n* Bullet weapons\n* Massive amount of tests. Some tests are missing however, like StateMachine and State class since I just copied from the book.\n\n### Missing features\n* Player control\n* Proper textures\n* Animations\n\n### Demo video\n[![run.py demo](http://i3.ytimg.com/vi/PQMbPXDseP4/maxresdefault.jpg)](https://youtu.be/PQMbPXDseP4)\n\nAbove is `run.py` There are more in the `demo` folder.\n\n### Requires:\n* pygame v1.9.3\n* python 3.5\n* Pycharm IDE\n\nThese are just what I use since I have them on my computer" }, { "alpha_fraction": 0.5995607376098633, "alphanum_fraction": 0.6039531230926514, "avg_line_length": 31.129411697387695, "blob_id": "5e6ce68b2c8f5d2e1f93170ee7bf9bc495565b60", "content_id": "c1ba9beb099dc762f981ea28cecde24f5ca9180c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5464, "license_type": "no_license", "max_line_length": 119, "num_lines": 170, "path": "/entity.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from pygame.math import Vector2\nimport math\nimport pygame\nimport utilities\n#from mobs import *\n\n\nclass GameEntity:\n \"\"\"GameEntity that has states\"\"\"\n def __init__(self, world, name, image, location=None, destination=None, speed=0):\n self.world = world\n self.name = name\n self.image = image\n self.location = Vector2(location) if location is not None else Vector2(0, 0)\n self.destination = Vector2(destination) if destination is not None else Vector2(0, 0)\n self.speed = speed\n self.id = 0\n self.__angle = 0.0\n self.__rect = None # represents the boundary rectangle\n self.__rect_offset = None\n self.render_offset = None # how much to offset the image by (relative to location) when rendering to a surface\n\n @property\n def angle(self):\n return utilities.unit_angle(self.__angle)\n\n @angle.setter\n def angle(self, angle):\n self.__angle = utilities.unit_angle(angle)\n\n def render(self, surface):\n if self.image is None:\n return\n\n x, y = 0, 0\n if self.render_offset is not None:\n x = self.location.x + self.render_offset.x\n y = self.location.y + self.render_offset.y\n else:\n x, y = self.location\n w, h = self.image.get_size()\n surface.blit(self.image, (x - w / 2, y - h / 2))\n\n def process(self, seconds_passed):\n if self.speed > 0 and self.location != self.destination:\n vec_to_destination = self.destination - self.location\n distance_to_destination = vec_to_destination.length()\n heading = vec_to_destination.normalize()\n travel_distance = min(distance_to_destination, seconds_passed * self.speed)\n self.location += travel_distance * heading\n\n def face_vector(self, vector):\n \"\"\"Face the entity towards the vector's location, set the new angle, and return it\"\"\"\n vec_diff = vector - self.location\n new_angle = self.get_angle(self.location, vector)\n self.angle = new_angle\n return new_angle\n\n def face_entity(self, entity):\n \"\"\"Face the entity towards the other entity's location, set the new angle, and return it\"\"\"\n return self.face_vector(entity.location)\n\n @staticmethod\n def get_angle(vectora, vectorb):\n \"\"\"Retrieve the angle (radians) between vectora and vectorb, where vectorb is the end point, and\n vectora, the starting point\"\"\"\n vec_diff = vectorb - vectora\n #return -math.atan2(vec_diff.y, vec_diff.x)\n return utilities.unit_angle(-math.atan2(vec_diff.y, vec_diff.x))\n\n def set_rect(self, rect, vec_offset=None):\n self.__rect = rect\n if vec_offset is not None:\n self.__rect_offset = vec_offset\n\n def get_rect(self):\n if self.__rect is not None:\n new_rect = pygame.Rect(self.__rect)\n new_rect.center = self.location\n if self.__rect_offset is not None:\n new_rect.x += self.__rect_offset.x\n new_rect.y += self.__rect_offset.y\n return new_rect\n\n img_rect = self.image.get_rect()\n img_rect.center = self.location\n return img_rect\n\n @property\n def rect(self):\n return self.get_rect()\n\n\nclass SentientEntity(GameEntity):\n \"\"\"GameEntity that has states, and is able to think...\"\"\"\n\n def __init__(self, world, name, image, location=None, destination=None, speed=0, friends=None, enemies=None):\n super().__init__(world, name, image, location, destination, speed)\n self.friends = friends\n self.enemies = enemies\n self.brain = StateMachine()\n\n def process(self, seconds_passed):\n self.brain.think()\n super().process(seconds_passed)\n\n def get_close_enemy(self, radius=100):\n for enemy in self.enemies:\n e = self.world.get_close_entity(enemy, self.location, radius)\n if e is not None:\n return e\n return None\n\n\nclass State:\n\n def __init__(self, name):\n self.name = name\n\n def do_actions(self):\n pass\n\n def check_conditions(self):\n pass\n\n def entry_actions(self):\n pass\n\n def exit_actions(self):\n pass\n\n\nclass StateMachine:\n\n def __init__(self):\n self.states = {}\n self.active_state = None\n\n def add_state(self, state):\n \"\"\"Add a state to the internal dictionary\"\"\"\n self.states[state.name] = state\n\n def think(self):\n \"\"\"Let the current state do it's thing\"\"\"\n\n # Only continue if there is an\n if self.active_state is None:\n return\n\n # Perform the actions of the active state and check conditions\n self.active_state.do_actions()\n\n new_state_name = self.active_state.check_conditions()\n if new_state_name is not None:\n self.set_state(new_state_name)\n\n def set_state(self, new_state_name):\n \"\"\"Change state machine's active state\"\"\"\n\n # perform any exit actions of the current state\n if self.active_state is not None:\n self.active_state.exit_actions()\n\n if new_state_name not in self.states.keys():\n print('Warning! \"{}\" not in self.states...'.format(new_state_name))\n return\n\n # Switch state and perform entry actions of new state\n self.active_state = self.states[new_state_name]\n self.active_state.entry_actions()\n\n\n" }, { "alpha_fraction": 0.5908163189888, "alphanum_fraction": 0.6117346882820129, "avg_line_length": 33.403507232666016, "blob_id": "5d37d765ba46ee4355b72b4478a352fba25d671e", "content_id": "c8dbb538ac391848dc0173edf6afe1f408b06996", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1960, "license_type": "no_license", "max_line_length": 120, "num_lines": 57, "path": "/demo/demo_rotate_towards_mouse.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import pygame\nfrom manager import ImageManager\nfrom game import *\nfrom pygame.locals import *\nfrom pygame.math import Vector2\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode(SCREEN_SIZE)\n clock = pygame.time.Clock()\n image_manager = ImageManager('../data/images')\n\n sprite_image = image_manager['sentrygun.png']\n sprite_location = Vector2(SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0)\n circles = []\n print(sprite_location)\n\n time_passed = 0\n while True:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n return\n\n screen.fill((0, 0, 0))\n\n mouse_x, mouse_y = mouse_pos = pygame.mouse.get_pos()\n mouse_location = Vector2(mouse_pos)\n vec_diff = mouse_location - sprite_location\n angle = -math.atan2(vec_diff.y, vec_diff.x) # atan2's result is inverted controls, so * -1\n #print(angle)\n rotated_image = pygame.transform.rotate(sprite_image, math.degrees(angle))\n rotated_x = (SCREEN_WIDTH - rotated_image.get_width()) / 2.0\n rotated_y = (SCREEN_HEIGHT - rotated_image.get_height()) / 2.0\n\n # Draw center cross-hair lines:\n pygame.draw.line(screen, (255, 0, 0), (0, SCREEN_HEIGHT/2), (SCREEN_WIDTH, SCREEN_HEIGHT/2))\n pygame.draw.line(screen, (255, 0, 0), (SCREEN_WIDTH / 2, 0), (SCREEN_WIDTH / 2, SCREEN_HEIGHT))\n\n if pygame.mouse.get_pressed()[0]:\n circles += [mouse_pos]\n\n for circle_pos in circles:\n pygame.draw.circle(screen, (0, 255, 0), circle_pos, 5)\n\n screen.blit(sprite_image, mouse_pos)\n screen.blit(rotated_image, (rotated_x, rotated_y))\n # Why is it the angle offset!?\n\n #pygame.display.update(pygame.Rect(rotated_x, rotated_y, rotated_image.get_width(), rotated_image.get_height()))\n pygame.display.update()\n time_passed = clock.tick(FPS)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6073932647705078, "alphanum_fraction": 0.6073932647705078, "avg_line_length": 32.34042739868164, "blob_id": "5c42fd1c1aaaf7271798a816fa0a9209bd5bcabb", "content_id": "df5d2a10bdc5a74d3e86292c417a896af5a436e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 108, "num_lines": 47, "path": "/manager.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import os\nimport pygame\n\nfrom errors import *\n\n\nclass ImageManager:\n \"\"\"The thing that manages images\"\"\"\n\n def __init__(self, dir='.'):\n self.image_directory = os.path.abspath(dir)\n self.surf_dict = {}\n\n if pygame.display.get_surface() is None:\n raise ScreenNotInitialized('ImageManager instances require a screen to be already initialised!')\n\n def __getitem__(self, item):\n \"\"\"Load the image even though it has not bee loaded before\"\"\"\n\n surface = None\n try:\n surface = self.surf_dict[item]\n except KeyError:\n # Image has not been loaded before\n if not isinstance(item, str):\n raise TypeError('argument item ({}) must be str!'.format(type(item)))\n\n image_path = self.__get_image_path(item)\n if not os.path.exists(image_path):\n raise FileNotFoundError('Path: {}'.format(image_path))\n\n # Load the image and store into dictionary\n surface = pygame.image.load(image_path).convert_alpha()\n self.surf_dict[item] = surface\n\n return surface\n\n def __get_image_path(self, image_name):\n return os.path.join(self.image_directory, image_name)\n\n def __setitem__(self, image_name, surface):\n \"\"\"Manually name an image surface (key-value pair)\"\"\"\n if not isinstance(surface, pygame.Surface):\n raise TypeError('surface argument ({}) must be a pygame.Surface type!'.format(surface))\n\n self.surf_dict[image_name] = surface\n return surface\n\n\n" }, { "alpha_fraction": 0.559183657169342, "alphanum_fraction": 0.5675617456436157, "avg_line_length": 30.45945930480957, "blob_id": "2e47798ce182d92b150ebd818b8a20cb4a800274", "content_id": "8adbe65d2c7a6c52021ca4c928b39ba25b4e8ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4655, "license_type": "no_license", "max_line_length": 125, "num_lines": 148, "path": "/weapon.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from random import *\nfrom entity import *\nfrom game import *\n\n'''\nself.pistol = Weapon(self.weap_damage, \\\n self.weap_clip, \\\n self.weap_reload_rate, \\\n self.weap_fire_rate, \\\n self.weap_spread, \\\n self.weap_rounds_per_shot, \\\n self.weap_projectile_type, \\\n self.weap_projectile_count)\n'''\n\n\nclass Weapon:\n def __init__(self,\n damage=1,\n clip=1,\n max_ammo=90,\n reload_rate=1,\n fire_rate=1,\n spread=0,\n rounds_per_shot=1,\n proj_type=None,\n num_proj=1,\n proj_speed=100,\n warhead=None,\n factory=None,\n reload_entire_clip=True,\n projectile_factory=None):\n\n if factory is not None:\n factory(self)\n\n self.DAMAGE = damage\n self.clip = clip\n self.MAX_CLIP = clip\n self.MAX_AMMO = max_ammo\n self.RELOAD_RATE = reload_rate\n self.FIRE_RATE = fire_rate\n self.SPREAD = spread\n self.ROUNDS_PER_SHOT = rounds_per_shot\n self.PROJECTILE_TYPE = proj_type\n self.NUM_PROJECTILES = num_proj\n self.PROJECTILE_SPEED = proj_speed\n self.WARHEAD=warhead\n self.ready = True\n self.reload_entire_clip = reload_entire_clip\n\n def shoot_angled(self, world, angle):\n \"\"\"Shoot the projectiles at an angle, and add them into the world\"\"\"\n pass\n\n def process(self, seconds_passed):\n if self.clip == 0:\n # reload\n self.reload(seconds_passed)\n\n if self.is_ready():\n pass\n\n def reload(self, seconds_passed):\n self.clip += self.RELOAD_RATE * seconds_passed\n # if self.clip > self.MAX_CLIP:\n\n\nclass ProjectileFactory:\n \"\"\"Class that gives a new projectile object each time it is called.\n An instance of it will reside in a weapon object.\"\"\"\n def __init__(self, ptype, speed, image, warhead):\n pass\n\n\nclass Projectile(GameEntity):\n\n def __init__(self, world, name, image, location, direction_vec, speed=200, damage=0, max_distance=300, owner=None):\n super().__init__(world, name, image, location, None, speed)\n self.direction = direction_vec\n self.damage = damage\n self.origin = location\n self.max_distance = max_distance\n self.owner = owner\n\n def process(self, seconds_passed):\n if self.location.distance_to(self.origin) >= self.max_distance:\n self.world.remove_entity(self)\n return\n self.location += self.direction * self.speed * seconds_passed\n\n def render(self, surface):\n if self.image is not None:\n super().render(surface)\n return\n pygame.draw.circle(surface, YELLOW, (int(self.location.x), int(self.location.y)), 1)\n\n @staticmethod\n def factory(type_name, world, owner, weapon):\n angle = owner.angle if not hasattr(owner, 'turret_angle') else owner.turret_angle\n angle *= -1 # Multiply by -1 to fix direction vector\n direction = Vector2(1, 0).rotate(math.degrees(angle) + uniform(-weapon.spread/2, weapon.spread/2))\n\n if type_name == 'bullet':\n return Projectile(world, 'bullet', None, owner.location, direction, speed=500, damage=weapon.damage, owner=owner)\n raise ValueError('Unknown projectile type name {}'.format(type_name))\n\n\nclass Warhead:\n pass\n\n\nclass WeaponSimplified(SentientEntity):\n \"\"\"A simple weapon that fires without reload; just a delay in between.\"\"\"\n\n def __init__(self, world, owner, fire_rate, damage, ammo, spread=0):\n self.world = world\n self.owner = owner\n self.fire_rate = fire_rate\n self.damage = damage\n self.ammo = ammo\n self.accumulator = 0\n self.spread = spread\n self.ready_to_fire = True\n\n def render(self, surface):\n return\n\n def process(self, seconds_passed):\n if self.ammo <= 0:\n self.accumulator = 0\n return\n if self.ready_to_fire:\n return\n\n if self.accumulator >= 1 / self.fire_rate:\n self.accumulator = 0\n self.ready_to_fire = True\n self.accumulator += seconds_passed\n\n def fire(self):\n if not self.ready_to_fire or self.ammo <= 0:\n return\n\n self.ready_to_fire = False\n bullet = Projectile.factory('bullet', self.world, self.owner, self)\n self.world.add_entity(bullet)\n self.ammo -= 1" }, { "alpha_fraction": 0.5952184796333313, "alphanum_fraction": 0.6112943291664124, "avg_line_length": 28.240962982177734, "blob_id": "d3abbdd7d8179a87976d44df433e27d670f2a17e", "content_id": "4f7735bcd6c44542cfafd704dc93001100d03a00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2426, "license_type": "no_license", "max_line_length": 89, "num_lines": 83, "path": "/demo/demo_weapon.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import sys\nimport pygame\nfrom pygame.math import Vector2\nfrom game import *\nfrom pygame.locals import *\nfrom weapon import Projectile, WeaponSimplified\nfrom entity import GameEntity\nimport utilities\n\npygame.init()\nscreen = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption('Projectile object demonstration')\nclock = pygame.time.Clock()\nworld = World()\nCENTER_VEC = Vector2(SCREEN_CENTER)\nAMMO = 10000\nSPREAD = 10\nFIRE_RATE = 10\n\ndef main():\n time_passed = 0\n player = GameEntity(world, 'player', None, CENTER_VEC)\n world.add_entity(player)\n\n weapon = WeaponSimplified(world, player, FIRE_RATE, 0, AMMO, spread=SPREAD)\n\n ready2fire_surf = pygame.Surface((32, 32))\n #font_obj = pygame.SysFont()\n #print('\\n'.join(pygame.font.get_fonts()))\n font_obj = pygame.font.SysFont('freesans', 32)\n\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n elif event.type == MOUSEBUTTONDOWN:\n pass\n #print(world.entity_count())\n elif event.type == MOUSEMOTION:\n angle = GameEntity.get_angle(player.location, Vector2(event.pos))\n player.angle = angle\n elif event.type == KEYDOWN:\n if event.key == K_r:\n weapon.ammo = AMMO\n\n seconds_passed = time_passed / 1000\n\n lmb, mmb, rmb = pygame.mouse.get_pressed()\n if any((lmb, mmb, rmb)):\n weapon.fire()\n\n world.process(time_passed)\n weapon.process(seconds_passed)\n\n screen.fill(BLACK)\n world.render(screen)\n ready2fire_surf.fill(GREEN if weapon.ready_to_fire else RED)\n screen.blit(ready2fire_surf, (0, 0))\n ready2fire_text = font_obj.render('ready' if weapon.ready_to_fire else 'loading',\n True,\n WHITE)\n screen.blit(ready2fire_text, (32, 0))\n\n pygame.display.set_caption('Weapon demo; Ammo: {ammo}'.format(ammo=weapon.ammo))\n\n pygame.display.update()\n time_passed = clock.tick(FPS)\n pass\n\n\n# def spawn_projectile(from_pos, to_pos):\n# direction = (Vector2(to_pos) - Vector2(from_pos)).normalize()\n# proj = Projectile(world, 'bullet', None, CENTER_VEC, direction, max_distance=100)\n# world.add_entity(proj)\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5416268110275269, "alphanum_fraction": 0.5622009634971619, "avg_line_length": 24.5, "blob_id": "09be361ef525de154acfb2efa287092d9bae2e11", "content_id": "806da3a7fcb297ddb72a762a6bdaeb88a5551ee7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "no_license", "max_line_length": 90, "num_lines": 82, "path": "/demo/demo_effects.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import time\nimport sys\nimport pygame\nfrom game import *\nfrom effects import *\nfrom pygame.locals import *\nfrom manager import ImageManager\n\nGREEN = (0, 255, 0)\nFPS = 30\n\n\"\"\"\nbullet_travel = BulletTravelEffect(world, Vector2(0, 0), Vector2(320, 240))\nworld.add_entity(bullet_travel)\n\"\"\"\n\nimage_dude = None\n\ndef main():\n pygame.init()\n clock = pygame.time.Clock()\n screen = pygame.display.set_mode((640, 480))\n world = World()\n\n global image_dude\n image_dude = ImageManager('../data/images')\n\n time_passed = 0\n while True:\n #print(time_passed)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == MOUSEBUTTONDOWN:\n print(event)\n if event.button is 1:\n spawn_effect(world)\n print('fx added')\n elif event.type == KEYDOWN:\n if event.key == K_e:\n spawn_explosion_effect(world)\n elif event.key == K_i:\n # Show entities\n print(world.entities.values())\n\n\n if pygame.mouse.get_pressed()[2]:\n spawn_effect(world)\n\n # if pygame.mouse.get_pressed()[3]:\n # print('world entities:')\n # print(world.entities.values())\n\n world.process(time_passed)\n\n screen.fill((0, 0, 0))\n world.render(screen)\n # pygame.draw.circle(screen, RED, pygame.mouse.get_pos(), 5)\n\n pygame.display.update()\n\n # simulate FPS drop\n #time.sleep(0.2)\n\n time_passed = clock.tick(FPS)\n\n\ndef spawn_effect(world):\n bullet_fx = BulletTravelEffect(world, Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2),\n Vector2(*pygame.mouse.get_pos()), GREEN, speed=500)\n world.add_entity(bullet_fx)\n\n\ndef spawn_explosion_effect(world):\n explosion = ExplosionEffect(world, Vector2(*pygame.mouse.get_pos()), 50, color=VIOLET)\n world.add_entity(explosion)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6607270240783691, "alphanum_fraction": 0.6771204471588135, "avg_line_length": 34.07500076293945, "blob_id": "feca18e4d3263cb072bc73660f63eeb4d163bd73", "content_id": "67d978dcec86caa753e4162f1308364cb626af5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1403, "license_type": "no_license", "max_line_length": 155, "num_lines": 40, "path": "/tests/test_projectile.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from weapon import Weapon, Projectile, Warhead\nfrom unittest import TestCase\nfrom game import *\nimport utilities\n\n\nclass DestinationProjectileTestCase(TestCase):\n\n def setUp(self):\n self.warhead = None\n self.speed = 100\n self.world = World()\n self.location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.destination = Vector2(SCREEN_WIDTH, SCREEN_HEIGHT)\n self.projectile = Projectile(self.world, None, self.location, self.destination, self.speed, self.warhead)\n self.world.add_entity(self.projectile)\n\n def test_instance(self):\n pass\n\n\nclass AngledProjectileTestCase(TestCase):\n\n def setUp(self):\n self.speed = 100\n self.world = World()\n self.location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.angle = utilities.unit_angle(math.radians(300))\n self.direction = Vector2(1, 0).rotate(self.angle)\n self.max_distance = 200\n self.projectile = Projectile(self.world, 'bullet', None, self.location, self.direction, speed=self.speed, damage=0, max_distance=self.max_distance)\n self.world.add_entity(self.projectile)\n\n def test_instance(self):\n pass\n\n def test_max_distance_remove_from_world(self):\n seconds = self.max_distance / self.speed\n self.projectile.process(seconds)\n self.assertNotIn(self.projectile, self.world.entities.values())\n" }, { "alpha_fraction": 0.6090750694274902, "alphanum_fraction": 0.6154741048812866, "avg_line_length": 34.1020393371582, "blob_id": "a139a68187f2bea3db636864700a149317f4369b", "content_id": "94a06f364a3c6004d5d40c0c0cc694f0d11aa0f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1719, "license_type": "no_license", "max_line_length": 81, "num_lines": 49, "path": "/tests/test_world.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from mobs import *\nfrom random import randint, random\nimport unittest\nfrom game import *\nimport pygame\n\nNUM_ZOMBIES = 10\nNUM_SURVIVORS = 5\nNUM_SENTRY_GUNS = 2\n\nclass WorldTestCase(unittest.TestCase):\n\n def setUp(self):\n self.world = World()\n dummy_surface = pygame.Surface((16, 16))\n w, h = dummy_surface.get_size()\n\n # Add zombies\n for i in range(NUM_ZOMBIES):\n x = random() * SCREEN_WIDTH\n y = random() * SCREEN_HEIGHT\n zombie = Zombie(self.world, dummy_surface, Vector2(x, y))\n self.world.add_entity(zombie)\n\n # Add survivors\n for i in range(NUM_SURVIVORS):\n x = random() * SCREEN_WIDTH\n y = random() * SCREEN_HEIGHT\n survivor = Survivor(self.world, dummy_surface, Vector2(x, y))\n self.world.add_entity(survivor)\n\n # Add sentry guns\n for i in range(NUM_SENTRY_GUNS):\n x = random() * SCREEN_WIDTH\n y = random() * SCREEN_HEIGHT\n self.sentry_gun = SentryGun(self.world, dummy_surface, Vector2(x, y))\n self.world.add_entity(self.sentry_gun)\n\n def test_list_all_entities_with_name(self):\n zombies = tuple(self.world.entities_with_name('zombie'))\n survivors = tuple(self.world.entities_with_name('survivor'))\n sentry_guns = tuple(self.world.entities_with_name('sentry_gun'))\n self.assertEqual(len(zombies), NUM_ZOMBIES)\n self.assertEqual(len(survivors), NUM_SURVIVORS)\n self.assertEqual(len(sentry_guns), NUM_SENTRY_GUNS)\n\n def test_get_close_entity_type_zombie(self):\n z = self.world.get_close_entity('zombie', SCREEN_CENTER)\n self.assertEqual(z.name, 'zombie')" }, { "alpha_fraction": 0.6361818909645081, "alphanum_fraction": 0.6524237990379333, "avg_line_length": 35.390907287597656, "blob_id": "b79b24f1fd4c14892a38e0231d732cfad769277b", "content_id": "c4e3ad2384e2c9d067b145ff8bb0719d68c56d65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4002, "license_type": "no_license", "max_line_length": 104, "num_lines": 110, "path": "/tests/test_image_manager.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import unittest\nfrom manager import ImageManager\nimport pygame\nimport os\nfrom errors import *\n\nclass ImageManagerTestCaseA(unittest.TestCase):\n\n def test_try_making_imagemanager(self):\n \"\"\"ImageManager should raise an error if the screen surface has not been initialised yet\"\"\"\n\n with self.assertRaises(ScreenNotInitialized):\n imagemanager = ImageManager()\n\nclass ImageManagerTestCaseB(unittest.TestCase):\n\n def setUp(self):\n # Initialise required stuff\n pygame.init()\n self.screen = pygame.display.set_mode((640, 480))\n\n self.path = '../data/images/'\n self.imagedude = ImageManager(self.path) # Load images from data/images/\n\n self.bg = pygame.image.load(os.path.join(self.path, 'backgroundA.jpg')).convert() # Load image\n self.bg_width, self.bg_height = self.bg.get_size()\n self.imagedude['backgroundB.jpg'] = self.bg # Add image\n\n def test_try_making_imagemanager(self):\n \"\"\"ImageManager should raise an error if the screen surface has not been initialised yet\"\"\"\n pygame.quit()\n pygame.init()\n with self.assertRaises(ScreenNotInitialized):\n imagemanager = ImageManager()\n\n def test_add_image_invalid_value(self):\n with self.assertRaises(TypeError):\n self.imagedude['abc'] = '123'\n self.imagedude['edf'] = 123\n\n def test_add_images(self):\n # Add image\n image_name = 'bg'\n self.imagedude[image_name] = self.bg\n self.assertEqual(self.imagedude[image_name], self.bg)\n\n def test_get_image(self):\n bg = self.imagedude['backgroundB.jpg']\n self.assertEqual(bg, self.bg)\n\n @unittest.skip\n def test_get_image_invalid_type(self):\n with self.assertRaises(TypeError):\n surf = self.imagedude[123123]\n\n def test_get_image_not_found(self):\n with self.assertRaises(FileNotFoundError):\n surf = self.imagedude['filenotfoundimage.png']\n\n\n def test_automatic_load_image(self):\n \"\"\"Load an image that has not been loaded before\"\"\"\n\n # Make sure that the requested surface is not none\n background = self.imagedude['backgroundA.jpg']\n self.assertIsNotNone(background)\n\n # Test that the image was actually stored into the dictionary\n self.assertEqual(background, self.imagedude['backgroundA.jpg'])\n\n # Compare the dimensions of the loaded images\n bgB = pygame.image.load(os.path.join(self.path, 'backgroundA.jpg')).convert()\n background_size = background.get_size()\n bgB_size = bgB.get_size()\n\n self.assertEqual(background_size, bgB_size)\n\n # Test loading image that doesn't exist.\n with self.assertRaises(FileNotFoundError):\n image = self.imagedude['asdflkjoiuqeioqwe.jog']\n\n # Make sure that loading images with invalid image filename types is illegal\n with self.assertRaises(TypeError):\n invalid = self.imagedude[123456]\n invalid = self.imagedude[123456.3]\n\n def test_transparent_image(self):\n # Test loading an image with alpha\n transparent_image = self.imagedude['transparent.png']\n pixel = transparent_image.get_at((10, 10))\n self.assertNotEqual(pixel, (0, 0, 0))\n self.assertNotEqual(pixel, (255, 255, 255))\n self.assertEqual(transparent_image.get_at((70, 70)), (0, 0, 0)) # BLACK\n self.assertEqual(transparent_image.get_at((35, 70)), (149, 0, 186)) # Arbitrary purple\n\n def test_pre_cache_all(self):\n pass\n\n def test_directory(self):\n imagedude_path = self.imagedude.image_directory\n #print(imagedude_path)\n self.assertEqual(imagedude_path, os.path.abspath(self.path))\n\n all_filesA = tuple((entry.name for entry in os.scandir(imagedude_path)))\n all_filesB = tuple((entry.name for entry in os.scandir(self.path)))\n self.assertTupleEqual(all_filesA, all_filesB)\n\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.6837607026100159, "avg_line_length": 27.393939971923828, "blob_id": "22907ab4291c6b97d37843363860395a0f8cf78c", "content_id": "7b2a61c4af3a7cef0b4d43807fd584828f449780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 936, "license_type": "no_license", "max_line_length": 100, "num_lines": 33, "path": "/demo/demo_image_manager.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from manager import ImageManager\nimport sys\nimport os\nimport pygame\nimport time\n\n# Add 1-dir-up to path (contains manager.py, and errors.py)\n# sys.path += [os.path.join(os.getcwd(), '..')]\n'''No need to do; just change the working directory of the file @ Run->Edit Configurations...\nDon't forget to change relative paths of instances (eg. ImageManager('../data/images/')\nto ImageManager('data/images/')'''\n\n\ndef main():\n pygame.init()\n SCREEN_WIDTH, SCREEN_HEIGHT = SCREEN_SIZE = (640, 480)\n\n screen = pygame.display.set_mode(SCREEN_SIZE)\n pygame.display.set_caption('[Demo] ImageManager image loading')\n imagedude = ImageManager('data/images')\n\n imagedude['backgroundB.jpg'] = pygame.transform.scale(imagedude['backgroundB.jpg'], SCREEN_SIZE)\n screen.blit(imagedude['backgroundB.jpg'], (0, 0))\n pygame.display.update()\n time.sleep(2)\n\n pygame.quit()\n sys.exit()\n\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.622020423412323, "alphanum_fraction": 0.6345062255859375, "avg_line_length": 26.5625, "blob_id": "710477190a2c8a07aa9aa3a18fd678284482d1a0", "content_id": "786c73b61d49c5ae9ce1a057d7d21712c8f1183a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 113, "num_lines": 32, "path": "/tests/test_warhead.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "from weapon import Weapon, Projectile, Warhead\nimport unittest\nfrom game import *\n\n\nclass WarheadTestCase(unittest.TestCase):\n\n \"\"\"Warheads should be reusable for different projectiles of same type\"\"\"\n\n def setUp(self):\n \"\"\"\n self.warhead = None\n self.speed = 100\n self.world = World()\n self.location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.projectile = Projectile(self.world, None, self.location, self.destination, self.speed, self.warhead)\n self.world.add_entity(self.projectile)\n \"\"\"\n\n def test_instance(self):\n pass\n\n\nclass WarheadTestCase(unittest.TestCase):\n\n def setUp(self):\n self.damage = 0\n self.vs_armor = 0.5\n self.vs_flesh = 1\n self.weapon = None # If there is one, the weapon will fire too\n self.radius = 0\n self.attached_effect = None" }, { "alpha_fraction": 0.6175413131713867, "alphanum_fraction": 0.6274862289428711, "avg_line_length": 39.712196350097656, "blob_id": "d00993bf639f63445d8e8a0bcedde29e043e7a2e", "content_id": "10cf10da27aec5d04630bc161f00f2c5ba068415", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8346, "license_type": "no_license", "max_line_length": 104, "num_lines": 205, "path": "/tests/test_effects.py", "repo_name": "marvin939/ZombiePygame", "src_encoding": "UTF-8", "text": "import copy\nfrom effects import BulletTravelEffect, ExplosionEffect\nfrom game import World\nimport unittest\nfrom pygame.math import Vector2\nfrom game import *\n\n\nTICK_SECOND = 1000 / 30 / 1000 # One tick represented by 30 frames per second; 33 milliseconds\n\n\nclass BulletTravelEffectTestCase(unittest.TestCase):\n def setUp(self):\n self.world = World()\n '''\n self.origin = Vector2(0, SCREEN_HEIGHT)\n self.destination = Vector2(SCREEN_WIDTH, 0)\n self.bullet_effect = BulletTravelEffect(self.world, self.origin, self.destination)\n '''\n self.origin = Vector2(0, SCREEN_HEIGHT)\n self.destination = Vector2(SCREEN_WIDTH, 0)\n self.color = YELLOW\n #self.duration = 1 / 10 # 1/10th of a second\n self.bullet = BulletTravelEffect(self.world, self.origin, self.destination, color=self.color)\n self.world.add_entity(self.bullet)\n\n def test_instance(self):\n origin = Vector2(0, SCREEN_HEIGHT)\n destination = Vector2(SCREEN_WIDTH, 0)\n color = YELLOW\n duration = 1/10 # 1/10th of a second\n\n bullet = BulletTravelEffect(self.world, origin, destination, color=color, duration=duration)\n self.assertEqual(bullet.location, origin)\n self.assertEqual(bullet.destination, destination)\n self.assertEqual(bullet.color, color)\n self.assertEqual(bullet.remaining_time, duration)\n\n def test_location_destination(self):\n pass\n\n def test_fade(self):\n d = 1\n self.bullet.DURATION = d\n self.bullet.remaining_time = d # seconds\n\n # Test when the bullet trail/line starts to fade\n self.bullet.process(TICK_SECOND)\n self.assertLess(self.bullet.remaining_time, self.bullet.DURATION)\n self.assertEqual(self.bullet.remaining_time, self.bullet.DURATION - TICK_SECOND)\n\n def test_remaining_zero(self):\n # Kill the effect\n self.bullet.remaining_time = 0\n self.bullet.process(TICK_SECOND)\n self.assertNotIn(self.bullet, self.world.entities.values())\n\n def test_bullet_travel(self):\n \"\"\"Test the bullet_head and bullet_tail vectors\"\"\"\n self.assertEqual(self.bullet.fx_head, self.bullet.location)\n self.assertEqual(self.bullet.fx_tail, self.bullet.location)\n #self.assertEqual(self.bullet.fx_length, 100)\n heading = (self.bullet.destination - self.bullet.location).normalize()\n self.assertEqual(self.bullet.fx_heading, heading)\n\n # Do one TICK; the head should start moving, while the tail remains the same\n self.bullet.process(TICK_SECOND)\n travelled = (TICK_SECOND * self.bullet.fx_speed)\n self.assertEqual(self.bullet.fx_head.distance_to(self.bullet.location), travelled)\n self.assertEqual(self.bullet.fx_tail, self.bullet.location)\n\n def test_process_head(self):\n num_ticks = 1000\n ticks = list((TICK_SECOND for i in range(num_ticks)))\n tick_accumulate = 0\n expected_head = {}\n b = self.bullet\n\n # build expected head; assumptions of fx_head's whereabouts relative to tick_accumulate\n for tick in ticks:\n heading = (b.destination - b.location).normalize()\n new_location = b.fx_head + (heading * (tick_accumulate + tick)* b.speed)\n # ^ accumulate current tick since it is leading tail\n expected_head[tick_accumulate] = new_location\n tick_accumulate += tick\n\n tick_accumulate = 0\n for i, tick in enumerate(ticks):\n if b not in self.world.entities.values():\n # bullet is no longer in this world... but still exists as object;\n # eg. b's fx_head == fx_tail == fx_destination\n break\n with self.subTest(tick_accumulate=tick_accumulate, i=i):\n b.process(tick)\n expected = expected_head[tick_accumulate]\n if b.fx_head != b.destination:\n self.assertEqual(expected, b.fx_head)\n tick_accumulate += tick\n\n def test_location(self):\n b = self.bullet\n self.assertEqual(b.fx_tail, b.location)\n self.assertEqual(b.fx_head, b.location)\n self.assertNotEqual(b.fx_head, b.destination)\n self.assertNotEqual(b.fx_tail, b.destination)\n self.assertIn(b, self.world.entities.values())\n\n def test_process_tail(self):\n self.assertIsNotNone(self.bullet)\n\n num_ticks = 1000\n ticks = list((TICK_SECOND for i in range(num_ticks)))\n tick_accumulate = 0\n expected_head = {}\n expected_tail = {}\n b = self.bullet\n self.assertIn(TICK_SECOND, ticks)\n self.assertEqual(num_ticks, len(ticks))\n\n # build expected tail; assumptions of fx_tail's whereabouts relative to tick_accumulate\n for tick in ticks:\n tail_heading = (b.destination - b.fx_tail).normalize()\n new_tail_location = b.fx_tail + (tail_heading * tick_accumulate * b.speed)\n expected_tail[tick_accumulate] = new_tail_location\n tick_accumulate += tick\n\n self.assertNotEqual(id(b.fx_tail), id(b.fx_head))\n\n tick_accumulate = 0\n for i, tick in enumerate(ticks):\n if b not in self.world.entities.values():\n break\n with self.subTest(tick_accumulate=tick_accumulate, i=i):\n b.process(tick)\n #print(expected_tail[tick_accumulate], b.fx_tail, sep='=')\n self.assertEqual(expected_tail[tick_accumulate], b.fx_tail)\n tick_accumulate += tick\n\n @unittest.skip\n def test_each_tick(self):\n # There's a bug here, where the length is far less than fx_length,\n # relative to a single tick and its speed... But visually, it's not a big problem.\\\n\n num_ticks = 100\n ticks = list((TICK_SECOND for i in range(num_ticks)))\n b = self.bullet\n\n tick_accumulate = 0\n for tick in ticks:\n b.process(tick)\n with self.subTest(tick_accumulate=tick_accumulate):\n if b.fx_head != b.destination and b.fx_tail != b.destination and \\\n b.fx_tail != b.location and b.fx_head != b.location:\n self.assertAlmostEqual(b.fx_head.distance_to(b.fx_tail), b.fx_length, 1)\n tick_accumulate += tick\n\n def test_die(self):\n \"\"\"Effect should die when both fx_head/tail reaches destination\"\"\"\n self.bullet.fx_head = self.bullet.destination\n self.bullet.fx_tail = self.bullet.fx_head\n self.bullet.process(TICK_SECOND)\n self.assertNotIn(self.bullet, self.world.entities.values())\n\n\nclass ExplosionEffectTestCase(unittest.TestCase):\n def setUp(self):\n self.exp_radius = 50\n self.exp_duration = 1 # second\n self.world = World()\n self.exp_location = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n #self.exp_image = pygame.Surface((32, 32)).fill(RED)\n self.exp_color = RED\n self.explosion = ExplosionEffect(self.world, self.exp_location, self.exp_radius, self.exp_color)\n self.world.add_entity(self.explosion)\n\n def test_instantiate_radius(self):\n # Negative radius\n with self.assertRaises(ValueError):\n ExplosionEffect(self.world, self.exp_location, -1)\n\n def test_instantiate_color(self):\n # Color argument type\n with self.assertRaises(TypeError):\n ExplosionEffect(self.world, self.exp_location, self.exp_radius, color=1)\n # Color argument length\n with self.assertRaises(ValueError):\n ExplosionEffect(self.world, self.exp_location, self.exp_radius, color=(100,200))\n\n def test_die_radius_zero(self):\n self.explosion.radius = 0\n self.explosion.process(TICK_SECOND)\n self.assertNotIn(self.explosion, self.world.entities.values())\n\n def test_radius_shrink(self):\n \"\"\"Explosion should shrink based on TICK\"\"\"\n old_radius = self.explosion.radius\n self.explosion.process(TICK_SECOND)\n self.assertLess(self.explosion.radius, old_radius)\n\n # num_ticks = 0\n # while self.explosion.radius >= 0:\n # self.explosion.process(TICK_SECOND)\n # print('radius:', self.explosion.radius)\n # num_ticks += 1\n # print(num_ticks)\n" } ]
24
rphillipsz/cleanElastic
https://github.com/rphillipsz/cleanElastic
9cda75c853a461f6f9a41500d66968397b5fadb9
37ce207916e8b7a30c7c5b1a2a77155029f35928
f1c2001820c7ab8ebaf5a64ebadca1a00308c92f
refs/heads/master
2017-12-22T15:48:38.824212
2016-11-03T21:09:41
2016-11-03T21:09:41
72,679,913
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6046072840690613, "alphanum_fraction": 0.7069917917251587, "avg_line_length": 47.19480514526367, "blob_id": "939ed2a263a312b616f8bcdcb20771ee281dab20", "content_id": "d6d2132290ead10906413967cadc2e99c834298e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7423, "license_type": "no_license", "max_line_length": 464, "num_lines": 154, "path": "/README.md", "repo_name": "rphillipsz/cleanElastic", "src_encoding": "UTF-8", "text": "\n```diff\n- WARNING: THIS SCRIPT SHOULD ONLY BE RUN IF `serviced service rm` FAILS\n- TO REMOVE A SERVICE DUE TO ZOOKEEPER ERRORS\n\n- It should be considered a last resort effort to recover a system that cannot\n- be fixed through the regular commands.\n```\n\n## cleanElastic\n\nThese scripts have been written to help remove services from an install with the\nZookeeper problem \"zk: buffer too small\", preventing any removal of services from\nControl Center.\n\n### Running the script\n\nCopy the two files to the CC master\nrun gen.py while serviced is running: python gen.py\n\nYou'll be presented with a numbered service tree to select which services you want\nto remove from Control Center:\n\n```\n 1. [ ] Zenoss.resmgr [deadjil7v454osr4biaza0x1v]\n 2. [ ] Infrastructure [80ymizlk9gsznjzcsfgbk3g3c]\n 3. [ ] redis [8jcb032ofbr2f45f1s8l1so4b]\n 4. [ ] RabbitMQ [w54rf4xi47ha2ajqlrvs2u9w]\n 5. [ ] mariadb-model [7ymdbtpy958a7ull3eym9d985]\n 6. [ ] zencatalogservice [39hh3p44i6ajz735scp8l7m67]\n 7. [ ] mariadb-events [5l4adpj8o1qvmtmnjw3m5ry5l]\n 8. [ ] memcached [uutfagv95ko3f3io96vicxpv]\n 9. [ ] opentsdb [eovaurpeqetd6wfduvh7cbxj7]\n 10. [ ] reader [459589hx7brjmqxj54uotao0g]\n 11. [ ] writer [cw5lr6fb5t27dzljlm46t7ri8]\n 12. [ ] HBase [cakf4s87acaqpnyomro5vzlf5]\n 13. [ ] HMaster [c0g87yd2tfkjpquzfb51ha9on]\n 14. [ ] RegionServer [cwvhj2squhchv28iq8fscunqc]\n 15. [ ] ZooKeeper [ex020ehq7ldt5tohwsp0j7keu]\n 16. [ ] Zenoss [7t53amlt7acfu9yklolij1icq]\n 17. [ ] Collection [59aedxqo99limb46da2x9tds2]\n 18. [ ] localhost [4kcz96d7f5gr9iawnirszq7vq]\n 19. [x] col1 [d2k6xj03h9b05k7mwe0maze6k]\n 20. [x] zensyslog [djwhudmt95ko1bpq344ulk67c]\n 21. [x] zenpython [582xqfthbaruwz2nxar5bomh]\n 22. [x] zenmail [evmqbe2b6ibqxbh7hh2vmwwel]\n 23. [x] zenvsphere [67qr816lelufbemzijfb1inc5]\n 24. [x] zenjmx [9m8ui2qjm8zlh4kiqj4v63ro1]\n 25. [x] zenucsevents [48ch3sbhekcrh10yp7oqqkf0q]\n 26. [x] zentrap [8fmspsflqinded28gvepbeqsf]\n 27. [x] zenmodeler [bxsw3nwokprnkrtcg9nkh4glz]\n 28. [x] zenstatus [5enbnl3sj4d6ndsg5db0c1821]\n 29. [x] zenping [2ykf3ts12snl7jvr3pv5w16q]\n 30. [x] zenperfsnmp [2i7jv2cej1tj9mu9ymv74oeh7]\n 31. [x] zenprocess [3qb7slfkos70maoo0ybkr6e9j]\n 32. [x] zenwebtx [5mngmwqkss9fu3ydb1ez10yqv]\n 33. [x] zenmailtx [96qrke3akjrzq64xcfhz8qnuw]\n 34. [x] MetricShipper [33d7acmd1wlrntmr863eyewyy]\n 35. [x] zminion [8qzfrlidehusx38ph3jd77sdq]\n 36. [x] collectorredis [4wrsimd9ysj21i2hmbj1gl54w]\n 37. [x] zencommand [8lwf3r0cpjasoqvvav04xux5i]\n 38. [x] zenpropertymonitor [bss1thnamns82tm1eqm2ni7f]\n 39. [x] zenpop3 [154rtq9e8rytqrkcig2ea5unn]\n...\n 82. [ ] zenhub [e92y5mn929av69gnibjioduik]\n 83. [ ] localhost [e52d2p4zk7qbaf52ekhfuqqzp]\n 84. [ ] zenpop3 [4hiqrneeuhhlimn8ubqk01zc0]\n 85. [ ] zenmail [h9wgn99qixa8na9byhhifdla]\n 86. [ ] zensyslog [c6x4vstcjv6u8c6z66c39hwgy]\n 87. [ ] zenpython [3w92lzdvf9ctaw30kv8m71qq0]\n 88. [ ] zenvsphere [a93c02mc8x2m9tuwsqbh5eavz]\n 89. [ ] zenjmx [e099vy5pq1htf9o2prs2c6nwm]\n 90. [ ] zenucsevents [1ysgxubyj7rqmnzhr5musz72x]\n 91. [ ] zenstatus [btjc9dzr5wup22xwaaqapecye]\n 92. [ ] zentrap [3uihszj0bx9nt2lg8fscsxdwf]\n 93. [ ] zenmodeler [49zefdtu7yjoq7ublrk3gf27n]\n 94. [ ] zenping [1avtx229dmeoi7a45056ba5mq]\n 95. [ ] zenperfsnmp [96ctxktjefkdmbqkhs8ihqccp]\n 96. [ ] zenprocess [3af5k7hlaxxffwoj6g9i40oy2]\n 97. [ ] zenwebtx [9yel4g4ec477aoquz3azv4pgq]\n 98. [ ] MetricShipper [10bnnkt9h6pk8778llaogcr80]\n 99. [ ] zenmailtx [311x303abayaakrxor1qkq7ie]\n100. [ ] zminion [1bilpist8678a9dy02d9lxzgh]\n101. [ ] collectorredis [azvnbimn76myk6ttgfbxxeo5]\n102. [ ] zencommand [ckyuiraa6jgzvxy35so5o6gzr]\n103. [ ] zenpropertymonitor [cfbxyonnkjww2hliv24nfyyk7]\n103. [ ] zenpropertymonitor [cfbxyonnkjww2hliv24nfyyk7]\n104. [ ] Events [dfiq6ldxsuf7rdyge3s2t8suy]\n105. [ ] zeneventd [df344ws5bkev1wrbd7beajeo4]\n106. [ ] zenactiond [2d5im0o6op2ephjn1271o0xpe]\n107. [ ] zeneventserver [98gk7kas0lvtx67d7560zxdbq]\n108. [ ] Metrics [91mw319kug0tcmg6hp01zfjrn]\n109. [ ] MetricConsumer [2p3l6w168hpe6kcngy2qmpwc4]\n110. [ ] CentralQuery [1wzvajhc6u4qor864prorhei4]\n111. [ ] MetricShipper [dhquuzgxbglf5t5iu91soy9d0]\n112. [ ] User Interface [1j0ugbb4wjn20eazwxbh439jr]\n113. [ ] Zope [c8vh8ahw90h8jsi76lq6liiiw]\n114. [ ] Zauth [eo34ufbfq7j2felntqcbyqbss]\n115. [ ] zenjobs [3s6yo9vyapl4s431wrnfa4c1f]\n116. [ ] zenjserver [abz1ueew1giod48hgwnabxp7v]\n\nSelect a service by number, 'p' to process the items, 'quit' or 'exit' to abort: \n```\n\nToggle services to remove by entering the numbers. When you have all services you want to remove\nselected, enter 'p' to generate scripts and inspect the running serviced.\n\nYou'll be presented with a set of steps to run to perform the cleanup:\n```\nSteps to clean services from Elastic:\n\n 1) Stop serviced: sudo systemctl stop serviced (on all hosts)\n 2) Backup isvcs: sudo tar -czvf isvcs.tgz /opt/serviced/var/isvcs (adjust the location of the tgz as needed)\n 3) run: docker run -v /home/rphillips/src/europa/opt_serviced/isvcs/resources:/usr/local/serviced/resources -v /home/rphillips/src/europa/opt_serviced/var/isvcs/elasticsearch-serviced/data:/opt/elasticsearch-serviced/data -v /tmp/startElastic.sh:/tmp/startElastic.sh -v /home/rphillips/test/services/removeService.py:/tmp/removeService.py -v /tmp/removeServices.sh:/tmp/removeServices.sh -it ce38a9911378c81ba691769592d057f37fd192e70afea5d9b2fedc9ae1a246b9 bash\n a) In the container: bash /tmp/startElastic.sh (wait for 'recovered [1] indices into cluster_state')\n * Note: If you don't see '[1] indices', check to make sure all serviced are stopped and try again\n b) In the container: bash /tmp/removeServices.sh\n c) Exit the container: exit\n 4) run: sudo rm -rf /opt/serviced/var/isvcs/zookeeper *for ALL hosts*\n 5) Start serviced: sudo systemctl start serviced (master first, then delegates)\n```\n\nFollow the steps above to remove the services from Control Center.\n\n## What does it do?\n\n1. shuts down serviced on all hosts.\n\n2. runs a docker container with Elastic, mapping the generated scripts into the container.\n\n2a. Starts Elastic in the container.\n\n2b. Removes the selected services from Elastic.\n\n3. Blows away the isvcs Zookeeper data.\n\n4. Starts Control Center. Zookeeper will reload itself from Elastic, without the removed services.\n\n## How are the services removed?\n\nThe service document is removed using curl:\n\n```curl -XDELETE 'http://localhost:9200/controlplane/service/serviceid'```\n\nThe address assignments are removed:\n\n```curl -XDELETE 'http://localhost:9200/controlplane/addressassignment/serviceid'```\n\nEach service config is removed by querying for all service configs with a path ending in this serviceid:\n\n```curl -H \"Content-Type: application/json\" -XGET -d '{\"fields\": [\"_id\"], \"query\": {\"wildcard\": { \"ServicePath\": \"*/serviceid\" }}}' http://localhost:9200/_search```\n\nFor each document id found, it gets removed:\n\n```curl -XDELETE 'http://localhost:9200/controlplane/svcconfigfile/docid'```\n" }, { "alpha_fraction": 0.5729166865348816, "alphanum_fraction": 0.5799319744110107, "avg_line_length": 33.3533821105957, "blob_id": "b1ca4f2d14f3d9b432e72bac4d2e2ea86216fda4", "content_id": "85de240939d3c3238710a16818bf840664c12ac2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9408, "license_type": "no_license", "max_line_length": 148, "num_lines": 266, "path": "/gen.py", "repo_name": "rphillipsz/cleanElastic", "src_encoding": "UTF-8", "text": "#\r\n# Usage: python gen.py\r\n#\r\n# Purpose: present a tree of services from a running serviced instance, allow the\r\n# selection of services, then generate scripts to remove those services\r\n# from elastic.\r\n\r\nimport json\r\nimport os\r\nimport re\r\nimport shutil\r\nimport subprocess\r\nimport sys\r\n\r\n\r\n# The script won't run unless the serviced version\r\n# matches one of these.\r\nversions = [\"1.2.[0-9]\", \"1.1.[0-9]\"]\r\n\r\n\r\n# Process helper\r\ndef shell(command):\r\n p = subprocess.Popen(\r\n command,\r\n shell=True,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)\r\n stdout, stderr = p.communicate()\r\n return p.returncode, stdout.encode('ascii', 'ignore'), stderr.encode('ascii', 'ignore')\r\n\r\n\r\ndef yellow(message, *args):\r\n if len(args):\r\n return \"%s%s%s\" % (\"\\033[93m\", message % args, \"\\033[0m\")\r\n return \"%s%s%s\" % (\"\\033[93m\", message, \"\\033[0m\")\r\n\r\n\r\n# Check the serviced version. Fail if it isn't whitelisted.\r\nresult = shell(\"serviced version\")\r\nmatched = False\r\nfor line in result[1].split('\\n'):\r\n if \"Version:\" in line:\r\n ccversion = line\r\n break\r\n\r\nfor version in versions:\r\n matcher = \"Version: *%s\" % version\r\n if re.match(matcher, ccversion):\r\n matched = True\r\n break\r\n\r\nif not matched:\r\n print yellow(\"Control Center %s is unsupported/untested\", ccversion)\r\n sys.exit(1)\r\n\r\n\r\n# Get the service definitions.\r\nservicesJson = shell(\"serviced service list -v\")\r\nif servicesJson[0] != 0 or not servicesJson[1]:\r\n print \"Unable to get the output from 'serviced service list -v'\"\r\n sys.exit(1)\r\n\r\n# Load the service data.\r\nservicedefs = json.loads(servicesJson[1])\r\nif len(servicedefs) == 0:\r\n print \"No services loaded from service definition.\"\r\n sys.exit(1)\r\n\r\nprint \"Got %d services\" % len(servicedefs)\r\n\r\n\r\nclass Service(object):\r\n def __init__(self, name, serviceid, parentid):\r\n self.children = []\r\n self.name = name\r\n self.id = serviceid\r\n self.parent = parentid\r\n self.selected = False\r\n def name(self):\r\n return self.name\r\n def id(self):\r\n return self.id\r\n def parent(self):\r\n return self.parent\r\n def addChild(self, child):\r\n self.children.append(child)\r\n def children(self):\r\n return children\r\n def selection(self):\r\n if self.selected:\r\n return '[x]'\r\n return '[ ]'\r\n def select(self, value):\r\n self.selected = value\r\n for child in self.children:\r\n child.select(value)\r\n def _tree(self, level, number, items):\r\n items.append(self)\r\n result = \"%3d. %s%s %s [%s]\" % (number, ' ' * level, self.selection(), self.name, self.id)\r\n for child in self.children:\r\n number = number + 1\r\n desc, number, items = child._tree(level + 1, number, items)\r\n result = result + \"\\n\" + desc\r\n return result.encode('ascii', 'ignore'), number, items\r\n def tree(self):\r\n \"\"\"\r\n Returns a tuple of the string representation of the service, how many items there\r\n are, and an array of those items in the same order presented in the representation.\r\n \"\"\"\r\n return self._tree(0, 1, [])\r\n def __repr__(self):\r\n return \"%s [%s]\" % (self.name, self.id)\r\n\r\n\r\n# Process the servicedefs into a set of services.\r\nservices = []\r\nfor servicedef in servicedefs:\r\n service = Service(servicedef['Name'], servicedef['ID'], servicedef['ParentServiceID'])\r\n services.append(service)\r\n\r\n# Find the top level service.\r\ntop = None\r\nfor service in services[:]:\r\n if service.parent == '':\r\n services.remove(service)\r\n top = service\r\n break\r\n\r\nprint \"Top level service is: %s\" % top\r\n\r\ndef findParent(depth, parent, service):\r\n for child in parent.children:\r\n if service.parent == child.id:\r\n return child\r\n recurse = findParent(depth + 1, child, service)\r\n if recurse:\r\n return recurse\r\n return None\r\n\r\n\r\n# Create the parent/child relationships for all services.\r\nwhile len(services) > 0:\r\n print \"\"\r\n for service in services[:]:\r\n if service.parent == top.id:\r\n services.remove(service)\r\n top.addChild(service)\r\n else:\r\n parent = findParent(1, top, service)\r\n if parent:\r\n services.remove(service)\r\n parent.addChild(service)\r\n\r\n\r\ndef writeElasticRun(runcmd):\r\n \"\"\"\r\n Writes /tmp/startElastic.sh for mounting into the container.\r\n \"\"\"\r\n with open('/tmp/startElastic.sh', 'w') as fd:\r\n fd.write('#!/bin/bash\\n')\r\n fd.write('%s &\\n' % runcmd.strip())\r\n\r\n\r\ndef parseElasticArgs(container):\r\n ret, stdout, stderr = shell(\"docker inspect %s\" % container)\r\n args = json.loads(stdout)\r\n runargs=args[0][\"Args\"]\r\n elasticid=args[0][\"Image\"].encode('ascii', 'ignore')\r\n #print \"Parsed container id: %s\" % elasticid\r\n mounts=args[0][\"Mounts\"]\r\n for arg in runargs:\r\n match = re.match(\".*(exec .*)\", arg)\r\n if match:\r\n runcmd = match.group(1)\r\n if not runcmd:\r\n print \"Unable to parse the Elastic start command from: %s\" % runargs\r\n sys.exit(1)\r\n #print \"Parsed elastic run command: %s\" % runcmd\r\n mountcmd = \"\"\r\n for mount in mounts:\r\n mountcmd = \"%s -v %s:%s\" % (mountcmd, mount[\"Source\"], mount[\"Destination\"])\r\n #print \"Parsed mounts: %s\" % mountcmd\r\n # Add additional scripts for Elastic cleanup into /tmp in the container.\r\n pyScriptPath = os.path.dirname(os.path.abspath(__file__))\r\n mountcmd += \" -v /tmp/startElastic.sh:/tmp/startElastic.sh\"\r\n mountcmd += \" -v %s/removeService.py:/tmp/removeService.py\" % pyScriptPath\r\n mountcmd += \" -v /tmp/removeServices.sh:/tmp/removeServices.sh\"\r\n writeElasticRun(runcmd)\r\n return \"docker run %s -it %s bash\" % (mountcmd, elasticid)\r\n\r\n\r\ndef parseElasticContainer():\r\n \"\"\"\r\n Looks at the docker information for elastic and creates a docker run\r\n command to fire up Elastic after serviced has been shut down.\r\n \"\"\"\r\n ret, stdout, stderr = shell(\"docker ps\")\r\n for line in stdout.split('\\n'):\r\n if \"serviced-isvcs_elasticsearch-serviced\" in line:\r\n match = re.match(\"^([0-9a-z]*) \", line)\r\n #print \"Found elastic container: %s\" % match.group(0)\r\n runcmd = parseElasticArgs(match.group(0))\r\n if not runcmd:\r\n print \"Unable to parse the Elastic args from docker. Is service running?\"\r\n sys.exit(1)\r\n print \"\"\r\n print \"Steps to clean services from Elastic:\\n\"\r\n print yellow(\" 1) Stop serviced:\") + \" sudo systemctl stop serviced \" + yellow(\"(on all hosts)\")\r\n print yellow(\" 2) Backup isvcs:\") + \" sudo tar -czvf isvcs.tgz /opt/serviced/var/isvcs \" + yellow(\"(adjust the location of the tgz as needed)\")\r\n print yellow(\" 3) run: \") + runcmd\r\n print yellow(\" a) In the container: \") + \"bash /tmp/startElastic.sh \" + yellow(\"(wait for 'recovered [1] indices into cluster_state')\")\r\n print yellow(\" * Note: If you don't see '[1] indices', check to make sure all serviced are stopped and try again\")\r\n print yellow(\" b) In the container: \") + \"bash /tmp/removeServices.sh\"\r\n print yellow(\" c) Exit the container: \") + \"exit\"\r\n print yellow(\" 4) run: \") + \"sudo rm -rf /opt/serviced/var/isvcs/zookeeper \" + yellow(\"*for ALL hosts*\")\r\n print yellow(\" 5) Start serviced: \") + \"sudo systemctl start serviced \" + yellow(\"(master first, then delegates)\")\r\n print \"\"\r\n\r\n\r\ndef process(fd, service):\r\n \"\"\"\r\n Takes the selected service tree items and processes them, generating the\r\n scripts needed to remove them from Elastic.\r\n \"\"\"\r\n print \"Generating scripts for %s\" % service\r\n fd.write(\"python /tmp/removeService.py %s\\n\" % service.id)\r\n\r\n\r\n# Find out what services they want to remove.\r\nwhile True:\r\n tree, count, items = top.tree()\r\n print tree\r\n response = raw_input(\"\\nSelect a service by number, 'p' to process the items, 'quit' or 'exit' to abort: \")\r\n if response.isdigit():\r\n n = int(response)\r\n if n < 1 or n > len(items):\r\n print yellow('\\nInvalid index')\r\n continue\r\n items[n-1].select(not items[n-1].selected)\r\n continue\r\n else:\r\n if response.startswith('quit') or response.startswith('exit') or response == 'q':\r\n print yellow('\\nAborted\\n')\r\n break\r\n if response == 'p':\r\n print \"\"\r\n count = 0\r\n fd = None\r\n for item in items:\r\n if item.selected:\r\n if not fd:\r\n # Create the remove command that gets mapped into\r\n # the container. This will remove each service selected.\r\n fd = open('/tmp/removeServices.sh', 'w')\r\n fd.write(\"#!/bin/bash\\n\\n\")\r\n fd.write(\"set -e\\n\")\r\n fd.write(\"set -o pipefail\\n\\n\")\r\n count = count + 1\r\n process(fd, item)\r\n if fd:\r\n fd.close()\r\n if count == 0:\r\n print yellow(\"\\nNo services were selected\")\r\n parseElasticContainer()\r\n break\r\n print yellow('\\nInvalid selection\\n')\r\n\r\n\r\n" }, { "alpha_fraction": 0.6076680421829224, "alphanum_fraction": 0.6158088445663452, "avg_line_length": 32.69911575317383, "blob_id": "b6776bd4d257295ae9d2483c983bc6e9c6d0023b", "content_id": "ebc5aad0107cf2c71e2da4a969ef351f7249dfc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3808, "license_type": "no_license", "max_line_length": 188, "num_lines": 113, "path": "/removeService.py", "repo_name": "rphillipsz/cleanElastic", "src_encoding": "UTF-8", "text": "#\n# Removes the service from Elastic specified as an argument. If we see something that doesn't look\n# right in queries/validation, prompt for an exit.\n#\n\nimport json\nimport subprocess\nimport sys\n\n\n# Process helper\ndef shell(command):\n p = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n return p.returncode, stdout.encode('ascii', 'ignore'), stderr.encode('ascii', 'ignore')\n\n\ndef exit(message):\n print message\n response = raw_input(\"Press [enter] to exit, 'i' to ignore and continue: \")\n if not response == 'i':\n print \"Exiting script..\"\n sys.exit(1)\n\n\ndef getService():\n \"\"\"\n Checks the command line for the right arguments.\n \"\"\"\n args = sys.argv\n # Check arguments\n if not len(args) == 2:\n exit(\"Usage: %s <serviceid>\" % __file__)\n # Get the service id.\n return args[1]\n\n\ndef verifyService(id):\n \"\"\"\n Verifies that the service exists in elastic, and gives us the\n opportunity to abort if things don't work right.\n \"\"\"\n ret = shell(\"curl -XGET 'http://localhost:9200/controlplane/service/%s'\" % id)\n jsonData = json.loads(ret[1])\n if not jsonData:\n exit(\"Unable to parse Elastic return: %s\" % ret[1])\n if \"error\" in jsonData:\n exit(\"Error validating service in Elastic: %s\" % jsonData[\"error\"])\n if not jsonData[\"exists\"]:\n exit(\"Service '%s' doesn't exist in elastic\" % id)\n\n\ndef removeService(id):\n \"\"\"\n Performs the removal of the service from Elastic.\n \"\"\"\n # Delete the service.\n print \"Removing service %s..\" % id\n shell(\"curl -XDELETE 'http://localhost:9200/controlplane/service/%s'\" % id)\n # Delete the address assignment (if any)\n print \"Removing address assignment (if any) for %s..\" % id\n removeAssignments(id)\n # Remove all service configs for this service.\n print \"Removing service configs for %s..\" % id\n removeConfigs(id)\n\n\ndef removeAssignments(id):\n \"\"\"\n Queries for all address assignments for the given service id.\n We have to query for assignments, then iterate the document ids to remove them.\n \"\"\"\n query = '{ \"query\": { \"filtered\": { \"filter\": { \"bool\": { \"must\": [ {\"query\": {\"match\": {\"ServiceID\": \"%s\"}}}, {\"query\": {\"match\": {\"_type\": \"addressassignment\"}}} ] } } } } }' % id\n cmd = \"curl -H \\\"Content-Type: application/json\\\" -XGET -d '%s' http://localhost:9200/_search\" % query\n ret = shell(cmd)\n jsonData = json.loads(ret[1])\n if not jsonData:\n exit(\"Error querying for address assignments\")\n # Get just the hit data\n jsonData = jsonData[\"hits\"]\n # For each hit, delete the address assignment\n for hit in jsonData[\"hits\"]:\n cmd = \"curl -XDELETE 'http://localhost:9200/controlplane/addressassignment/%s'\" % hit[\"_id\"]\n shell(cmd)\n\n\ndef removeConfigs(id):\n \"\"\"\n Queries for service config matches for this service id, then removes\n each of the configs.\n \"\"\"\n query = '{ \"query\": { \"filtered\": { \"filter\": { \"bool\": { \"must\": [ {\"query\": {\"wildcard\": {\"ServicePath\": \"*/%s\"}}}, {\"query\": {\"match\": {\"_type\": \"svcconfigfile\"}}} ] } } } } }' % id\n cmd = \"curl -H \\\"Content-Type: application/json\\\" -XGET -d '%s' http://localhost:9200/_search\" % query\n ret = shell(cmd)\n jsonData = json.loads(ret[1])\n if not jsonData:\n exit(\"Error querying for service configs\")\n # Get just the hit data\n jsonData = jsonData[\"hits\"]\n # For each hit, delete the config\n for hit in jsonData[\"hits\"]:\n cmd = \"curl -XDELETE 'http://localhost:9200/controlplane/svcconfigfile/%s'\" % hit[\"_id\"]\n shell(cmd)\n\n\nif __name__ == \"__main__\":\n id = getService()\n verifyService(id)\n removeService(id)\n" } ]
3
p-schlickmann/proffy-app
https://github.com/p-schlickmann/proffy-app
b6102ff2e8a1330ffc66a876dafca41fd10dc37d
2c8edb3195993e29f2c4033eed1f330ea79a5cd6
72df669dfccb5d731e0c4d81c56c31be7ca51d75
refs/heads/master
2022-11-27T10:54:57.006742
2020-08-07T16:38:31
2020-08-07T16:38:31
285,146,058
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6225680708885193, "alphanum_fraction": 0.6225680708885193, "avg_line_length": 22.454545974731445, "blob_id": "0d79a23976e7d8ee5bd095d420cf74613caa3d06", "content_id": "3bd4c1a41320e943e2cc491bcadf35498b50780d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "permissive", "max_line_length": 48, "num_lines": 11, "path": "/web/server/urls.py", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('study/', views.study, name='study'),\n path('teach/', views.teach, name='teach'),\n path('search/', views.search, name='search')\n \n]" }, { "alpha_fraction": 0.6787564754486084, "alphanum_fraction": 0.6804835796356201, "avg_line_length": 25.363636016845703, "blob_id": "16af59cbb34e5857ca1390566a10ad92ea2375d6", "content_id": "41f5cd7211a05257a23b5fb734974516393dbe6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 579, "license_type": "permissive", "max_line_length": 77, "num_lines": 22, "path": "/web/server/static/server/scripts/fieldManager.js", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "document.querySelector('#add-time').addEventListener('click', addElement)\n\nfunction addElement() {\n const newField = document.querySelector('.schedule-item').cloneNode(true)\n const fields = newField.querySelectorAll(\"input\")\n\n for (var field of fields){\n field.value = ''\n }\n \n document.querySelector('#schedule-items').appendChild(newField)\n}\n\nfunction removeField(el){\n var len = document.querySelectorAll(\".schedule-item\").length\n if (len == 1){\n return\n }else{\n var element = el.parentElement.parentElement\n element.remove()\n}\n}" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6883720755577087, "avg_line_length": 25.875, "blob_id": "ff90f0900a537840bea02326da824e7004d5e173", "content_id": "e9e07d122bd9ec4a1fa6cee51803be91e9003c96", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 430, "license_type": "permissive", "max_line_length": 52, "num_lines": 16, "path": "/README.md", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "# Proffy Web Application\n## Sua plataforma de estudos online :purple_heart: \n<img src=\"images/Screenshot_2.png\" width=\"700px\"> \n\n## Mobile Responsive :star: :heart_eyes: \n<img src=\"images/home_mobile.png\">\n\n## Estude :books:\n<img src=\"images/study-1.png\" width=\"700px\"> \n\n### Encontre professores :speech_balloon: \n<img src=\"images/study-2.png\" width=\"700px\">\n\n\n## Ensine :pencil:\n<img src=\"images/give-1.png\" width=\"700px\">\n" }, { "alpha_fraction": 0.5490680932998657, "alphanum_fraction": 0.5580068230628967, "avg_line_length": 33.14285659790039, "blob_id": "ad9c76c09e1803f0f16e3b33a30d92c6170f54e1", "content_id": "874402dc3739cdffb2a6dc31b45049338e340ffd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5269, "license_type": "permissive", "max_line_length": 132, "num_lines": 154, "path": "/web/server/views.py", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport time\nimport datetime\n\nfrom server import models\n\n\n# Create your views here.\n\n\ndef index(request):\n return render(request, \"server/index.html\")\n\n\ndef study(request):\n return render(request, \"server/study.html\", {\n 'proffys': models.Teacher.objects.all()\n })\n\n\ndef teach(main_request):\n if main_request.method == 'GET':\n return render(main_request, \"server/give-classes.html\")\n elif main_request.method == 'POST':\n request = dict(main_request.POST)\n print(request)\n name = request.get('name')[0]\n img_url = request.get('avatar')[0]\n whatsapp = int(request.get('whatsapp')[0])\n bio = request.get('bio')[0]\n subject_id = request.get('subject')[0]\n subject_name = convert_id(subject_id)\n cost = int(request.get('cost')[0])\n\n week_day = request['weekday[]']\n week_day_name = [convert_id(week_day_id, day=True) for week_day_id in week_day]\n\n starts = request['time_from[]']\n start_seconds = [convert_to_seconds(start) for start in starts]\n\n ends = request.get('time_to[]')\n end_seconds = [convert_to_seconds(end) for end in ends]\n\n new_teacher = models.Teacher(name=name, avatar_url=img_url, whatsapp=whatsapp, bio=bio, subject=subject_id,\n subject_name=subject_name, cost=cost)\n new_teacher.save()\n\n for wk_day, wk_day_name, st, st_sec, en, end_secs in zip(week_day, week_day_name, starts, start_seconds, ends, end_seconds):\n new_class = models.Class(teacher=new_teacher, week_day=wk_day, week_day_name=wk_day_name, start=st,\n end=en, start_seconds=st_sec, end_seconds=end_secs)\n new_class.save()\n return render(main_request, \"server/study.html\", {\n 'proffys': models.Teacher.objects.all()\n })\n\n\ndef search(request):\n subject = request.GET.get('subject', None)\n week_day = request.GET.get('weekday', None)\n time = convert_to_seconds(request.GET.get('time', None))\n\n matches = []\n if subject and week_day and time:\n teachers = models.Teacher.objects.filter(subject=subject)\n for teacher in teachers:\n classes = teacher.classes.filter(week_day=week_day)\n for _class in classes:\n start = _class.start_seconds\n end = _class.end_seconds - 3600\n if end >= time >= start:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif subject and week_day:\n teachers = models.Teacher.objects.filter(subject=subject)\n classes = [teacher.classes.filter(week_day=week_day) for teacher in teachers][0]\n for _class in classes:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif week_day and time:\n classes = models.Class.objects.filter(week_day=week_day)\n for _class in classes:\n start = _class.start_seconds\n end = _class.end_seconds - 3600\n if end >= time >= start:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif subject and time:\n teachers = models.Teacher.objects.filter(subject=subject)\n for teacher in teachers:\n classes = teacher.classes.all()\n for _class in classes:\n start = _class.start_seconds\n end = _class.end_seconds - 3600\n if end >= time >= start:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif subject:\n matches = models.Teacher.objects.filter(subject=subject)\n elif week_day:\n classes = models.Class.objects.filter(week_day=week_day)\n for _class in classes:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif time:\n classes = models.Class.objects.all()\n for _class in classes:\n start = _class.start_seconds\n end = _class.end_seconds - 3600\n if end >= time >= start:\n if _class.teacher not in matches:\n matches.append(_class.teacher)\n elif not week_day and not subject and not time:\n matches = models.Teacher.objects.all()\n else:\n matches = None\n return render(request, \"server/study.html\", {\n 'proffys': matches\n })\n\n\ndef convert_id(_id, day=False):\n if not day:\n conv = {\n 1: 'Artes',\n 2: 'Biologia',\n 3: 'Ciências',\n 4: 'Educação Física',\n 5: 'Física',\n 6: 'Geografia',\n 7: 'História',\n 8: 'Matemática',\n 9: 'Português',\n 10: 'Química',\n }\n else:\n conv = {\n 1: 'Domingo',\n 2: 'Segunda',\n 3: 'Terça',\n 4: 'Quarta',\n 5: 'Quinta',\n 6: 'Sexta',\n 7: 'Sábado',\n }\n\n return conv[int(_id)]\n\n\ndef convert_to_seconds(time):\n if not time:\n return None\n ftr = [3600, 60]\n\n return sum([a * b for a, b in zip(ftr, map(int, time.split(':')))])\n" }, { "alpha_fraction": 0.664882242679596, "alphanum_fraction": 0.680942177772522, "avg_line_length": 33.55555725097656, "blob_id": "f92f43b01592c336ceec4feee3c39f0f6c3fd05d", "content_id": "9e61a33310974961ac14ddc13cd4bbebc9d8bbff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 934, "license_type": "permissive", "max_line_length": 90, "num_lines": 27, "path": "/web/server/models.py", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Teacher(models.Model):\n name = models.CharField(max_length=64)\n avatar_url = models.CharField(max_length=2048)\n whatsapp = models.IntegerField()\n bio = models.CharField(max_length=500)\n subject = models.IntegerField()\n subject_name = models.CharField(max_length=50)\n cost = models.IntegerField()\n\n def __str__(self):\n return f\"{self.subject_name}: {self.name} | {self.cost}R$\"\n\n\nclass Class(models.Model):\n teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='classes')\n week_day = models.IntegerField()\n week_day_name = models.CharField(max_length=20)\n start = models.CharField(max_length=5)\n end = models.CharField(max_length=5)\n start_seconds = models.IntegerField()\n end_seconds = models.IntegerField()\n\n def __str__(self):\n return f\"{self.teacher} | from {self.start} to {self.end}, {self.week_day_name}\"\n\n" }, { "alpha_fraction": 0.8031495809555054, "alphanum_fraction": 0.8031495809555054, "avg_line_length": 17.14285659790039, "blob_id": "c4351feed4a81fd6991d82f98bded8c92814df28", "content_id": "4164b8fa18cf49efc15febac6a5fc475e2b3c303", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "permissive", "max_line_length": 35, "num_lines": 7, "path": "/web/server/admin.py", "repo_name": "p-schlickmann/proffy-app", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom . import models\n\n\nadmin.site.register(models.Teacher)\nadmin.site.register(models.Class)\n" } ]
6
lbialik/ginkgo_challenge
https://github.com/lbialik/ginkgo_challenge
013239c30cf12debb1bacb49776d10294829ea74
53b77073f6fff6ffb3a6e978a8b6aa11b3c72baf
91558fc8e29f29ba3fdd5c1d2587a6148980d6fd
refs/heads/master
2021-09-27T10:07:50.110020
2020-01-21T05:25:05
2020-01-21T05:25:05
234,404,189
0
0
null
2020-01-16T20:19:26
2020-01-21T05:25:07
2021-09-22T18:25:06
Python
[ { "alpha_fraction": 0.6644474267959595, "alphanum_fraction": 0.6657789349555969, "avg_line_length": 38.52631759643555, "blob_id": "f1692f058347c042dcc6e3b5a0a3e37b85eec288", "content_id": "fd492fb57758cd342d0d86de36bf783e04388d80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 105, "num_lines": 19, "path": "/sequence_matcher/views.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom .alignment import align\nfrom .models import Sequence\nfrom django.utils import timezone\n\ndef sequence_matcher(request):\n if request.method == 'POST':\n sequence = request.POST.get('info', None).upper()\n protein, index = align(sequence)\n if index == -1:\n protein = 'Not Found'\n index = ''\n seq, created = Sequence.objects.get_or_create(title = sequence, index = index, protein = protein)\n seq.timestamp = timezone.now()\n seq.save()\n data = Sequence.objects.all().order_by('timestamp').reverse()\n sequence_dict = {'sequences':data}\n return render(request, 'sequence_matcher.html', sequence_dict)\n" }, { "alpha_fraction": 0.5766773223876953, "alphanum_fraction": 0.5782747864723206, "avg_line_length": 37.25, "blob_id": "0aa91ea69f1a705bbde56ce7481f6e0cac005f19", "content_id": "6ea482ef55352396711b7c1b80f29d3d95a0768d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 120, "num_lines": 16, "path": "/sequence_matcher/data_processing.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "import os\r\nimport Bio\r\nfrom Bio import Seq, SeqIO\r\n\r\ndef get_proteins():\r\n path = \"../ginkgo/data\"\r\n proteins = {}\r\n for file_name in os.listdir(path):\r\n file_path = os.path.join(path, file_name)\r\n with open(file_path, \"r\") as sequence_data:\r\n for index, record in enumerate(SeqIO.parse(sequence_data, \"genbank\")):\r\n seq = str(record.seq)\r\n for feature in record.features:\r\n if feature.type == 'CDS':\r\n proteins[feature.qualifiers['protein_id'][0]] = seq[feature.location.start:feature.location.end]\r\n return proteins" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 23.33333396911621, "blob_id": "ca4d185550cf77a0a1f6901f158e35f2db06456d", "content_id": "b78f4bbe70910a0e3abe3407b704b3e7b3f9c087", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 62, "num_lines": 6, "path": "/sequence_matcher/urls.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "from django.urls import path\r\nfrom sequence_matcher import views\r\n\r\nurlpatterns = [\r\n path('', views.sequence_matcher, name='sequence_matcher'),\r\n]" }, { "alpha_fraction": 0.7432950139045715, "alphanum_fraction": 0.7509578466415405, "avg_line_length": 31.625, "blob_id": "e5c575b453cca133d9822539ad8a3e68d785a1cd", "content_id": "743ea017417ea6b000513848da7d4801a7f94ad7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 58, "num_lines": 8, "path": "/sequence_matcher/models.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\nclass Sequence(models.Model):\n title = models.TextField()\n protein = models.TextField()\n index = models.CharField(max_length=20)\n timestamp = models.DateTimeField(default=timezone.now)\n" }, { "alpha_fraction": 0.6270626783370972, "alphanum_fraction": 0.6336633563041687, "avg_line_length": 23.41666603088379, "blob_id": "51b3b05d92c5c300e293e60503971d7f688dbc71", "content_id": "a82bd3a24039f2ef87e25dc773c2552095753dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 48, "num_lines": 12, "path": "/sequence_matcher/alignment.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "import sys\r\nimport Bio\r\nfrom Bio.Seq import Seq\r\nfrom .data_processing import get_proteins\r\n\r\ndef align(sequence):\r\n proteins = get_proteins()\r\n for protein in proteins:\r\n index = proteins[protein].find(sequence)\r\n if index > -1:\r\n return protein, index\r\n return '', -1" }, { "alpha_fraction": 0.44117647409439087, "alphanum_fraction": 0.6176470518112183, "avg_line_length": 16, "blob_id": "d4b9fb0d0b041b9992ea58edea3c74af1c1ea937", "content_id": "42152727e47171152ba2a5113c75536d66edc4b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 34, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/requirements.txt", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "biopython == 1.76\r\nDjango == 3.0.2" }, { "alpha_fraction": 0.7830188870429993, "alphanum_fraction": 0.7830188870429993, "avg_line_length": 20.200000762939453, "blob_id": "a09c62330b5a3399bdd926633f781d9a4bf4b908", "content_id": "ad7c3c26b0c8887c1e449b3bba998e50d223784c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/sequence_matcher/apps.py", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass SequenceMatcherConfig(AppConfig):\n name = 'sequence_matcher'\n" }, { "alpha_fraction": 0.7312661409378052, "alphanum_fraction": 0.7312661409378052, "avg_line_length": 15.82608699798584, "blob_id": "706a4502ca0c314b6d51342ca2145bea7886aa29", "content_id": "e29bb6f5b2b28773731f68111bacf8524f1b1031", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 387, "license_type": "no_license", "max_line_length": 102, "num_lines": 23, "path": "/README.md", "repo_name": "lbialik/ginkgo_challenge", "src_encoding": "UTF-8", "text": "# ginkgo_challenge\n\n## Description\n\nA web app that finds a dna sequence's location in proteins.\n\n## Requirements\n\n```bash\n\n# Install Python requirements\n$ pip install -r requirements.txt\n```\n## Running\n\n```bash\n\n# Run the server\n$ python manage.py runserver\n```\n\n### Add Protein Data\nTo add more proteins to check sequences against, add their genabnk files from ncbi to the data folder.\n" } ]
8
Cuchau/MCOC2021-P0
https://github.com/Cuchau/MCOC2021-P0
c04718806ff66e15d223fdf065fc1c7d0b63cc90
d1850d172a312d433f3469edae7c35f29f4ba78f
8bdf496f99b05867c5b14aab50e6f00f27e926cb
refs/heads/main
2023-07-25T03:05:00.812358
2021-09-03T17:07:33
2021-09-03T17:07:33
392,094,444
0
0
null
2021-08-02T21:06:41
2021-08-02T16:25:56
2021-08-02T16:25:54
null
[ { "alpha_fraction": 0.4678770899772644, "alphanum_fraction": 0.5335195660591125, "avg_line_length": 23.5, "blob_id": "02371923072f3b25c30587a8392e19b72d67ce62", "content_id": "7f4f82291802a0ea27de26aa3b5fc48a44c9b197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 69, "num_lines": 28, "path": "/timing_matmul.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import zeros\r\nfrom time import perf_counter\r\nimport matplotlib as plt\r\n\r\nN = 3\r\nNs = [10,100,1000,2000,3000,4000,5000,6000,7000,8000]\r\ndts = []\r\nmemt = []\r\narchivo= open(\"rendimiento.txt\",\"w\")\r\n\r\nfor i in range (10):\r\n for N in Ns:\r\n uso_memoria_total = 0\r\n A = zeros((N,N))+1\r\n B = zeros((N,N))+2\r\n \r\n t1 = perf_counter()\r\n C =A@B\r\n t2 = perf_counter()\r\n\r\n uso_memoria_total= A.nbytes + B.nbytes + C.nbytes\r\n dt= t2-t1\r\n dts.append(dt)\r\n memt.append(uso_memoria_total)\r\n print(f\"N = {N} dt = {dt} s mem = {uso_memoria_total} bytes\")\r\n archivo.write(f\"{N} {dt} {uso_memoria_total}\\n\")\r\n \r\narchivo.close()\r\n\r\n" }, { "alpha_fraction": 0.5005807280540466, "alphanum_fraction": 0.5760743618011475, "avg_line_length": 23.909090042114258, "blob_id": "e82ce645d90e7807ee0587f502a5e9e77c15bf1c", "content_id": "421cf564bcaf3126ac83974f2f53e25869b2253c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "no_license", "max_line_length": 58, "num_lines": 33, "path": "/P0E6/codigos/matriz_dispersa_inv.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "import scipy.sparse as sp\r\nimport scipy.sparse.linalg as lin\r\nfrom scipy.sparse import lil_matrix\r\nfrom numpy import double, dtype,ones,eye\r\nfrom time import perf_counter\r\n\r\ndef matriz_laplaciana(N, t=double):\r\n e= sp.eye(N,dtype=double)-sp.eye(N,N,1,dtype=double)\r\n return (e+e.T)\r\n\r\nNs = [10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000]\r\ndts1 = []\r\ndts2 = []\r\n\r\narchivo= open(\"matriz_dispersa_inv.txt\",\"w\")\r\n\r\nfor i in range (10):\r\n for N in Ns:\r\n t1= perf_counter()\r\n A= matriz_laplaciana(N)\r\n Acsc=sp.csc_matrix(A)\r\n t2 = perf_counter()\r\n Ainv=lin.inv(Acsc)\r\n t3 = perf_counter()\r\n\r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4445876181125641, "alphanum_fraction": 0.5489690899848938, "avg_line_length": 20.764705657958984, "blob_id": "055e25f991e3e79cac972f5bc027ba66cb059acc", "content_id": "bb05f1f08aef601f9e855c917662adf07042240b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 78, "num_lines": 34, "path": "/P0E5/Codigo/matriz_llena.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import double, eye\r\nfrom time import perf_counter\r\nimport matplotlib as plt\r\n\r\n#tipo de dato double\r\ndef matriz_laplaciana(N, t=double):\r\n e= eye(N)-eye(N,N,1)\r\n return t(e+e.T)\r\n\r\nNs = [10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000]\r\n\r\ndts1 = []\r\ndts2 = []\r\n\r\narchivo= open(\"Matmul_laplaciana.txt\",\"w\")\r\n\r\nfor i in range (10):\r\n for N in Ns:\r\n t1= perf_counter()\r\n A= matriz_laplaciana(N)\r\n B= matriz_laplaciana(N)\r\n t2 = perf_counter()\r\n C =A@B\r\n t3 = perf_counter()\r\n\r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()\r\n\r\n" }, { "alpha_fraction": 0.4363636374473572, "alphanum_fraction": 0.6236363649368286, "avg_line_length": 29.371429443359375, "blob_id": "c354488670c3f495bfb8bcdc820e0eb522421a89", "content_id": "a3160702886852d9559ff72357d586817887a579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 229, "num_lines": 35, "path": "/P0E6/codigos/matriz_dispersa_solve.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy.typing import NBitBase\r\nimport scipy.sparse as sp\r\nimport scipy.sparse.linalg as lin\r\nfrom scipy.sparse import lil_matrix\r\nfrom numpy import double, dtype,ones,eye\r\nfrom time import perf_counter\r\n\r\ndef matriz_laplaciana(N, t=double):\r\n e= sp.eye(N,dtype=double)-sp.eye(N,N,1,dtype=double)\r\n return (e+e.T)\r\n\r\nNs = [10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,7500,8000,8500,9000,9500,10000,10500,11000,11500,12000,12500,13000,13500,14000,14500,15000,15500,16000,16500,17000,17500,18000,18500,19000,19500,20000]\r\ndts1 = []\r\ndts2 = []\r\n\r\narchivo= open(\"matriz_dispersa_solv.txt\",\"w\")\r\n\r\nfor i in range (10):\r\n for N in Ns:\r\n t1= perf_counter()\r\n A= matriz_laplaciana(N)\r\n B= ones(N,dtype=double)\r\n Acsr=sp.csr_matrix(A)\r\n t2 = perf_counter()\r\n x=lin.spsolve(Acsr,B)\r\n t3 = perf_counter()\r\n\r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()\r\n\r\n" }, { "alpha_fraction": 0.44936707615852356, "alphanum_fraction": 0.5305907130241394, "avg_line_length": 26.66666603088379, "blob_id": "1c7b367f6116a92ee87480d030d3fd629fa5f5dc", "content_id": "55209c94c2f5a668b4a27c777640373f4ce558f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 86, "num_lines": 33, "path": "/P0E6/codigos/matriz_llena_solve.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import double, eye, ones\r\nfrom time import perf_counter\r\nfrom scipy.linalg import inv, solve\r\n#Para trabajar el tipo de dato float o double sacar el # para que funcione esa funcion\r\n\r\n#tipo de dato float\r\ndef matriz_laplaciano(N, t=double):\r\n e= eye(N)-eye(N,N,1)\r\n return t(e+e.T)\r\n\r\nNs=[10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500]\r\ndts1=[]\r\ndts2=[]\r\n\r\narchivo= open(\"matriz_llena_solv.txt\",\"w\")\r\n\r\nfor i in range(10):\r\n for N in Ns:\r\n t1=perf_counter()\r\n A= matriz_laplaciano(N)\r\n B= ones(N)\r\n t2=perf_counter()\r\n x=solve(A,B,assume_a='pos')\r\n t3=perf_counter()\r\n\r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()\r\n\r\n" }, { "alpha_fraction": 0.43350863456726074, "alphanum_fraction": 0.6190834045410156, "avg_line_length": 24.13725471496582, "blob_id": "8f58f47457067592dcd500cd181e124bf0c7df28", "content_id": "ef66a431178e0f7194ea0eed9bdb021d130dc7ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 119, "num_lines": 51, "path": "/grafico.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\n\r\nNs = []\r\ndts = []\r\nmemt = []\r\n\r\narchivo= open(\"rendimiento.txt\", \"r\")\r\n\r\n\r\nfor line in archivo:\r\n sep= line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n mem=int(sep[2])\r\n \r\n Ns.append(N)\r\n dts.append(dt)\r\n memt.append(mem)\r\n\r\n\r\narchivo.close()\r\n\r\nplt.figure(1)\r\na=plt.subplot(2,1,1)\r\nK=10\r\nfor i in range (K):\r\n plt.loglog(Ns[i*K:(i+1)*K],dts[i*K:(i+1)*K],marker=\"o\",linestyle=\"-\")\r\n\r\nplt.grid()\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,10000,20000],[10,20,50,100,200,500,1000,2000,5000,10000,20000])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\na.axes.xaxis.set_ticklabels([])\r\na.set_ylabel(\"Tiempo transcurrido (s)\")\r\na.set_title(\"Rendimiento A@B\")\r\n\r\n\r\nb=plt.subplot(2,1,2)\r\nplt.loglog(Ns,memt,marker=\"o\")\r\nplt.plot(0,16)\r\nplt.grid()\r\nplt.xticks(rotation=45)\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,10000,20000],[10,20,50,100,200,500,1000,2000,5000,10000,20000])\r\nplt.yticks([1000,10000,100000,(1e6),(1e7),(1e8),(1e9),(1e10)],[\"1KB\",\"10KB\",\"100KB\",\"1MB\",\"10MB\",\"100MB\",\"1GB\",\"10GB\"])\r\nplt.axhline(y=1.6e10, color=\"k\", linestyle=\"--\")\r\nb.set_ylabel(\"Uso de memoria (s)\")\r\nb.set_xlabel(\"Tamaño de matriz N\")\r\n\r\nplt.savefig(\".jpg\")\r\nplt.tight_layout()\r\nplt.show()" }, { "alpha_fraction": 0.41344955563545227, "alphanum_fraction": 0.4993773400783539, "avg_line_length": 24.83333396911621, "blob_id": "8cd4bc22a005130f1dfbf460648fb50c079c1673", "content_id": "8bc571380c396dbe97b626918c252bf1d08c6fc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/P0E6/codigos/matriz_llena_inv.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import double,eye\r\nfrom time import perf_counter\r\nfrom scipy.linalg import inv \r\n\r\ndef matriz_laplaciana(N, t=double):\r\n e= eye(N)-eye(N,N,1)\r\n return t(e+e.T)\r\n\r\nNs=[10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500]\r\ndts1=[]\r\ndts2=[]\r\n\r\narchivo= open(\"matriz_llena_inv.txt\",\"w\")\r\n\r\nfor i in range(10):\r\n for N in Ns:\r\n t1=perf_counter()\r\n A= matriz_laplaciana(N)\r\n t2=perf_counter()\r\n A_inv= inv(A,overwrite_a=False)\r\n t3=perf_counter()\r\n \r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()" }, { "alpha_fraction": 0.47158217430114746, "alphanum_fraction": 0.617511510848999, "avg_line_length": 29.39759063720703, "blob_id": "d675123944e926827f21e40f201b8ac8e85fbd59", "content_id": "e0d5d10b1b35d17e76bdb2d56cb7c9d1e508fe17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 111, "num_lines": 83, "path": "/P0E6/codigos/grafico_mat_llena_inv.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.core.fromnumeric import mean\r\n\r\nNs = []\r\ndts1 = []\r\ndts2 = []\r\n\r\narchivo= open(\"matriz_llena_inv.txt\", \"r\")\r\n\r\nfor line in archivo:\r\n sep= line.split()\r\n N=int(sep[0])\r\n dt1=float(sep[1])\r\n dt2=float(sep[2])\r\n\r\n Ns.append(N)\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n\r\narchivo.close()\r\n\r\nx1=[0,Ns[11]]\r\ny1=[max(dts1),max(dts1)]\r\nx2=[Ns[0],Ns[11]]\r\ny2=[dts1[0],max(dts1)]\r\nx3=[Ns[0],Ns[11]]\r\ny3=[dts1[0]**2,max(dts1)]\r\nx4=[Ns[0],Ns[11]]\r\ny4=[dts1[0]**3,max(dts1)]\r\nx5=[Ns[0],Ns[11]]\r\ny5=[dts1[0]**4,max(dts1)]\r\n\r\nplt.figure(1)\r\n#Grafico tiempo de ensamblado\r\na=plt.subplot(2,1,1)\r\nK=12\r\nfor i in range (K):\r\n plt.loglog(Ns[i*K:(i+1)*K],dts1[i*K:(i+1)*K],marker=\"o\",linestyle=\"-\",color=\"gray\",alpha=0.5)\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,10000,20000],[10,20,50,100,200,500,1000,2000,5000,10000,20000])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.plot(x1,y1,linestyle=\"--\",color=\"royalblue\", label= \"constante\")\r\nplt.plot(x2,y2,linestyle=\"--\",color=\"y\",label= \"O(N)\")\r\nplt.plot(x3,y3,linestyle=\"--\",color=\"g\",label= \"O(N^2)\")\r\nplt.plot(x4,y4,linestyle=\"--\",color=\"r\",label= \"O(N^3)\")\r\nplt.plot(x5,y5,linestyle=\"--\",color=\"m\",label= \"O(N^4)\")\r\nplt.ylim(0.00001,600)\r\n\r\na.axes.xaxis.set_ticklabels([])\r\na.set_ylabel(\"Tiempo de ensamblado (s)\")\r\na.set_title(\"Complejidad computacional matriz llena inv\")\r\n\r\nx1=[0,Ns[11]]\r\ny1=[max(dts2),max(dts2)]\r\nx2=[Ns[0],Ns[11]]\r\ny2=[dts2[0],max(dts2)]\r\nx3=[Ns[0],Ns[11]]\r\ny3=[dts2[0]**2,max(dts2)]\r\nx4=[Ns[0],Ns[11]]\r\ny4=[dts2[0]**3,max(dts2)]\r\nx5=[Ns[0],Ns[11]]\r\ny5=[dts2[0]**4,max(dts2)]\r\n\r\n#Grafico tiempo de solucion\r\nb=plt.subplot(2,1,2)\r\nK=12\r\nfor i in range (K):\r\n plt.loglog(Ns[i*K:(i+1)*K],dts2[i*K:(i+1)*K],marker=\"o\",linestyle=\"-\",color=\"gray\",alpha=0.5)\r\nplt.xticks(rotation=45)\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,10000,20000],[10,20,50,100,200,500,1000,2000,5000,10000,20000])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.plot(x1,y1,linestyle=\"--\",color=\"royalblue\",label= \"constante\")\r\nplt.plot(x2,y2,linestyle=\"--\",color=\"y\",label= \"O(N)\")\r\nplt.plot(x3,y3,linestyle=\"--\",color=\"g\",label= \"O(N^2)\")\r\nplt.plot(x4,y4,linestyle=\"--\",color=\"r\",label= \"O(N^3)\")\r\nplt.plot(x5,y5,linestyle=\"--\",color=\"m\",label= \"O(N^4)\")\r\nplt.ylim(0.00001,600)\r\nb.set_ylabel(\"Tiempo de solucion (s)\")\r\nb.set_xlabel(\"Tamaño de matriz N\")\r\nb.legend(loc=\"upper left\")\r\nplt.tight_layout()\r\nplt.savefig(\"matriz_llena_inv\")\r\nplt.show()" }, { "alpha_fraction": 0.47821101546287537, "alphanum_fraction": 0.5332568883895874, "avg_line_length": 26.129032135009766, "blob_id": "ec8b5d7b6b34a7692c81e5d05659542e059d12fd", "content_id": "8304118f9a41c6e576bf5b134b8da9ccb0fcf9f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 76, "num_lines": 31, "path": "/P0E3/Codigos/timing_inv_caso_3_single.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import half, single, double, longdouble, eye\r\nfrom time import perf_counter\r\nfrom scipy.linalg import inv \r\n\r\ndef matriz_laplaciano(N, t=single):\r\n e= eye(N)-eye(N,N,1)\r\n return t(e+e.T)\r\n\r\nNs=[3,4,10,100,1000,2000,3000,4000,5000,6000,7000,8000]\r\nmemt=[]\r\ndts=[]\r\n\r\narchivo= open(\"single_caso_3.txt\",\"w\")\r\n\r\nfor i in range(10):\r\n for N in Ns:\r\n uso_memoria_total = 0\r\n A= matriz_laplaciano(N)\r\n\r\n t1=perf_counter()\r\n A_inv= inv(A,overwrite_a=True)\r\n t2=perf_counter()\r\n dt= t2-t1\r\n dts.append(dt)\r\n\r\n uso_memoria_total= A_inv.nbytes\r\n memt.append(uso_memoria_total)\r\n print (f\"N = {N} dt = {dt} s mem = {uso_memoria_total} bytes\")\r\n archivo.write(f\"{N} {dt} {uso_memoria_total}\\n\")\r\n\r\narchivo.close\r\n" }, { "alpha_fraction": 0.5131690502166748, "alphanum_fraction": 0.5930331349372864, "avg_line_length": 21.326732635498047, "blob_id": "a0eaf016b6a4a60eb7c8ac5ae30f2bc895085142", "content_id": "b5370ffcefe622a68c96a679e821efebdf3ceda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2355, "license_type": "no_license", "max_line_length": 103, "num_lines": 101, "path": "/P0E4/codigo/grafico_solve_single.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\n\r\nNs_1 = []\r\nNs_2 = []\r\nNs_3 = []\r\nNs_4 = []\r\nNs_5 = []\r\nNs_6 = []\r\nNs_7 = []\r\ndts_1 = []\r\ndts_2 = []\r\ndts_3 = []\r\ndts_4 = []\r\ndts_5 = []\r\ndts_6 = []\r\ndts_7 = []\r\n\r\n#Para abrir cada archivo se cambia el nombre en open\r\narchivo1= open(\"sist_ec_caso_1_single.txt\", \"r\")\r\narchivo2= open(\"sist_ec_caso_2_single.txt\", \"r\")\r\narchivo3= open(\"sist_ec_caso_3_single.txt\", \"r\")\r\narchivo4= open(\"sist_ec_caso_4_single.txt\", \"r\")\r\narchivo5= open(\"sist_ec_caso_5_single.txt\", \"r\")\r\narchivo6= open(\"sist_ec_caso_6_single.txt\", \"r\")\r\narchivo7= open(\"sist_ec_caso_7_single.txt\", \"r\")\r\n\r\n\r\nfor line in archivo1:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_1.append(N)\r\n dts_1.append(dt)\r\n\r\nfor line in archivo2:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_2.append(N)\r\n dts_2.append(dt)\r\n\r\nfor line in archivo3:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_3.append(N)\r\n dts_3.append(dt)\r\n\r\nfor line in archivo4:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_4.append(N)\r\n dts_4.append(dt)\r\n\r\nfor line in archivo5:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_5.append(N)\r\n dts_5.append(dt)\r\n\r\nfor line in archivo6:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_6.append(N)\r\n dts_6.append(dt)\r\n\r\nfor line in archivo7:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_7.append(N)\r\n dts_7.append(dt)\r\n\r\narchivo1.close()\r\narchivo2.close()\r\narchivo3.close()\r\narchivo4.close()\r\narchivo5.close()\r\narchivo6.close()\r\narchivo7.close()\r\n\r\n\r\nplt.plot(Ns_1,dts_1,label=\"caso 1\",marker=\"o\")\r\nplt.plot(Ns_1,dts_2,label=\"caso 2\",marker=\"o\")\r\nplt.plot(Ns_1,dts_3,label=\"caso 3\",marker=\"o\")\r\nplt.plot(Ns_1,dts_4,label=\"caso 4\",marker=\"o\")\r\nplt.plot(Ns_1,dts_5,label=\"caso 5\",marker=\"o\")\r\nplt.plot(Ns_1,dts_6,label=\"caso 6\",marker=\"o\")\r\nplt.plot(Ns_1,dts_7,label=\"caso 7\",marker=\"o\")\r\nplt.loglog()\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,6500],[10,20,50,100,200,500,1000,2000,5000,6500])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Tiempo[s]\")\r\nplt.legend()\r\nplt.title(\"Caso solve con tipo de datos single\")\r\nplt.show()" }, { "alpha_fraction": 0.4540358781814575, "alphanum_fraction": 0.584080696105957, "avg_line_length": 24.969696044921875, "blob_id": "bc84ec80b20058153c39145329479b97123b5e87", "content_id": "88ee7e90868b8abd32abbf4fbdef5e1da617e809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 121, "num_lines": 33, "path": "/P0E5/Codigo/matriz_dispersa.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import double, eye,mean\r\nfrom time import perf_counter\r\nimport scipy.sparse as sparse\r\nimport matplotlib as plt\r\n\r\n#tipo de dato double\r\ndef matriz_laplaciana(N, t=double):\r\n e= sparse.eye(N,dtype=double)-sparse.eye(N,N,1,dtype=double)\r\n return (e+e.T)\r\n \r\nNs = [10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,7500,8000,8500,9000,9500,10000,15000,20000]\r\ndts1 = []\r\ndts2 = []\r\n\r\narchivo= open(\"Matmul_dispersa.txt\",\"w\")\r\n\r\nfor i in range (10):\r\n for N in Ns:\r\n t1= perf_counter()\r\n A= matriz_laplaciana(N)\r\n B= matriz_laplaciana(N)\r\n t2 = perf_counter()\r\n C =A@B\r\n t3 = perf_counter()\r\n\r\n dt1= t2-t1\r\n dt2= t3-t2\r\n dts1.append(dt1)\r\n dts2.append(dt2)\r\n print(f\"N = {N} dt1 = {dt1} s dt2 = {dt2} s\")\r\n archivo.write(f\"{N} {dt1} {dt2} \\n\")\r\n\r\narchivo.close()\r\n\r\n" }, { "alpha_fraction": 0.492397665977478, "alphanum_fraction": 0.5853801369667053, "avg_line_length": 19.94871711730957, "blob_id": "96bce19e284c0fd5e431371f37ce4594fb972c2c", "content_id": "14e69c3840281c0b97b2e21b2b1ede02c67cc393", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1711, "license_type": "no_license", "max_line_length": 103, "num_lines": 78, "path": "/P0E4/codigo/grafico_comparacion_eigh.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\n\r\nNs_1 = []\r\nNs_2 = []\r\nNs_3 = []\r\nNs_4 = []\r\nNs_5 = []\r\nNs_6 = []\r\nNs_7 = []\r\nNs_8 = []\r\nNs_9 = []\r\ndts_1 = []\r\ndts_2 = []\r\ndts_3 = []\r\ndts_4 = []\r\ndts_5 = []\r\ndts_6 = []\r\ndts_7 = []\r\ndts_8 = []\r\ndts_9 = []\r\n\r\n#Para abrir cada archivo se cambia el nombre en open\r\narchivo1= open(\"vec_val_caso_3_a_double.txt\", \"r\")\r\narchivo2= open(\"vec_val_caso_3_b_double.txt\", \"r\")\r\narchivo3= open(\"vec_val_caso_3_a_single.txt\", \"r\")\r\narchivo4= open(\"vec_val_caso_3_a_single.txt\", \"r\")\r\n\r\n\r\n\r\nfor line in archivo1:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_1.append(N)\r\n dts_1.append(dt)\r\n\r\nfor line in archivo2:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_2.append(N)\r\n dts_2.append(dt)\r\n\r\nfor line in archivo3:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_3.append(N)\r\n dts_3.append(dt)\r\n\r\nfor line in archivo4:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_4.append(N)\r\n dts_4.append(dt)\r\n\r\n\r\narchivo1.close()\r\narchivo2.close()\r\narchivo3.close()\r\narchivo4.close()\r\n\r\n\r\nplt.plot(Ns_1,dts_1,label=\"caso 3-a,double\",marker=\"o\")\r\nplt.plot(Ns_2,dts_2,label=\"caso 3-b,double\",marker=\"o\")\r\nplt.plot(Ns_3,dts_3,label=\"caso 3-a,single\",marker=\"o\")\r\nplt.plot(Ns_4,dts_4,label=\"caso 3-b,single\",marker=\"o\")\r\n\r\nplt.loglog()\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,6500],[10,20,50,100,200,500,1000,2000,5000,6500])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Tiempo[s]\")\r\nplt.title(\"comparacion eigh double vs single\")\r\nplt.legend()\r\nplt.show()" }, { "alpha_fraction": 0.6962583065032959, "alphanum_fraction": 0.7810757160186768, "avg_line_length": 65.9337387084961, "blob_id": "359b1b81e396b4b8bb09719decf926cfc250a8c2", "content_id": "a9c4382d827f2e6c5ac547c82a332faa8414a93f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11208, "license_type": "no_license", "max_line_length": 950, "num_lines": 166, "path": "/README.md", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "# MCOC2021-P0\n\n# Mi computador principal\n\n* Marca/modelo: Armado\n* Tipo: Desktop\n* Año adquisición: 2018\n* Procesador:\n * Marca/Modelo: Intel Core i3-8100\n * Velocidad Base: 3.60 GHz\n * Velocidad Máxima: 3.60 GHz\n * Numero de núcleos: 4 \n * Numero de hilos: 4\n * Arquitectura: x86_64\n * Set de instrucciones: Intel SSE4.1, Intel SSE4.2, Intel AVX2\n* Tamaño de las cachés del procesador\n * L1: 256 KB\n * L2: 1 MB\n * L3: 6 MB\n* Memoria \n * Total: 16 GB\n * Tipo memoria: DDR4\n * Velocidad 2400 MHz \n * Numero de (SO)DIMM: 2\n* Tarjeta Gráfica\n * Marca / Modelo: Amd Radeon Rx 570\n * Memoria dedicada: 4 GB\n * Resolución: 1920 x 1080\n* Disco 1: \n * Marca: Crucial\n * Tipo: SSD\n * Tamaño: 500 GB\n * Particiones: 3\n * Sistema de archivos: NTFS\n* Disco 2: \n * Marca: Western digital\n * Tipo: HDD\n * Tamaño: 1TB\n * Particiones: 1\n * Sistema de archivos: NTFS\n\n \n* Dirección IP (Interna, del router): 192.168.100.1\n* Dirección IP (Externa, del ISP): 2800:300:6271:6c70::1\n* Proveedor internet: Entel Chile S.A.\n\nPREGUNTA 2\n\n¿Cómo difiere del gráfico del profesor/ayudante?\n R:Se puede observar como el grafico se comporta de manera similar al del ayudante, claramente habrá diferencias ya que no es el mismo computador y no se probaron con las mismas cantidades de matrices, este comportamiento similar se puede observar en ambos gráficos (uso de memoria y tiempo transcurrido).\n\n¿A qué se pueden deber las diferencias en cada corrida?\n R:Se pueden deber a la potencia de hardware de cada computador, como la memora ram, la cantidad de núcleos y memoria cache del procesador, como también el tamaño de matrices que se probaron, ya que matrices de mayor tamaño necesitaran mayores recursos.\n\nEl gráfico de uso de memoria es lineal con el tamaño de matriz, pero el de tiempo transcurrido no lo es ¿porqué puede ser?\n R:Puede ser debido a la cantidad de memoria que deja reservada para continuar haciendo procesos, ya que al terminar de ejecutar una matriz grande al empezar otra matriz tendrá menor memoria para ocupar por un momento.\n\n¿Qué versión de python está usando?\n R:3.9.6\n \n¿Qué versión de numpy está usando?\n R:1.21.1\n\nDurante la ejecución de su código ¿se utiliza más de un procesador? Muestre una imagen (screenshot) de su uso de procesador durante alguna corrida para confirmar. \n R: Como se puede ver se están usando los 4 núcleos del procesador\n \n ![image](https://user-images.githubusercontent.com/88348645/128414845-eb59632c-f5e4-4eb4-af60-307d25af9d1c.png)\n \n \n ![image](https://user-images.githubusercontent.com/88348645/128416213-c4afa072-7d8e-4a88-9216-aaa80c392212.png)\n \n # Tarea 3 (P0E3)\n \n Durante la corrida de los diferentes programas se observo el uso del procesador y memoria que se utilizaban, mientras corrian los programas en los distintos casos se pudo percibir que tenian un patron, el cual era que mientras mas chica era el tamaño de las matrices, menos procesador y memoria se utilizaban, en cambio cuando el tamaño de las matrices crecian el uso de cpu y memoria aumentaban como se muestra en las siguientes imagenes.\n \n ![single](https://user-images.githubusercontent.com/88348645/129987950-30c94d85-42f1-452e-be56-1dd9a0f61126.png)\n \n ![single2](https://user-images.githubusercontent.com/88348645/129987958-87b816c2-e395-430c-ba24-0cf023a6a39c.png)\n\nTambien se puede ver como los 4 nucleos del procesador trabajan al mismo tiempo y con practicamente la misma intensidad, esto es debido a que se dividen entre los 4 la tarea de realizar el codigo, realizando calculos simultaneamente, otro aspecto que influye es la memoria cache del procesador, ya que aqui es donde almacena los datos e instrucciones que mas esta utilizando en el momento, por lo cual si mi procesador tuviera mas nucleos y memoria cache, el codigo podria realizarse con mayor rapidez .\n\nLa unica matriz que no se invirtio fue al usar numpy con el tipo de dato half, todos los demas casos tuvieron matrices invertidas.\nAl observar los graficos, se llego a la conclusion que al invertir la matriz tanto con numpy o scipy tienen un rendimiento muy similar, ya que ambos estan cerca de los 10 segundos, donde el caso de scipy.linalg.inv con overwrite_a=True llegaba al menor tiempo, aunque la diferencia es casi nula.\n\n![longdouble_caso_1](https://user-images.githubusercontent.com/88348645/129989567-b00d7643-46db-43ea-acf4-495ff6cf6df9.png)\n![longdouble_caso_2](https://user-images.githubusercontent.com/88348645/129989573-d7e4f5c5-e9e5-42ea-a5e4-97c2b9efc0d5.png)\n![longdouble_caso_3](https://user-images.githubusercontent.com/88348645/129989576-0e3720f6-5379-41f3-ba2b-6c1d5b57bc35.png)\n \nesto ocurre para los 4 tipos de datos, pero con longdouble es mas perceptible.\n\n# Tarea 4 (P0e4)\n\nEn el caso de solve para los datos tipo single se ve para la mayoría de los casos una pequeña mejora en el tiempo, esto puede ser a que los datos tipo single tienen un tamaño menor a los double\n\n![caso solve con tipos de datos double](https://user-images.githubusercontent.com/88348645/130308369-8a6b0512-8781-4f1a-9bb5-75a8947e8e59.png)\n\n![caso solve con tipos de datos single](https://user-images.githubusercontent.com/88348645/130308370-3ca36741-c0fe-408c-b478-b7456c2c4397.png)\n\n\nPero en ambos tipos de datos se cumple que al ocupar el caso 3 (assume_a= “pos”) se tiene el menor tiempo de ejecución, por lo que es el mas optimo y en este caso el tiempo de ejecución de los datos singles es menor al final.\n\n![comparacion solve double vs single](https://user-images.githubusercontent.com/88348645/130308373-54b12195-dd60-4b38-8269-6759cdeb3dd8.png)\n\n\nEn el caso de eigh pasa algo similar que en solve con los datos de tipo double y single, ya que single vuelve a tener menores tiempo de ejecución\n\n![caso eigh con tipo de datos double](https://user-images.githubusercontent.com/88348645/130308374-27feb10b-db3f-4984-8691-838ce3ed881e.png)\n\n![caso eigh con tipo de datos single](https://user-images.githubusercontent.com/88348645/130308376-8cd11761-15e8-4ca5-bfa3-6270b96266ab.png)\n\n\nEn ambos casos, el caso 3a y 3b (overwrite_a=False y overwrite_a=True) dan los menores tiempo de espera siendo prácticamente iguales, esto puede deberse en que en estos procesos se lleva muchos más procesos que en el solve, por lo que los tipos de datos no deben influir mucho.\n\n![comparacion eigh double vs single](https://user-images.githubusercontent.com/88348645/130308383-bebd682c-916b-42ef-9803-56391ca4a21c.png)\n\nEn el caso de uso de cpu era bastante desigual para solve y eigh, esto puede deberse a la rapidez con la que resolvia las matrices, siendo solve la que más cpu ocupo, esto puede deberse a que se resolvieron matrices de mayor tamaño que en el caso de eigh, esto simplemente se debio a que en el caso de eigh al sobrepasar matrices de tamaño 3000 este se demoraba más de 2 minutos, pero al bajar a 2700 baja considerablemente su tiempo, llegando a tiempos cercanos al minuto con diez segundo.\n\n![cpu_solve_1](https://user-images.githubusercontent.com/88348645/130308454-a22dd626-dd88-4e59-b095-abbfebeff1a3.png)\n![cpu_eigh_1](https://user-images.githubusercontent.com/88348645/130308456-8d3f2cfe-4a1e-4725-9629-9d87e6c7adf1.png)\n\n# Tarea 5(P0E5)\n\n```\n#tipo de dato double, matriz laplaciana dispersa\ndef matriz_laplaciana(N, t=double):\n e= sparse.eye(N,dtype=double)-sparse.eye(N,N,1,dtype=double)\n return (e+e.T)\n#tipo de dato double, matriz laplaciana llena\ndef matriz_laplaciana(N, t=double):\n e= eye(N)-eye(N,N,1)\n return t(e+e.T) \n```\nSe puede observar como la matriz llena al tener que guardar los ceros de la matriz, ósea tener que guardar más información es más lenta al momento de ensamblar las matrices, como al momento de resolver la multiplicación de matrices laplacianos, por esto mismo en el caso de la matriz llena se realizaron cálculos con tamaño de matrices menores a la de matrices dispersa, ya que se demoraban unos 2 minutos aproximadamente en resolver las 10 corridas, en cambio al realizar los cálculos con la matriz dispersa se pudo llegar a tamaño de matrices de 20000 sin problemas, esto posiblemente debido a que no necesitaba utilizar mucha memoria del procesador, ya que solo guarda los valores que no son ceros de la matriz, estos son una cantidad de datos muy chicas comparadas con la cantidad de ceros que si tendría que guardar. En el caso de la multiplicación de matrices sucede lo mismo, es más eficiente el caso de la matriz dispersa que la matriz llena.\n\n#matriz llena\n![grafico_mat_llena](https://user-images.githubusercontent.com/88348645/131186197-2662c48c-5389-4f0c-8514-319ac5a6c581.png)\n\n#matriz dispersa\n![grafico_mat_dispersa](https://user-images.githubusercontent.com/88348645/131186245-4797115c-be95-435f-9efe-e76bb469616a.png)\n\n# Tarea 6(P0E6)\n\n```\n#tipo de dato double, matriz laplaciana llena\ndef matriz_laplaciano(N, t=double):\n e= eye(N)-eye(N,N,1)\n return t(e+e.T)\n#tipo de dato double, matriz laplaciana dispersa \ndef matriz_laplaciana(N, t=double):\n e= sp.eye(N,dtype=double)-sp.eye(N,N,1,dtype=double)\n return (e+e.T)\n```\n\nPara el caso de solve la matriz llena tiene mayor tiempo de ensamblado y de solución que la matriz dispersa, siendo que la matriz llena llega a tamaño de matrices N de 6500, en cambio la matriz dispersa llega a un tamaño de 20000 sin problemas, con tiempos de ensamblado y solución muy inferiores a los de matrices llenas, manteniendo sus tiempos de solución bastante constantes sim importar el aumento del tamaño de las matrices, en cambio para matrices llenas los tiempo de ensamblado y solución tienden a aumentar con el aumento del tamaño de las matrices.\n\n![matriz_llena_solve](https://user-images.githubusercontent.com/88348645/132042575-aba07c60-d40f-457d-b1ce-89f241129d25.png)\n![matriz_llena_inv](https://user-images.githubusercontent.com/88348645/132042580-e3d14daf-5cf6-4e6d-99f7-ebcdcb3b8f3d.png)\n\n\nPara el caso de inv sucede algo curioso, ya que el tiempo de ensamblado de la matriz llena es mayor al de las matrices dispersas, pero en el tiempo de solución se parecen bastante, incluso las matrices llenas lograron llegar a un N de 5500, en cambio las matrices dispersas solo llegaron a 5000 en el límite de tiempo de 2 minutos, esto se puede deber a que al llegar a un numero de N=100 las matrices llenas disminuyen su tiempo de solución y ensamblaje, después vuelve aumentar con el aumento del tamaño de las matrices, en cambio con las matrices dispersas al llegar a 100 se mantiene constante el tiempo de solución, pero luego sigue aumentando con el aumento del tamaño de las matrices, el tiempo de ensamblaje se mantiene mayormente constante sin importar el tamaño de las matrices. \n\n![matriz_llena_inv](https://user-images.githubusercontent.com/88348645/132042604-10bec12b-4ede-4abf-bf8d-786f32ab13be.png)\n![matriz_dispersa_inv](https://user-images.githubusercontent.com/88348645/132042610-dd5969bd-5772-45e4-b650-c2fcd16c2cea.png)\n\n\nPor ultimo las corridas para todos los casos son muy estables, por lo que se pudo observar una de cada 10 corridas tiene algún cambio mayor, pero en la mayoría se mantienen bastante cerca y con pocos cambios\n\n \n\n" }, { "alpha_fraction": 0.51488196849823, "alphanum_fraction": 0.5880944132804871, "avg_line_length": 21.399999618530273, "blob_id": "cd8271d2eb598f768eeea5e767878df0e65555f2", "content_id": "adb5f01b7606edbcd539ce2cc91c3a6ebe3c779e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2924, "license_type": "no_license", "max_line_length": 103, "num_lines": 125, "path": "/P0E4/codigo/grafico_eigh_double.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\n\r\nNs_1 = []\r\nNs_2 = []\r\nNs_3 = []\r\nNs_4 = []\r\nNs_5 = []\r\nNs_6 = []\r\nNs_7 = []\r\nNs_8 = []\r\nNs_9 = []\r\ndts_1 = []\r\ndts_2 = []\r\ndts_3 = []\r\ndts_4 = []\r\ndts_5 = []\r\ndts_6 = []\r\ndts_7 = []\r\ndts_8 = []\r\ndts_9 = []\r\n\r\n#Para abrir cada archivo se cambia el nombre en open\r\narchivo1= open(\"vec_val_caso_1_double.txt\", \"r\")\r\narchivo2= open(\"vec_val_caso_2_a_double.txt\", \"r\")\r\narchivo3= open(\"vec_val_caso_2_b_double.txt\", \"r\")\r\narchivo4= open(\"vec_val_caso_3_a_double.txt\", \"r\")\r\narchivo5= open(\"vec_val_caso_3_b_double.txt\", \"r\")\r\narchivo6= open(\"vec_val_caso_4_a_double.txt\", \"r\")\r\narchivo7= open(\"vec_val_caso_4_b_double.txt\", \"r\")\r\narchivo8= open(\"vec_val_caso_5_a_double.txt\", \"r\")\r\narchivo9= open(\"vec_val_caso_5_b_double.txt\", \"r\")\r\n\r\n\r\nfor line in archivo1:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_1.append(N)\r\n dts_1.append(dt)\r\n\r\nfor line in archivo2:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_2.append(N)\r\n dts_2.append(dt)\r\n\r\nfor line in archivo3:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_3.append(N)\r\n dts_3.append(dt)\r\n\r\nfor line in archivo4:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_4.append(N)\r\n dts_4.append(dt)\r\n\r\nfor line in archivo5:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_5.append(N)\r\n dts_5.append(dt)\r\n\r\nfor line in archivo6:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_6.append(N)\r\n dts_6.append(dt)\r\n\r\nfor line in archivo7:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_7.append(N)\r\n dts_7.append(dt)\r\n\r\nfor line in archivo8:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_8.append(N)\r\n dts_8.append(dt)\r\n\r\nfor line in archivo9:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_9.append(N)\r\n dts_9.append(dt)\r\n\r\narchivo1.close()\r\narchivo2.close()\r\narchivo3.close()\r\narchivo4.close()\r\narchivo5.close()\r\narchivo6.close()\r\narchivo7.close()\r\narchivo8.close()\r\narchivo9.close()\r\n\r\n\r\nplt.plot(Ns_1,dts_1,label=\"caso 1\",marker=\"o\")\r\nplt.plot(Ns_2,dts_2,label=\"caso 2-a\",marker=\"o\")\r\nplt.plot(Ns_3,dts_3,label=\"caso 2-b\",marker=\"o\")\r\nplt.plot(Ns_4,dts_4,label=\"caso 3-a\",marker=\"o\")\r\nplt.plot(Ns_5,dts_5,label=\"caso 3-b\",marker=\"o\")\r\nplt.plot(Ns_6,dts_6,label=\"caso 4-a\",marker=\"o\")\r\nplt.plot(Ns_7,dts_7,label=\"caso 4-b\",marker=\"o\")\r\nplt.plot(Ns_8,dts_8,label=\"caso 5-a\",marker=\"o\")\r\nplt.plot(Ns_9,dts_9,label=\"caso 5-b\",marker=\"o\")\r\nplt.loglog()\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,6500],[10,20,50,100,200,500,1000,2000,5000,6500])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Tiempo[s]\")\r\nplt.title(\"Caso eigh con tipo de datos double\")\r\nplt.legend()\r\nplt.show()" }, { "alpha_fraction": 0.44421273469924927, "alphanum_fraction": 0.5015641450881958, "avg_line_length": 23.546667098999023, "blob_id": "31425325b959d5e85f3313252d22ad4800cacfe5", "content_id": "1f159b4b2d2ea01e480990f81d46984deb459510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 86, "num_lines": 75, "path": "/P0E4/codigo/vec_val_caso_2_b.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from numpy import double, eye, ones, mean,single\r\nfrom time import perf_counter\r\nfrom scipy.linalg import inv, solve, eigh\r\n#Para trabajar el tipo de dato float o double sacar el # para que funcione esa funcion\r\n\r\n#tipo de dato float\r\ndef matriz_laplaciano(N, t=single):\r\n e= eye(N)-eye(N,N,1)\r\n return t(e+e.T)\r\n\r\n#tipo de dato double\r\n#def matriz_laplaciano(N, t=double):\r\n #e= eye(N)-eye(N,N,1)\r\n #return t(e+e.T)\r\n\r\nNs=[3,4,10,50,100,500,1000,1500]\r\ndts=[]\r\npromt=[]\r\ndtp_3=[]\r\ndtp_4=[]\r\ndtp_10=[]\r\ndtp_50=[]\r\ndtp_100=[]\r\ndtp_500=[]\r\ndtp_1000=[]\r\ndtp_1500=[]\r\n\r\n\r\narchivo= open(\"vec_val_caso_2_b_single.txt\",\"w\")\r\n#archivo= open(\"vec_val_caso_2_b_double.txt\",\"w\")\r\n\r\nfor i in range(10):\r\n for N in Ns:\r\n A= matriz_laplaciano(N)\r\n # w valores propios, h vectores propios\r\n t1=perf_counter()\r\n w,h= eigh(A,driver=\"ev\",overwrite_a=True)\r\n t2=perf_counter()\r\n dt= t2-t1\r\n if N==3:\r\n dtp_3.append(dt)\r\n elif N==4:\r\n dtp_4.append(dt)\r\n elif N==10:\r\n dtp_10.append(dt)\r\n elif N==50:\r\n dtp_50.append(dt)\r\n elif N==100:\r\n dtp_100.append(dt)\r\n elif N==500:\r\n dtp_500.append(dt)\r\n elif N==1000:\r\n dtp_1000.append(dt)\r\n elif N==1500:\r\n dtp_1500.append(dt)\r\n\r\ndts.append(dtp_3)\r\ndts.append(dtp_4)\r\ndts.append(dtp_10)\r\ndts.append(dtp_50)\r\ndts.append(dtp_100)\r\ndts.append(dtp_500)\r\ndts.append(dtp_1000)\r\ndts.append(dtp_1500)\r\n\r\n\r\n\r\n#Sacar promedio de cada matriz\r\nfor i in range(len(Ns)):\r\n prom=mean(dts[i])\r\n promt.append(prom)\r\n print (f\"N = {Ns[i]} dt = {prom} s \")\r\n archivo.write(f\"{Ns[i]} {prom} \\n\") \r\n\r\narchivo.close\r\n\r\n" }, { "alpha_fraction": 0.4733158349990845, "alphanum_fraction": 0.5896762609481812, "avg_line_length": 19.203702926635742, "blob_id": "166cd814a3b919b7cb6c813f56c9230bbdba61d6", "content_id": "ac0a1dae3b2782c78acff757a1a197e6318cde91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 103, "num_lines": 54, "path": "/P0E4/codigo/grafico_comparacion_solve.py", "repo_name": "Cuchau/MCOC2021-P0", "src_encoding": "UTF-8", "text": "from time import sleep\r\nimport matplotlib.pyplot as plt\r\n\r\nNs_1 = []\r\nNs_2 = []\r\nNs_3 = []\r\nNs_4 = []\r\nNs_5 = []\r\nNs_6 = []\r\nNs_7 = []\r\ndts_1 = []\r\ndts_2 = []\r\ndts_3 = []\r\ndts_4 = []\r\ndts_5 = []\r\ndts_6 = []\r\ndts_7 = []\r\n\r\n#Para abrir cada archivo se cambia el nombre en open\r\narchivo1= open(\"sist_ec_caso_3_double.txt\", \"r\")\r\narchivo2= open(\"sist_ec_caso_3_single.txt\", \"r\")\r\n\r\n\r\n\r\nfor line in archivo1:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_1.append(N)\r\n dts_1.append(dt)\r\n\r\nfor line in archivo2:\r\n sep=line.split()\r\n N=int(sep[0])\r\n dt=float(sep[1])\r\n Ns_2.append(N)\r\n dts_2.append(dt)\r\n\r\narchivo1.close()\r\narchivo2.close()\r\n\r\n\r\n\r\nplt.plot(Ns_1,dts_1,label=\"caso 3-double\",marker=\"o\")\r\nplt.plot(Ns_1,dts_2,label=\"caso 3-single\",marker=\"o\")\r\n\r\nplt.loglog()\r\nplt.xticks([10,20,50,100,200,500,1000,2000,5000,6500],[10,20,50,100,200,500,1000,2000,5000,6500])\r\nplt.yticks([0.0001,0.001,0.01,0.1,1,10,60,600],[\"0.1ms\",\"1ms\",\"10ms\",\"0.1s\",\"1s\",\"10s\",\"1min\",\"10min\"])\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Tiempo[s]\")\r\nplt.legend()\r\nplt.title(\"Comparacion solve double vs single\")\r\nplt.show()" } ]
16
AuliaYF/XbitzPool
https://github.com/AuliaYF/XbitzPool
36dcd38024b4c4a42fc436298144b7ed840eab82
a828a2e99624457c32497115fceb43dc5192124e
56e34fc48b1487ca5f419c33aad331810d3f864f
refs/heads/master
2021-01-21T15:18:37.386114
2017-05-20T21:04:27
2017-05-20T21:04:27
91,838,170
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.571841835975647, "alphanum_fraction": 0.6171649098396301, "avg_line_length": 28.558822631835938, "blob_id": "4af734f2aa201fbf6b1f25caa9737377fd2b95a9", "content_id": "065c2a30b54a6415a410335861ee0222cc0e6e06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1037, "license_type": "permissive", "max_line_length": 130, "num_lines": 34, "path": "/pool/application/controllers/Test.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Test extends CI_Controller {\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t$resAccount = file_get_contents('https://raiblockscommunity.net/account/index.php?acc=xrb_3o7iocfcx1gcpa4q33ze56jmgicgct15kz4b4feu8mwxr43ju3t8cu668nei&json=1');\r\n\t\t$arrAccount = json_decode($resAccount, TRUE);\r\n\t\t$tArrTx = $arrAccount['history'];\r\n\t\t$arrTx = array();\r\n\t\tforeach($tArrTx as $obj){\r\n\t\t\tif($obj['type'] == \"receive\" && $obj['account'] == \"xrb_13ezf4od79h1tgj9aiu4djzcmmguendtjfuhwfukhuucboua8cpoihmh8byo\")\r\n\t\t\t\t$arrTx[] = $obj;\r\n\t\t}\r\n\t\t$lastIndex = $this->array_search2d_by_field(\"ACA94885D0800A78DAC4B0F919973C2D8E02C90804715D97B4A5947BE73B66AB\", $arrTx, \"hash\");\r\n\t\tfor ($i = ($lastIndex-1); $i >= 0; $i--) {\r\n\t\t\techo $arrTx[$i]['hash'] . \"<br>\";\t\t\t\r\n\t\t}\r\n\t}\r\n\r\n\tprivate function array_search2d_by_field($needle, $haystack, $field) {\r\n\t\tforeach ($haystack as $index => $innerArray) {\r\n\t\t\tif (isset($innerArray[$field]) && $innerArray[$field] === $needle) {\r\n\t\t\t\treturn $index;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Test.php */\r\n/* Location: ./application/controllers/Test.php */" }, { "alpha_fraction": 0.6963562965393066, "alphanum_fraction": 0.7071524858474731, "avg_line_length": 17.549999237060547, "blob_id": "fcd7694be0b36b2cbc912bf7ed3330f49abc1635", "content_id": "2d02d07fc82735f893a8fead38d5c6470e34f348", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 741, "license_type": "permissive", "max_line_length": 162, "num_lines": 40, "path": "/readme.md", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "# XbitzPool\nXbitzPool is one of RaiBlocks faucet pool based on mainly PHP CodeIgniter and Python. In this repository, there are pool, api, bot, and faucet validation sources.\n\n# Requirements\n - python-flask for API\n - mysql\n - Any webserver for pool\n - Python 3\n - RaiBlocks Node\n\n# Faucet Distribution\n```sh\n$ cd pool\n$ php index.php payout1432 cli\n```\n\n# Faucet Validation\n```sh\n$ python3 faucet.py\n```\n\n# Telegram Bot\n```sh\n$ cd XbitzPoolBot\n$ python3 bot.py\n```\n\n# API\n```sh\n$ cd api\n$ python3 api.py\n```\n# Final Goodbye\nThank you everyone for this amazing journey, i got to know a lot of stuffs from you guys. A big thanks to all of my pool's member.\nIf any of you want to contact me, send me an email to [email protected]\n\nLicense\n----\n\nMIT" }, { "alpha_fraction": 0.49017468094825745, "alphanum_fraction": 0.5082969665527344, "avg_line_length": 31.72142791748047, "blob_id": "34130c220f85f5d9ea96ec396730051b7da62f7d", "content_id": "78b6d63f5b346684cfdf50aed0a0ccc02bcc0000", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4580, "license_type": "permissive", "max_line_length": 179, "num_lines": 140, "path": "/pool/application/views/pages/paylist.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\n$paylist = json_decode(performGet('https://faucet.raiblockscommunity.net/paylist.php?acc=' . $this->config->item('xrb_address') . '&json=1'), TRUE);\n$dbDistribution = $this->db->get('distribution_history')->row();\n$threshold = (isset($paylist['threshold']) ? $paylist['threshold'] : 0);\n$poolClaim = (isset($paylist['pending'][0]['pending']) ? $paylist['pending'][0]['pending'] : 0);\n$poolMrai = (isset($paylist['pending'][0]['expected-pay']) ? $paylist['pending'][0]['expected-pay'] / 1000000 : 0);\n?>\n<div class=\"container-fluid\">\n\t<div class=\"col-md-12\">\n\t\t<div class=\"page-header\">\n\t\t\t<h1>NEXT DISTRIBUTION IN <?php echo floor($paylist['eta'] / 60) ?> MINUTES</h1>\n\t\t</div>\n\t\t<div class=\"alert alert-info\" role=\"alert\">\n\t\t\t<p><b>Please note</b> that RaiBlocks's paylist takes time to update.</p>\n\t\t\t<p>List updated every <b>5</b> minutes.</p>\n\t\t</div>\n\t</div>\n</div>\n<div class=\"container-fluid\">\n\t<div class=\"col-md-12\">\n\t\t<div class=\"row\">\n\t\t\t<div class=\"col-md-offset-3 col-md-6\">\n\t\t\t\t<table class=\"table\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th class=\"text-center\">Accounts</th>\n\t\t\t\t\t\t\t<th class=\"text-center\">Pool Claims</small></th>\n\t\t\t\t\t\t\t<th class=\"text-center\">Threshold </th>\n\t\t\t\t\t\t\t<th class=\"text-center\">Top 60</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody style=\"font-size: 18px;\">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class=\"text-center\">\n\t\t\t\t\t\t\t\t<?php echo $poolClaim > 0 ? count($this->model->countMember(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 3600), date(\"Y-m-d H:i:s\", time() + 3600))) : \"0\" ?>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td class=\"text-center\">\n\t\t\t\t\t\t\t\t<?php echo number_format($poolClaim, 0, '.', ',') ?>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td class=\"text-center\">\n\t\t\t\t\t\t\t\t<?php echo number_format($threshold, 0, '.', ',') ?>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td class=\"text-center\">\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\tif($poolClaim < $threshold)\n\t\t\t\t\t\t\t\t\techo '<span class=\"text-danger\">' . number_format(($threshold - $poolClaim), 0, '.', ',') . ' to Top 60</span>';\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\techo '<span class=\"text-success\">Yes <i class=\"fa fa-check\" aria-hidden=\"true\"></i></span>';\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</tbody>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t</div>\n\t\t\n\t\t<div class=\"panel panel-default\">\n\t\t\t<div class=\"panel-heading\">\n\t\t\t\t<div class=\"panel-title\">\n\t\t\t\t\tClaims\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"panel-body\">\n\n\t\t\t\t<table class=\"table\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"80\">#</th>\n\t\t\t\t\t\t\t<th class=\"text-left\">Account</th>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"200\">Claims</th>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tif($poolMrai > 0){\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t<th class=\"text-right\" width=\"200\">Mrai (XRB)</th>\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody style=\"font-size: 18px;\">\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\tif($poolClaim > 0){\n\t\t\t\t\t\t\t$arr = $this->model->populatePaylist(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 3600), date(\"Y-m-d H:i:s\", time() + 3600));\n\t\t\t\t\t\t\t$no = 0;\n\t\t\t\t\t\t\t$totalClaim = 0;\n\t\t\t\t\t\t\t$totalMrai = 0;\n\t\t\t\t\t\t\tforeach ($arr as $row) {\n\t\t\t\t\t\t\t\tif($row->totalClaim > 0){\n\t\t\t\t\t\t\t\t\t$no++;\n\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t<tr <?php echo \"\" /*$row->accountAddress == $this->session->userdata('xrb_address')['address'] ? \"style=\\\"background-color: #A5D6A7;\\\"\" : \"\"*/ ?>>\n\t\t\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\n\t\t\t\t\t\t\t\t\t\t<td><a href=\"https://raiblockscommunity.net/account/index.php?acc=<?php echo $row->accountAddress ?>\" target=\"_blank\"><?php echo $row->accountName ?></a></td>\n\t\t\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->totalClaim, 0, '.', ',') ?></td>\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\tif($poolMrai > 0){\n\t\t\t\t\t\t\t\t\t\t\t$mrai = ($row->totalClaim / $poolClaim * $poolMrai);\n\t\t\t\t\t\t\t\t\t\t\t$totalMrai += $mrai;\n\t\t\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($mrai, 6, '.', ',') ?></td>\n\t\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t$totalClaim += $row->totalClaim;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t</tbody>\n\t\t\t\t\t<tfoot style=\"font-size: 18px;\">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan=\"2\">&nbsp;</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tif($poolMrai > 0){\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class=\"info\">\n\t\t\t\t\t\t\t<td colspan=\"2\" class=\"text-right\">Total Claims</td>\n\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalClaim, 0, '.', ',') ?></td>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tif($poolMrai > 0){\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalMrai, 6, '.', ',') ?></td>\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</tfoot>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>" }, { "alpha_fraction": 0.5809524059295654, "alphanum_fraction": 0.5809524059295654, "avg_line_length": 20.210525512695312, "blob_id": "4bcf5faa2bb954f862935919d094c933988d20a0", "content_id": "7bc9907b4beba80fb1e4ee1daa7f141e00420aec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 420, "license_type": "permissive", "max_line_length": 75, "num_lines": 19, "path": "/pool/application/core/MY_Output.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); \r\n\r\nclass MY_Output extends CI_Output {\r\n\r\n\tfunction _display_cache(&$CFG, &$URI){\r\n\t\t\r\n\t\tif (in_array(@$_SESSION['xrb_address']['address'], array(\r\n\t\t\t'xrb_3o7iocfcx1gcpa4q33ze56jmgicgct15kz4b4feu8mwxr43ju3t8cu668nei',\r\n\t\t\t'xrb_1y8ib51kuzf61mak6ojex3oor7kgntcc57rdwmt517a7nmnxpgxaxy7pgd84'\r\n\t\t\t))){\r\n\t\t\treturn FALSE;\r\n\t\t}\r\n\t\t\r\n\t\treturn parent::_display_cache($CFG,$URI);\r\n\t}\r\n}\r\n\r\n/* End of file MY_Output.php */\r\n/* Location: ./application/core/MY_Output.php */" }, { "alpha_fraction": 0.7458333373069763, "alphanum_fraction": 0.7458333373069763, "avg_line_length": 33.28571319580078, "blob_id": "d08a4c9da12c6d528decd229994cd345d4fe4db1", "content_id": "f39a47f38db81b552a7de58d6d9291051eb66957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 240, "license_type": "permissive", "max_line_length": 162, "num_lines": 7, "path": "/XbitzPoolBot/readme.md", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "# XbitzPool - Telegram Bot\nXbitzPool is one of RaiBlocks faucet pool based on mainly PHP CodeIgniter and Python. In this repository, there are pool, api, bot, and faucet validation sources.\n\n# Configuration\n - bot.py\n - db.py\n - lang.py\n" }, { "alpha_fraction": 0.6177884340286255, "alphanum_fraction": 0.6177884340286255, "avg_line_length": 17.904762268066406, "blob_id": "a3b593c89453069bcf0a6e56a52c980acba7aa66", "content_id": "a6a216dcff81d4aeda2bfb2f35b83caae4a2d550", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 416, "license_type": "permissive", "max_line_length": 63, "num_lines": 21, "path": "/pool/application/controllers/Index.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Index extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t$data['active'] = 'home';\r\n\t\t$this->view('pages/home', $data);\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Index.php */\r\n/* Location: ./application/controllers/Index.php */" }, { "alpha_fraction": 0.6344647407531738, "alphanum_fraction": 0.6431679725646973, "avg_line_length": 37.31666564941406, "blob_id": "7f2a8fd48729a8072a262c555f39f99b4da6b938", "content_id": "6084eef6cd3a7e232fa239884b2179f653f1942a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2298, "license_type": "permissive", "max_line_length": 566, "num_lines": 60, "path": "/pool/application/controllers/Faucet.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\nclass Faucet extends MY_Controller {\n\n\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\t\t$this->load->model('accountmodel', 'model');\n\t}\n\n\tpublic function index()\n\t{\n\t\tif(NULL == $this->session->userdata('xrb_address'))\n\t\t\tredirect('login');\n\t\t$data['active'] = 'faucet';\n\t\t$this->view('pages/faucet', $data);\n\t}\n\n\tpublic function validate(){\n\t\tif(NULL == $this->session->userdata('xrb_address'))\n\t\t\tredirect('login');\n\t\t$distribution = $this->db->get('distribution_history')->row();\n\t\t$accountId = $this->model->isAccountExist($this->session->userdata('xrb_address')['address'])->accountId;\n\n\t\t$claimCaptchas = json_decode($this->input->post('captchas'), TRUE);\n\t\t$arrCaptcha = array();\n\t\tforeach($claimCaptchas as $claimCaptcha){\n\t\t\t$claimStatus = \"p\";\n\t\t\t$claimTime = date(\"Y-m-d H:i:s\", time() + 3600);\n\t\t\t\n\t\t\t$arrCaptcha[] = array(\n\t\t\t\t'accountId' => $accountId,\n\t\t\t\t'claimCaptcha' => $claimCaptcha,\n\t\t\t\t'claimStatus' => $claimStatus,\n\t\t\t\t'claimTime' => $claimTime\n\t\t\t);\n\t\t}\n\t\t$this->db->insert_batch('pending_claims', $arrCaptcha);\n\t\techo json_encode(array(\"error\" => \"no\"));\n\t}\n\n\tpublic function stat(){\n\t\tif(NULL == $this->session->userdata('xrb_address'))\n\t\t\tredirect('login');\n\t\t$this->db->cache_on();\n\t\t$distribution = $this->db->get('distribution_history')->row();\n\t\t$accountId = $this->model->isAccountExist($this->session->userdata('xrb_address')['address'])->accountId;\n\t\t\n\t\t$claimStat = $this->db->query(\"SELECT (SELECT COUNT(*) FROM pending_claims WHERE accountId = '\" . $accountId . \"' AND claimStatus = 'p' AND claimTime BETWEEN '\" . date(\"Y-m-d H:i:s\", $distribution->distributionCurrent + 3600) . \"' AND '\" . date(\"Y-m-d H:i:s\", time() + 3600) . \"') pendingClaims, (SELECT COUNT(*) FROM pending_claims WHERE accountId = '\" . $accountId . \"' AND claimStatus = 'd' AND claimTime BETWEEN '\" . date(\"Y-m-d H:i:s\", $distribution->distributionCurrent + 3600) . \"' AND '\" . date(\"Y-m-d H:i:s\", time() + 3600) . \"') validatedClaims\")->row();\n\t\techo json_encode(array(\n\t\t\t'pendingClaims' => intval($claimStat->pendingClaims),\n\t\t\t'validatedClaims' => intval($claimStat->validatedClaims)\n\t\t));\n\t\t$this->db->cache_off();\n\t}\n}\n\n/* End of file Faucet.php */\n/* Location: ./application/controllers/Faucet.php */" }, { "alpha_fraction": 0.5787278413772583, "alphanum_fraction": 0.5985401272773743, "avg_line_length": 22.64102554321289, "blob_id": "8e15cdba994a14c55098afb5627f8bebdf94d87f", "content_id": "2b5d27653fca283b2892f67aad1b11668ab3cf86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 959, "license_type": "permissive", "max_line_length": 102, "num_lines": 39, "path": "/pool/application/controllers/Pending1432.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Pending1432 extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t\tif(NULL === $this->session->userdata('xrb_address'))\r\n\t\t\tredirect('login');\r\n\t\telse{\r\n\t\t\tif(!isAdmin($this->session->userdata['xrb_address']['address']))\r\n\t\t\t\tredirect('login');\r\n\t\t}\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t$data['active'] = 'payout1432';\r\n\t\t$this->view('pages/pending', $data);\r\n\t}\r\n\r\n\tpublic function process(){\r\n\t\t$res = $this->db->where('payoutId', $this->input->post('payoutId'))->update('payout_history', array(\r\n\t\t\t'payoutHash' => $this->input->post('payoutHash'),\r\n\t\t\t'payoutStatus' => 'c'\r\n\t\t));\r\n\r\n\t\techo json_encode(\r\n\t\t\tarray(\r\n\t\t\t\t'status' => $this->db->affected_rows() > 0 ? '1' : '0'\r\n\t\t\t)\r\n\t\t);\r\n\t}\r\n}\r\n\r\n/* End of file Pending1432.php */\r\n/* Location: ./application/controllers/Pending1432.php */" }, { "alpha_fraction": 0.49370837211608887, "alphanum_fraction": 0.4964224100112915, "avg_line_length": 18.68877601623535, "blob_id": "cd74a348cc3bd0db96ba85806033479209f72f9d", "content_id": "280a2b26a23cbee24c6925341b5c3237d25c8d6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4053, "license_type": "permissive", "max_line_length": 155, "num_lines": 196, "path": "/pool/application/helpers/global_helper.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nif(!function_exists('isAdmin')){\r\n\tfunction isAdmin($address){\r\n\t\treturn in_array($address, array(\r\n\t\t\t'xrb_3o7iocfcx1gcpa4q33ze56jmgicgct15kz4b4feu8mwxr43ju3t8cu668nei',\r\n\t\t\t'xrb_1y8ib51kuzf61mak6ojex3oor7kgntcc57rdwmt517a7nmnxpgxaxy7pgd84'\r\n\t\t\t));\r\n\t}\r\n}\r\n\r\nif(!function_exists('isBTC')){\r\n\tfunction isBTC($address){\r\n\t\treturn in_array($address, array(\r\n\t\t\t'xrb_11h9r9dq8f1kffjp4ob89ewbofcqhun93hhjs48znfoktjrib63y5tus6fc7',\r\n\t\t\t'xrb_11z8a5gdrdtimo7fu31tyfgi5makxn1fyhbaejkpg4mjxsu76366ed6zqhn5',\r\n\t\t\t'xrb_14jyjetsh8p7jxx1of38ctsa779okt9d1pdnmtjpqiukuq8zugr3bxpxf1zu',\r\n\t\t\t'xrb_157i3hsque5btyhnkck147sto3htiq555i9kfrkah66i8uhrnhzifrps5cmm',\r\n\t\t\t'xrb_15csbzdxxpbw371yx7ygu63s79hke98tbyoyyz6peg9j9rayewofpzyw5qtf',\r\n\t\t\t'xrb_15zyhp773ai14ri9o9sywt65rfd336kzrihkr1hgychkh15hj9jros8ye19y',\r\n\t\t\t'xrb_1aridcdf53h73qp6n7urdqraaqszxcraysy6nqr19csenwffs4najhaysoz8',\r\n\t\t\t'xrb_1beyc4xfzga8bjqs9mwo6f11asockypdu7868rzx147au7n5pmahnj3c7zrc',\r\n\t\t\t'xrb_1ca68e7pgr6934g74j6anhba5hdgbeawcrbh9mi7d9ehd9gf58dow57bufh7',\r\n\t\t\t'xrb_1dns5txokxu4hdj3jnydu6bxnerd3ijzy9y6ixqmkoxtnpwuw8igodzf8os7',\r\n\t\t\t'xrb_1ej6ys9sbqzppq49geikx99gjfr5bjmuf5kfieuy1aas1c9hxcgdn5rfifyq',\r\n\t\t\t'xrb_1fexq3m3ej7tekonpm956qkohb8csgakpya1t9h6inf5hxywk87cacmp4ken',\r\n\t\t\t'xrb_1gfts18bc65ogkd95ydjd5i775zoabh81cu3451bihsrnaxps7fp3zwhkg1u',\r\n\t\t\t'xrb_1gru6tw6ab7ndqcq31ebs57w5p39e7azs17z5z9ac4w6hzi4e69wdmuqpkhd',\r\n\t\t\t'xrb_1kkh3rz38kyeodj1ezzhph3cd6abe9ct9f9h5f6tp5zfzta4sze6qgtg3oo9',\r\n\t\t\t'xrb_1mx8m6qai6kwftw1w4s44j4jcx195xcqngi7fia7rejzbhuudroxet5at1bw',\r\n\t\t\t'xrb_1mzsi9yf79yroof96uyo9f111igas1d64k5t4qehqqtme5okpjiapbe8ri6h',\r\n\t\t\t'xrb_1nz8gu5rrbe1yw4jydj9gaaeu396uz5w4gay99d77j1ajp5jgw7wdu5t1qyc',\r\n\t\t\t'xrb_1p93ni1aub9uzpnkhw9grpbxu5qoiu1imdzraq5b8ewc1zkx5wk7mox9k8qt',\r\n\t\t\t'xrb_1pgyh8exgrjxoigdjqk64ysi3a3ggnczud1kedfpm5qhu6befcjq7hmbrqtm',\r\n\t\t\t'xrb_1pj9b6a9mfzkip45qhxtrdjetgjqigeszifgm3xe6xbfb3dnwpt5j43o8sp6',\r\n\t\t\t'xrb_1pkneux7anrfpiari9d3cf8i57dsjx38gm4qxapd1dm9paxc3dkiaxfkkqf1',\r\n\t\t\t'xrb_1qspmpgbsk5jhbmqehittkz43zruqgu9cshecdsrqb6yphn15ai56oxtgh5f',\r\n\t\t\t'xrb_1rck5o87m3uowpb5pimmdeuej1hgitee3n5ux6zpda5ehtig4mooci4uemzt',\r\n\t\t\t'xrb_1rgffjigjti5jqneomfiowns7zotrncacj7epgfnyrgoygkehr5ndxj3ywzc',\r\n\t\t\t'xrb_1s484k471eq8e68nmrzdiwybsct8h4uxgrjrdgmb1jwmkafpzf7hei91qouc',\r\n\t\t\t'xrb_1sd4ipowittg517fb5yuye4mr9ucwmn9tf44x45mfprapn5t4853iuyffrct',\r\n\t\t\t'xrb_1se8hs97ou4pojn15edawgw4qhyq3jop9ogg4jk94qe5q4ahept4xdittfz3',\r\n\t\t\t'xrb_1spe8c9hqdtawprn5pozuppwuofg58xn5jtwyp9181hxfp4tjtebbdbygbqc',\r\n\t\t\t'xrb_1su4e3a6yktwh3gxu8wkemersm8ne3a6775oam9jnjk3i93t63sxj9c6dgg9',\r\n\t\t\t'xrb_1tjunup3cd7nwury63gqxemzhuitk4p77fuqnaz5okigkum1sfpspu9319bp',\r\n\t\t\t'xrb_1tjwpj3ez6go8qrdypfcq8ctecfk8nfqnzhegr5f9njnpzrt6111zmuk16qg',\r\n\t\t\t'xrb_1twm9thaxpfez54aty5c68k7z338jmxjuemaqnm9e8z3amh4an4jkrmwoyds',\r\n\t\t\t'xrb_1whuie3u3ij5k5ji6n98m9jexyykuz6c5egj65aieeahmdd8xw8gb3our963',\r\n\t\t\t'xrb_1wiwpdxxgzzsun6btjtiom7eigczeht7xpg4h7bcpkscftq7wws7gjzpsfdo',\r\n\t\t\t'xrb_1xbohr8s47et4asq9rxbsnzr5zqnwno8g94bfxmrbo3wr9aphf7qusegty1f',\r\n\t\t\t'xrb_1ygi86qugoxnrnu5xjhcbr6mqkpy55djn4izrih6j4z3dmwuinsijb6nhzi7',\r\n\t\t\t'xrb_1zefntwhskgo6qg45betms1g99c5pu3n9p6r366trxbthpoworh8q9zak3d4',\r\n\t\t\t'xrb_1zbupekjsqtbd5cs4xsu4dp8rt14kcfkmm8jxm53pr969a3ksm3p9w9ficdj',\r\n\t\t\t'xrb_344gsm4rbqsq473ah86bskx1gk6x5tf76qrwn4x8u7bz355qhq66951z4z7a',\r\n\t\t\t'xrb_356f1ugy616qwcao7thu8awzrktn5g1b4dgz5hdbxsey8twh7559tzpz5jrf',\r\n\t\t\t'xrb_35ak7ri9rbsf7gcccj8r5pgnwtjhz65i9g4esf9i3iop1gj877pnnnjyhenr',\r\n\t\t\t'xrb_35ax3k8qx633o5nz87peq8tjkd57yu3bapbqmxjxjky1hzfapskzdhp1dk8f',\r\n\t\t\t'xrb_36w9gtkpkd4cgmhkoc4thqq91cbuf61nafr4qzeojxh4bz5wkeecawegfhbc',\r\n\t\t\t'xrb_386h4zr9nkfcxahmo1djecqc53f6j391zdkfcdtrc4dme4hw91z8iqqosh13',\r\n\t\t\t'xrb_3aah5egag135csxq3r3c7anhzkjwx6az1tt4e8enwc3b1n4gjupt5murmzbg',\r\n\t\t\t'xrb_3ajmmwm7ymroa3ahn8x9xhqx5xkcpojxgemmfcaanau5xyeg9ipe643c316u',\r\n\t\t\t'xrb_3auqjtdad61fe8unei4uxnaogr5frtje5ijgdpcqqfri3ujurzpxuzhr69zp',\r\n\t\t\t'xrb_3axpdk46x8khyqcdth8brnunoq7k9agwnrchxir1om6w9qxyjucnkrsasuq6',\r\n\t\t\t'xrb_3b87j47ck1uge8em6yz38zdw3ctp7jzuj6bf5zar5fehzi971zf87u9nmxin',\r\n\t\t\t'xrb_3b9wnq35gwwdsywz7g6tsj9f46anxw19nk4rrq91nyuu4j7qkg4gzrah7oqe',\r\n\t\t\t'xrb_3bgjaa9y8xekaxzfx9jyrurst9zhmx96zpmddrrp4qazr386pdsma9qffg77',\r\n\t\t\t'xrb_3bwfgutwjs4w4c3rr3cb9pjfkj13u5gb77dgtpcwzamncyym7thhbwntk7m4',\r\n\t\t\t'xrb_3d3cq7fy7pdmk4rsuuy5pn9uk9d6kzrmn5gcwg791zy1f4uoarfssmedefix',\r\n\t\t\t'xrb_3d53rmhpymdwy6zbkuswxep5wpzatz4x9ezqpop49h89kdrp6d5ebow9zdu1',\r\n\t\t\t'xrb_3dn9ti4hxkdm7ac447ez3ir3dsci51wxwm7nqayymzbqo6eo1936m7yjkqwk',\r\n\t\t\t'xrb_3dsfiynajhtxe67psmc77wu56xymdt7thunxtkbm3q4rngfcpjizuduxrhra',\r\n\t\t\t'xrb_3dx3dzru1yh97xr7pqyrxjmt4xxu4shj53drps5btourbyr3jghsdt1ptye1',\r\n\t\t\t'xrb_3dz3qs6kn8x4mewco9jbpp4b6hn3h3y8fxu8cgspys9hc5ob35b1m3uwcxf6',\r\n\t\t\t'xrb_3faz5mj64ybq6osfkqjuujm1dyxbabrpem3peu3qk7ksr4bim5fmy7tgkegb',\r\n\t\t\t'xrb_3g78xuat3x81jsq7jtrxkkuhj5ajsafp7jyce1gqw78tu3966xckm3obphe9',\r\n\t\t\t'xrb_3g83pzpcgngowqkjrrfcibrpatr7ufkg56tpphiii5tgh5p986hr7hxhg19q',\r\n\t\t\t'xrb_3gx3gqi4i1i8drc8jwhnpkcguucoohds3yr6hrwt63dz5hzna43w1wpswh6s',\r\n\t\t\t'xrb_3hhnee4p47u1h1pi39hquc6war8r56ubuic6b9sikt1e5es97wco4tydjrs7',\r\n\t\t\t'xrb_3jp5b5p3q3m41auaroa958nxki9jej9ppmc6on3ffagxgchaxhtsc34zqfmp',\r\n\t\t\t'xrb_3kfu3dnxog9aahdwa9934kxnatcy71e3tg6u4nipt9m7dycgqxskb1hrbqxb',\r\n\t\t\t'xrb_3m84nz3wsgnjhhz77gtccg9eeb8syrkjkzjck67wt54fu9h39qebg3g4kuak',\r\n\t\t\t'xrb_3n5i5w6yf4rsn6339tbn83epgpe5ten8c4fmg9qwrwqxcmn47m81tk36do7i',\r\n\t\t\t'xrb_3n86gj3t5ypc6dsq85af1ntqjywyyg1b1k15g1wu7cthusoat3dkowr7tkeo',\r\n\t\t\t'xrb_3rmjeycx5oz1zqpirbkm3hehhxgo5m8cwa1rswmtqbzkm3tcdm9poc8xd176',\r\n\t\t\t'xrb_3secrazinfbaqkb19fw5patzg9ehnj8nh6u8hxk81hj8efzamdnw73hcnumg',\r\n\t\t\t'xrb_3ut9oks5ugjg4kkjft4d33q1kg58wd9whkwjnpizr7kpokjzjs9hafztz1bj',\r\n\t\t\t'xrb_3wa7gcxz4we8e6z8iwatsoix7rrtjzyoafn8hk76kjf9tsxpcpwbi5femb9d',\r\n\t\t\t'xrb_3x95rgks3t5shqf649xnbawagzckyg9pksr46etxdq1jxy7d8qpjzmj34g6a',\r\n\t\t\t'xrb_3zekt4tpcjyx57hhqxfe69hcz9o9acyny9enm6ku8iwbgc811mugzttdu4jt',\r\n\t\t\t'xrb_3zg7unmxg6ha67u1hma4w9n1ss7r5fin3jwwu5ywr1xjo7eh6ymo73ksmquz',\r\n\t\t\t'xrb_3znijk4g4cbb4m6qwqamcbwuqmcc5exyqyuaofoh13tecpmr3r85qbns5uk9'\r\n\t\t\t));\r\n}\r\n}\r\n\r\nif(!function_exists('postCURL')){\r\n\tfunction postCURL($_url, $_param){\r\n\r\n\t\t$postData = '';\r\n //create name value pairs seperated by &\r\n\t\tforeach($_param as $k => $v) \r\n\t\t{ \r\n\t\t\t$postData .= $k . '='.$v.'&'; \r\n\t\t}\r\n\t\trtrim($postData, '&');\r\n\r\n\t\ttry {\r\n\t\t\t$ch = curl_init();\r\n\t\t\tcurl_setopt($ch, CURLOPT_ENCODING, '');\r\n\t\t\tcurl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\r\n\t\t\tcurl_setopt($ch, CURLOPT_URL,$_url);\r\n\t\t\tcurl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\r\n\t\t\tcurl_setopt($ch, CURLOPT_HEADER, false); \r\n\t\t\tcurl_setopt($ch, CURLOPT_POST, count($_param));\r\n\t\t\tcurl_setopt($ch, CURLOPT_POSTFIELDS, $postData); \r\n\r\n\t\t\t$output=curl_exec($ch);\r\n\t\t\tif (FALSE === $output)\r\n\t\t\t\tthrow new Exception(curl_error($ch), curl_errno($ch));\r\n\r\n\t\t\tcurl_close($ch);\r\n\r\n\t\t\treturn $output;\r\n\t\t} catch(Exception $e) {\r\n\t\t\ttrigger_error(sprintf(\r\n\t\t\t\t'Curl failed with error #%d: %s',\r\n\t\t\t\t$e->getCode(), $e->getMessage()),\r\n\t\t\tE_USER_ERROR);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nif(!function_exists('truncate')){\r\n\tfunction truncate($in, $len = 50){\r\n\t\treturn strlen($in) > $len ? substr($in, 0, $len) . \"...\" : $in;\r\n\t}\r\n}\r\n\r\nif(!function_exists('getIndexByValue')){\r\n\tfunction getIndexByValue($array, $field, $content){\r\n\t\tforeach($array as $key => $obj){\r\n\t\t\tif($obj[$field] == $content)\r\n\t\t\t\treturn $key;\r\n\t\t}\r\n\r\n\t\treturn NULL;\r\n\t}\r\n}\r\n\r\nif(!function_exists('performGet')){\r\n\tfunction performGet($url){\r\n\t\trequire_once APPPATH.'third_party/Guzzle/autoloader.php';\r\n\t\ttry {\r\n\t\t\t$client = new \\GuzzleHttp\\Client(\r\n\t\t\t\tarray(\r\n\t\t\t\t\t'base_uri' => 'https://faucet.raiblockscommunity.net/',\r\n\t\t\t\t\t'timeout' => 60.0,\r\n\t\t\t\t\t'verify' => FALSE\r\n\t\t\t\t\t));\r\n\t\t\t$response = $client->request('GET', $url);\r\n\t\t\treturn $response->getBody();\r\n\t\t} catch (\\GuzzleHttp\\Exception\\BadResponseException $e) {\r\n\t\t\treturn performGet($url);\r\n\t\t}\r\n\t}\r\n}\r\nif(!function_exists('performPost')){\r\n\tfunction performPost($url, $param = array(), $uri = \"https://faucet.raiblockscommunity.net/\", $timeout=60.0, $retry = TRUE, $auth = FALSE, $maxRetry = 3){\r\n\t\trequire_once APPPATH.'third_party/Guzzle/autoloader.php';\r\n\t\t$attempt = 0;\r\n\t\ttry {\r\n\t\t\t$attempt++;\r\n\t\t\t$client = new \\GuzzleHttp\\Client(\r\n\t\t\t\tarray(\r\n\t\t\t\t\t'base_uri' => $uri,\r\n\t\t\t\t\t'timeout' => $timeout,\r\n\t\t\t\t\t'verify' => FALSE\r\n\t\t\t\t\t));\r\n\t\t\t$options = array();\r\n\t\t\t$options['multipart'] = $param;\r\n\t\t\tif($auth)\r\n\t\t\t\t$options['auth'] = ['pool', 'p0ol4dmin'];\r\n\t\t\t$response = $client->request('POST', $url, $options);\r\n\t\t\treturn $response->getBody();\r\n\t\t} catch (\\GuzzleHttp\\Exception\\BadResponseException $e) {\r\n\t\t\tif($retry && $attempt <= $maxRetry)\r\n\t\t\t\treturn performPost($url, $param);\r\n\t\t\telse\r\n\t\t\t\tdie($e);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/* End of file global_helper.php */\r\n/* Location: ./application/helpers/global_helper.php */" }, { "alpha_fraction": 0.5162144303321838, "alphanum_fraction": 0.5226119756698608, "avg_line_length": 45.26530456542969, "blob_id": "333bbbd81d825004e12dcef3318afc7d30f37f2c", "content_id": "5ca6f35778672cd88404512944a336105118f09b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4533, "license_type": "permissive", "max_line_length": 187, "num_lines": 98, "path": "/pool/application/views/base.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\n$sess = $this->session->userdata('xrb_address');\n$account = NULL;\nif(NULL != $sess)\n $account = $this->model->isAccountExist($sess['address']);\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"shortcut icon\" href=\"<?php echo base_url('favicon.ico') ?>\" />\n <title>XRB Pool</title>\n\n <link href=\"<?php echo base_url('assets/css/bootstrap.min.css') ?>\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"<?php echo base_url('assets/css/font-awesome.min.css') ?>\">\n\n <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->\n <script src=\"<?php echo base_url('assets/js/jquery.min.js') ?>\"></script>\n <!-- Include all compiled plugins (below), or include individual files as needed -->\n <script src=\"<?php echo base_url('assets/js/bootstrap.min.js') ?>\"></script>\n\n <script type=\"text/javascript\">\n var base_url = '<?php echo base_url() ?>';\n var xrb_address = '<?php echo $this->config->item('xrb_address') ?>';\n </script>\n</head>\n<body>\n <nav class=\"navbar navbar-default\">\n <div class=\"container-fluid\">\n <div class=\"col-md-12\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"<?php echo base_url() ?>\">\n <span><img alt=\"XRB Pool\" src=\"<?php echo base_url('assets/img/logo.png') ?>\" width=\"20\" height=\"20\" style=\"display: inline-block; margin-top: -5px; margin-right: 5px\"></span>\n XRB Pool\n </a>\n </div>\n\n <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\n <ul class=\"nav navbar-nav navbar-right\">\n <li <?php echo $active == \"home\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url() ?>\">Home</a></li>\n <li <?php echo $active == \"payouts\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url('payouts') ?>\">Payouts</a></li>\n <?php\n if($this->uri->segment(1) != 'paylist'){\n if(isAdmin(@$account->accountAddress)){\n ?>\n <li class=\"dropdown <?php echo $active == \"payout1432\" || $active == \"pending1432\" ? \"active\" : '' ?>\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">Payout <span class=\"caret\"></span></a>\n <ul class=\"dropdown-menu\">\n <li><a href=\"<?php echo base_url('payout1432/cli') ?>\">Override Distribution</a></li>\n <li><a href=\"<?php echo base_url('pending1432') ?>\">Pending</a></li>\n </ul>\n </li>\n <?php\n }\n }\n ?>\n \t<li <?php echo $active == \"logs\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url('logs') ?>\">Logs</a></li>\n <?php\n if(NULL != $account){\n ?>\n <li <?php echo $active == \"paylist\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url('paylist') ?>\">Paylist</a></li>\n <li <?php echo $active == \"faucet\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url('faucet') ?>\">Faucet</a></li>\n <li class=\"dropdown <?php echo $active == \"account\" ? \"active\" : '' ?>\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">Account <span class=\"caret\"></span></a>\n <ul class=\"dropdown-menu\">\n <li><a href=\"<?php echo base_url('profile') ?>\">Profile</a></li>\n <li role=\"separator\" class=\"divider\"></li>\n <li><a href=\"<?php echo base_url('logout') ?>\">Logout</a></li>\n </ul>\n </li>\n <?php\n }else{\n ?>\n <li <?php echo $active == \"login\" ? \"class='active'\" : '' ?>><a href=\"<?php echo base_url('login') ?>\">Login</a></li>\n <?php\n }\n ?>\n </ul>\n </div>\n </div>\n </div>\n </nav>\n\n <?php\n if(!empty($content)){\n $this->load->view($content);\n }\n ?>\n</body>\n</html>" }, { "alpha_fraction": 0.6033386588096619, "alphanum_fraction": 0.6438791751861572, "avg_line_length": 21.070175170898438, "blob_id": "2740e69a50c41d8b11dfa48970fd0534e18e1ca7", "content_id": "8f7cee00b211c7e1d6d160c69dc692485641836d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2516, "license_type": "permissive", "max_line_length": 97, "num_lines": 114, "path": "/api/api.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import math\nimport json\nfrom easyraikit import *\nfrom flask import Flask, Response, request, jsonify\n\napp = Flask(__name__)\nrai = Rai()\nunlocked = rai.password_enter({'wallet': wallet, 'password': wallet_password})['valid']\n\nHOST_ORIGIN = 'http://xbitzpool.com'\n\nlastPayoutId = \"0\";\n\[email protected](\"/\")\ndef block_count():\n\tblock_count = rai.block_count()\n\tmessage = {\n\t\t'status': 200,\n\t\t'message': {\n\t\t\t'block': {\n\t\t\t\t'count': block_count['count'],\n\t\t\t\t'unchecked': block_count['unchecked'],\n\t\t\t},\n\t\t\t'unlocked': unlocked,\n\t\t\t'version': rai.version()['node_vendor']\n\t\t},\n\t}\n\tresp = jsonify(message)\n\tresp.status_code = 200\n\n\treturn resp\n\[email protected](\"/accounts\", methods=['GET'])\ndef account_list():\n\tglobal wallet\n\taccount_list = rai.account_list({'wallet': wallet})\n\tmessage = {\n\t\t'status': 200,\n\t\t'message': {\n\t\t\t'accounts': account_list['accounts']\n\t\t},\n\t}\n\tresp = jsonify(message)\n\tresp.status_code = 200\n\n\treturn resp\n\[email protected](\"/accounts/<account>\", methods=['GET'])\ndef account_detail(account):\n\taccount_balance = rai.account_balance({'account': account})\n\tmessage = {\n\t\t'status': 200,\n\t\t'message': {\n\t\t\t'balance': {\n\t\t\t\t'balance': raiblocks_mrai_from_raw(int(account_balance['balance'])),\n\t\t\t\t'pending': raiblocks_mrai_from_raw(int(account_balance['pending']))\n\t\t\t}\n\t\t},\n\t}\n\tresp = jsonify(message)\n\tresp.status_code = 200\n\n\treturn resp\n\[email protected](\"/send\", methods=['POST'])\ndef send():\n\tglobal wallet\n\tglobal lastPayoutId\n\tif lastPayoutId == request.form['payoutId']:\n\t\tmessage = {\n\t\t\t'status': 200,\n\t\t\t'message': 'double'\n\t\t}\n\t\tresp = jsonify(message)\n\t\tresp.status_code = 200\n\t\tresp.headers.add('Access-Control-Allow-Origin', HOST_ORIGIN)\n\n\t\treturn resp\n\n\taccount_list = rai.account_list({'wallet': wallet})\n\tsender = account_list['accounts'][0]\n\taccount = request.form['account']\n\tamount = raiblocks_mrai_to_raw(float(request.form['amount']))\n\n\tblock = rai.send({'wallet': wallet, 'source': sender, 'destination': account, 'amount': amount})\n\tif block is not None:\n\t\tif block['block'] != \"0000000000000000000000000000000000000000000000000000000000000000\":\n\t\t\tmessage = {\n\t\t\t\t'status': 200,\n\t\t\t\t'message': {\n\t\t\t\t\t'block': block['block']\n\t\t\t\t}\n\t\t\t}\n\t\telse:\n\t\t\tmessage = {\n\t\t\t\t'status': 200,\n\t\t\t\t'message': 'error',\n\t\t\t\t'error': block['error']\n\t\t\t}\n\telse:\n\t\tmessage = {\n\t\t\t'status': 200,\n\t\t\t'message': 'error',\n\t\t\t'error': block['error']\n\t\t}\n\n\tresp = jsonify(message)\n\tresp.status_code = 200\n\tresp.headers.add('Access-Control-Allow-Origin', HOST_ORIGIN)\n\n\treturn resp\n\nif __name__ == \"__main__\":\n\tapp.run()\n" }, { "alpha_fraction": 0.6002284288406372, "alphanum_fraction": 0.6230725049972534, "avg_line_length": 22.31944465637207, "blob_id": "3c92cb21fb180055166cf5248e5f87d4bc48866b", "content_id": "d0553dd9f005b00618378f8d17b65b1b7fd1c5f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1751, "license_type": "permissive", "max_line_length": 80, "num_lines": 72, "path": "/api/easyraikit.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import re\r\nimport math\r\nimport json\r\nimport requests\r\nimport configparser\r\nfrom time import sleep\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('config.cfg')\r\nserver = config.get('main', 'server')\r\nwallet = config.get('main', 'wallet')\r\nwallet_password = config.get('main', 'wallet_password')\r\n\r\ndef raiblocks_account_validate(account):\r\n\tif isinstance(account, str):\r\n\t\tif ('xrb_1' in account) or ('xrb_3' in account) and (len(account) == 64):\r\n\t\t\taccount = account[4:]\r\n\t\t\tchar_validation = re.search('^[13456789abcdefghijkmnopqrstuwxyz]+$', account)\r\n\t\t\tif char_validation is not None:\r\n\t\t\t\treturn True\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\telse:\r\n\t\t\treturn False\r\n\telse:\r\n\t\treturn False\r\n\r\ndef raiblocks_mrai_from_raw(raw):\r\n\treturn int(math.floor(raw / (10 ** 30)))\r\n\r\ndef raiblocks_mrai_to_raw(mrai):\r\n\treturn int(math.floor(mrai * (10 ** 30)))\r\n\r\ndef raiblocks_rai_from_raw(raw):\r\n\treturn int(math.floor(raw / (10 ** 24)))\r\n\r\ndef raiblocks_rai_to_raw(rai):\r\n\treturn int(math.floor(rai * (10 ** 24)))\r\n\r\ndef raiblocks_krai_from_raw(raw):\r\n\treturn int(math.floor(raw / (10 ** 27)))\r\n\r\ndef raiblocks_krai_to_raw(krai):\r\n\treturn int(math.floor(krai * (10 ** 27)))\r\n\r\nclass Rai:\r\n\tdef __getattr__(self, name, *args):\r\n\t\tdef function (*args):\r\n\t\t\trequest = {}\r\n\t\t\trequest['action'] = name\r\n\t\t\tif args:\r\n\t\t\t\tfor key, value in args[0].items():\r\n\t\t\t\t\trequest[key] = value\r\n\t\t\ttry:\r\n\t\t\t\tr = requests.post(server, data = json.dumps(request)).json()\r\n\r\n\t\t\t\tif 'error' not in r:\r\n\t\t\t\t\treturn(r)\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(r['error'])\r\n\t\t\t\t\treturn None\r\n\t\t\texcept:\r\n\t\t\t\tsleep(0.5)\r\n\t\t\t\tr = requests.post('', data = json.dumps(request)).json()\r\n\r\n\t\t\t\tif 'error' not in r:\r\n\t\t\t\t\treturn(r)\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(r['error'])\r\n\t\t\t\t\treturn None\r\n\r\n\t\treturn function\r\n" }, { "alpha_fraction": 0.5304149389266968, "alphanum_fraction": 0.5395461320877075, "avg_line_length": 34.336585998535156, "blob_id": "fce3c6fbd5496252221cd88619d1a23673ac1680", "content_id": "aaad144b48b55e5fc0e811c634ac23953a661bcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7447, "license_type": "permissive", "max_line_length": 256, "num_lines": 205, "path": "/pool/application/views/pages/pending.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<div class=\"container-fluid\">\r\n\t<div class=\"col-md-12\">\r\n\t\t<?php\r\n\t\t$pendings = $this->db->select('t2.accountName, t2.accountAddress, t2.accountThreshold, t1.payoutId, t1.payoutQty, t1.payoutProfit')->join('app_account t2', 't2.accountId = t1.accountId')->where('t1.payoutStatus', 'p')->get('payout_history t1')->result();\r\n\t\t$cmd = 0;\r\n\t\t$fee = 0;\r\n\t\tforeach ($pendings as $row) {\r\n\t\t\t$cmd++;\r\n\t\t\t$fee += $row->payoutProfit;\r\n\t\t\t?>\r\n\t\t\t<div class=\"panel panel-default\">\r\n\t\t\t\t<div class=\"panel-body\">\r\n\t\t\t\t\t<div class=\"form-horizontal\">\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Fullname</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo $row->accountName ?></p>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">XRB Address</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo $row->accountAddress ?></p>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Amount</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo number_format($row->payoutQty, 6, '.', ',') ?> Mrai</p>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Block</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<input type=\"hidden\" id=\"inputAccount[<?php echo $row->payoutId ?>]\" value=\"<?php echo $row->accountAddress ?>\">\r\n\t\t\t\t\t\t\t\t<input type=\"hidden\" id=\"inputAmount[<?php echo $row->payoutId ?>]\" value=\"<?php echo number_format($row->payoutQty, 6, '.', '') ?>\">\r\n\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form-control hash-field\" id=\"inputBlock[<?php echo $row->payoutId ?>]\" placeholder=\"Transaction hash\">\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t\t<div class=\"col-sm-offset-3 col-sm-9\">\r\n\t\t\t\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t\t\t\t<div class=\"col-xs-6\">\r\n\t\t\t\t\t\t\t\t\t\t<button id=\"send[<?php echo $row->payoutId ?>]\" class=\"btn btn-warning col-xs-12 send-btn\"><i class=\"fa fa-refresh fa-spin\" style=\"display: none; margin-right: 5px;\"></i>Send</button>\r\n\t\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t\t\t<div class=\"col-xs-6\">\r\n\t\t\t\t\t\t\t\t\t\t<button id=\"submit[<?php echo $row->payoutId ?>]\" class=\"btn btn-primary col-xs-12 process-btn\"><i class=\"fa fa-refresh fa-spin\" style=\"display: none; margin-right: 5px;\"></i>Process</button>\r\n\t\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<?php\r\n\t\t}\r\n\r\n\t\tif($cmd == 0){\r\n\t\t\t?>\r\n\t\t\t<div class=\"page-header\">\r\n\t\t\t\t<h1>No Pending Payouts</h1>\r\n\t\t\t</div>\r\n\t\t\t<?php\r\n\t\t}else{\r\n\t\t\t?>\r\n\t\t\t<div class=\"page-header\">\r\n\t\t\t\t<h1>Take Fee</h1>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"panel panel-default\">\r\n\t\t\t\t<div class=\"panel-body\">\r\n\t\t\t\t\t<div class=\"form-horizontal\">\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Amount</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo number_format($fee, 6, '.', ',') ?> Mrai</p>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Account</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" id=\"inputAccount[fee]\" value=\"<?php echo $this->session->userdata('xrb_address')['address']; ?>\">\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"form-group\">\r\n\t\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Block</label>\r\n\t\t\t\t\t\t\t<div class=\"col-sm-9\">\r\n\t\t\t\t\t\t\t\t<input type=\"hidden\" id=\"inputAmount[fee]\" value=\"<?php echo number_format($fee, 6, '.', '') ?>\">\r\n\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form-control hash-field\" id=\"inputBlock[fee]\" placeholder=\"Transaction hash\" readonly=\"readonly\">\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t\t<div class=\"col-sm-offset-3 col-sm-9\">\r\n\t\t\t\t\t\t\t\t<div class=\"row\">\r\n\t\t\t\t\t\t\t\t\t<div class=\"col-xs-12\">\r\n\t\t\t\t\t\t\t\t\t\t<button id=\"send[fee]\" class=\"btn btn-warning col-xs-12 send-btn\"><i class=\"fa fa-refresh fa-spin\" style=\"display: none; margin-right: 5px;\"></i>Send</button>\r\n\t\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<?php\r\n\t\t}\r\n\t\t?>\r\n\t</div>\r\n</div>\r\n<script type=\"text/javascript\">\r\n\tvar lastSend = new Date().getTime();\r\n\tfunction makeBaseAuth(user, pswd){ \r\n\t\tvar token = user + ':' + pswd;\r\n\t\tvar hash = \"\";\r\n\t\tif (btoa) {\r\n\t\t\thash = btoa(token);\r\n\t\t}\r\n\t\treturn \"Basic \" + hash;\r\n\t}\r\n\t$(document).ready(function(){\r\n\t\t$('.send-btn').on('click', function(){\r\n\t\t\tif(lastSend != ''){\r\n\t\t\t\tvar execTime = new Date().getTime();\r\n\t\t\t\tvar seconds = (execTime - lastSend) / 1000;\r\n\t\t\t\tif(seconds >= 10){\r\n\r\n\t\t\t\t\tvar $this = $(this);\r\n\t\t\t\t\tvar payoutId = $(this).attr('id').replace('send[', '').replace(']', '');\r\n\t\t\t\t\tvar $hashField = $(\".hash-field#inputBlock\\\\[\" + payoutId + \"\\\\]\");\r\n\t\t\t\t\tvar $accountField = $(\"#inputAccount\\\\[\" + payoutId + \"\\\\]\");\r\n\t\t\t\t\tvar $amountField = $(\"#inputAmount\\\\[\" + payoutId + \"\\\\]\");\r\n\r\n\t\t\t\t\t$this.prop('disabled', 'disabled');\r\n\t\t\t\t\t$(\"i\", $this).css('display', 'inline-block');\r\n\r\n\t\t\t\t\t$.ajax({\r\n\t\t\t\t\t\ttype: \"POST\",\r\n\t\t\t\t\t\turl: \"<?php echo $this->config->item('api_url') ?>\",\r\n\t\t\t\t\t\tdataType : \"JSON\",\r\n\t\t\t\t\t\tdata: \"payoutId=\" + payoutId + \"&account=\" + $accountField.val() + \"&amount=\" + $amountField.val(),\r\n\t\t\t\t\t\tcrossDomain: true,\r\n\t\t\t\t\t\tsuccess: function(data){\r\n\t\t\t\t\t\t\tif(data.message != \"error\"){\r\n\t\t\t\t\t\t\t\t$hashField.val(data.message.block)\r\n\t\t\t\t\t\t\t\t$hashField.prop('disabled', 'disabled');\r\n\t\t\t\t\t\t\t\t$hashField.parent().parent().addClass('has-success');\r\n\t\t\t\t\t\t\t\t$this.remove();\r\n\t\t\t\t\t\t\t}else if(data.message == \"double\"){\r\n\t\t\t\t\t\t\t\talert('WARNING!!!\\nAlready spent. Copy block from raiblock.');\r\n\t\t\t\t\t\t\t\t$this.remove();\r\n\t\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t\t$hashField.parent().parent().addClass('has-error');\r\n\t\t\t\t\t\t\t\t$(\"i\", $this).css('display', 'none');\r\n\t\t\t\t\t\t\t\t$this.removeAttr('disabled');\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tlastSend = new Date().getTime();\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\terror: function(data){\r\n\t\t\t\t\t\t\t$hashField.parent().parent().addClass('has-error');\r\n\t\t\t\t\t\t\t$(\"i\", $this).css('display', 'none');\r\n\t\t\t\t\t\t\t$this.removeAttr('disabled');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}else{\r\n\t\t\t\t\talert('Please wait 10 seconds...');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t$('.process-btn').on('click', function(){\r\n\t\t\tvar $this = $(this);\r\n\t\t\tvar payoutId = $(this).attr('id').replace('submit[', '').replace(']', '');\r\n\t\t\tvar $hashField = $(\".hash-field#inputBlock\\\\[\" + payoutId + \"\\\\]\");\r\n\t\t\tif($hashField.val() == ''){\r\n\t\t\t\t$hashField.parent().parent().addClass('has-error');\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t$this.prop('disabled', 'disabled');\r\n\t\t\t$(\"i\", $this).css('display', 'inline-block');\r\n\t\t\t\r\n\t\t\t$.ajax({\r\n\t\t\t\ttype: \"POST\",\r\n\t\t\t\turl: \"<?php echo base_url('pending1432/process') ?>\",\r\n\t\t\t\tdataType : \"JSON\",\r\n\t\t\t\tdata: \"payoutId=\" + payoutId + \"&payoutHash=\" + $hashField.val(),\r\n\t\t\t\tsuccess: function(data){\r\n\t\t\t\t\tif(data.status == \"1\"){\r\n\t\t\t\t\t\t$hashField.prop('disabled', 'disabled');\r\n\t\t\t\t\t\t$hashField.parent().parent().addClass('has-success');\r\n\t\t\t\t\t\t$this.remove();\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\t$hashField.parent().parent().addClass('has-error');\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\terror: function(data){\r\n\t\t\t\t\t$hashField.parent().parent().addClass('has-error');\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\t$('.hash-field').on('keyup', function(){\r\n\t\t\t$(this).parent().parent().removeClass('has-error');\r\n\t\t});\r\n\t});\r\n</script>" }, { "alpha_fraction": 0.5887234210968018, "alphanum_fraction": 0.6065957546234131, "avg_line_length": 42.92523193359375, "blob_id": "a8c39d4ff2bc0591b7a6ed65ca1ba8c26e7bfe2b", "content_id": "7e7282aed2ffbdd7c807313fefbe5ce46a508be5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4700, "license_type": "permissive", "max_line_length": 182, "num_lines": 107, "path": "/pool/application/controllers/Payout1432.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\nrequire_once APPPATH.'third_party/Guzzle/autoloader.php';\nuse GuzzleHttp\\Client;\nclass Payout1432 extends MY_Controller {\n\n\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\t\t$this->load->model('accountmodel', 'model');\n\t\t// if(NULL === $this->session->userdata('xrb_address'))\n\t\t// \tredirect('login');\n\t}\n\n\tpublic function index()\n\t{\n\t\t$data['active'] = 'payout1432';\n\t\t$this->view('pages/payout', $data);\n\t}\n\n\tpublic function cli($time = NULL, $mrai = 0){\n\t\terror_reporting(-1);\n\t\tini_set('display_errors', 1);\n\t\t\n\t\t$startTime = microtime(true);\n\t\t$arrDistribution = json_decode(performGet('https://faucet.raiblockscommunity.net/history.php?json=1'), TRUE);\n\n\t\t$dbDistribution = $this->db->get('distribution_history')->row();\n\t\t$disStart = $time == NULL ? $arrDistribution['distributions'][0]['time_start'] : $time;\n\t\t//$disStart = 1493953202;\n\t\tif($dbDistribution->distributionCurrent != $disStart){\n\t\t\t$distributionSingle = json_decode(performGet('https://faucet.raiblockscommunity.net/distribution-single.php?did=' . $disStart . '&json=1'), TRUE);\n\t\t\t$indexPool = getIndexByValue($distributionSingle['pending'], 'account', $this->config->item('xrb_address'));\n\t\t\tif(NULL != $indexPool || NULL != $time){\n\t\t\t\t$disMrai = $time == NULL ? $distributionSingle['pending'][$indexPool]['amount'] / 1000000 : $mrai;\n\t\t\t\t//$disMrai = 1836;\n\n\t\t\t\t$paylist = $this->model->populatePaylist(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 3600), date(\"Y-m-d H:i:s\", $disStart + 3600));\n\t\t\t\t\t\t// $poolClaim = number_format($distributionSingle['pending'][$indexPool]['ask'], 0, '.', '');\n\t\t\t\t$poolClaim = $this->model->countClaims(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 1 * 3600), date(\"Y-m-d H:i:s\", $disStart + 1 * 3600));\n\n\t\t\t\tforeach ($paylist as $row) {\n\t\t\t\t\tif($row->totalClaim > 0){\n\t\t\t\t\t\t$claimRate = $disMrai / $poolClaim;\n\t\t\t\t\t\t$memberMrai = $row->totalClaim / $poolClaim * $disMrai;\n\t\t\t\t\t\t$claimMrai = $memberMrai;\n\t\t\t\t\t\t$memberMrai = $memberMrai + $row->accountBalance;\n\t\t\t\t\t\tif($memberMrai >= $row->accountThreshold){\n\t\t\t\t\t\t\t$payoutMrai = $memberMrai - ((2 / 100) * $memberMrai);\n\t\t\t\t\t\t\t$payoutProfit = ((2 / 100) * $memberMrai);\n\t\t\t\t\t\t\tforeach($this->db->where('accountId', $row->accountId)->where('payoutStatus', 'p')->get('payout_history')->result() as $payout){\n\t\t\t\t\t\t\t\t$payoutMrai = $payoutMrai + $payout->payoutQty;\n\t\t\t\t\t\t\t\t$payoutProfit = $payoutProfit + $payout->payoutProfit;\n\n\t\t\t\t\t\t\t\t$this->db->where('payoutId', $payout->payoutId)->delete('payout_history');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$this->db->insert('payout_history', array(\n\t\t\t\t\t\t\t\t'accountId' => $row->accountId,\n\t\t\t\t\t\t\t\t'payoutProfit' => number_format($payoutProfit, 6, '.', ''),\n\t\t\t\t\t\t\t\t'payoutQty' => number_format($payoutMrai, 6, '.', ''),\n\t\t\t\t\t\t\t\t'payoutTime' => date(\"Y-m-d H:i:s\"),\n\t\t\t\t\t\t\t\t'payoutStatus' => 'p'\n\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\tif($row->accountBalance > 0){\n\t\t\t\t\t\t\t\t$this->db->where('accountId', $row->accountId)->update('app_account', array(\n\t\t\t\t\t\t\t\t\t'accountBalance' => '0'\n\t\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\techo \"payout to: \" . $row->accountAddress . ' ' . number_format($payoutMrai, 6, '.', '') . \" mrai <br>\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t$this->db->where('accountId', $row->accountId)->update('app_account', array(\n\t\t\t\t\t\t\t\t'accountBalance' => number_format($memberMrai, 6, '.', '')\n\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\techo \"updating balance to: \" . $row->accountAddress . ' ' . number_format($memberMrai, 6, '.', '') . \" mrai <br>\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$this->db->insert('app_account_claim', array(\n\t\t\t\t\t\t\t'accountId' => $row->accountId,\n\t\t\t\t\t\t\t'claimQty' => $row->totalClaim,\n\t\t\t\t\t\t\t'claimRate' => number_format($claimRate, 6, '.', ','),\n\t\t\t\t\t\t\t'claimMrai' => number_format($claimMrai, 6, '.', ''),\n\t\t\t\t\t\t\t'createdTime' => date(\"Y-m-d H:i:s\")\n\t\t\t\t\t\t));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$this->db->where('distributionId', 1)->update('distribution_history', array(\n\t\t\t\t\t'distributionPrevious' => $dbDistribution->distributionCurrent,\n\t\t\t\t\t'distributionCurrent' => $disStart\n\t\t\t\t));\n\n\t\t\t\t$this->db->query(\"DELETE FROM pending_claims WHERE claimTime < '\" . date(\"Y-m-d H:i:s\", $disStart + 3600) . \"'\");\n\t\t\t}else {\n\t\t\t\techo 'pool not in top 60';\n\t\t\t}\n\t\t}else{\n\t\t\techo 'distribution already done.';\n\t\t}\n\n\t\t$rowCount = $this->db->query(\"SELECT COUNT(*) count FROM cron_history\")->row()->count;\n\t\tif($rowCount >= 1000)\n\t\t\t$this->db->truncate('cron_history');\n\t\t$time_elapsed_secs = microtime(true) - $startTime;\n\t\t$this->db->insert('cron_history', array('cronDuration' => number_format($time_elapsed_secs, 3, '.', ',') . \" ms\", 'cronTime' => date('Y-m-d H:i:s'), 'cronType' => 'distribution'));\n\t}\n}\n\n/* End of file Index.php */\n/* Location: ./application/controllers/Index.php */\n" }, { "alpha_fraction": 0.6528497338294983, "alphanum_fraction": 0.6865285038948059, "avg_line_length": 24.799999237060547, "blob_id": "0ba97d1dc0119b1d494732fe61c2dae4387b04ad", "content_id": "0c2c7febb51746a9bfc0e32314844df0e781704b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "permissive", "max_line_length": 80, "num_lines": 15, "path": "/XbitzPoolBot/common.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import re\n\ndef raiblocks_account_validate(account):\n\tif isinstance(account, str):\n\t\tif (\"xrb_1\" in account) or (\"xrb_3\" in account) and (len(account) == 64):\n\t\t\taccount = account[4:]\n\t\t\tchar_validation = re.search(\"^[13456789abcdefghijkmnopqrstuwxyz]+$\", account)\n\t\t\tif char_validation is not None:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False" }, { "alpha_fraction": 0.6023701429367065, "alphanum_fraction": 0.6157337427139282, "avg_line_length": 36.06542205810547, "blob_id": "76ef8d39bdab6853606738f850ab49cc2cf06a94", "content_id": "8e388aed80fd852d8caaf59c85ef880713c6e961", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3966, "license_type": "permissive", "max_line_length": 564, "num_lines": 107, "path": "/pool/application/views/pages/faucet.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\n$distribution = $this->db->get('distribution_history')->row();\n$accountId = $this->model->isAccountExist($this->session->userdata('xrb_address')['address'])->accountId;\n$claimStat = $this->db->query(\"SELECT (SELECT COUNT(*) FROM pending_claims WHERE accountId = '\" . $accountId . \"' AND claimStatus = 'p' AND claimTime BETWEEN '\" . date(\"Y-m-d H:i:s\", $distribution->distributionCurrent + 3600) . \"' AND '\" . date(\"Y-m-d H:i:s\", time() + 3600) . \"') pendingClaims, (SELECT COUNT(*) FROM pending_claims WHERE accountId = '\" . $accountId . \"' AND claimStatus = 'd' AND claimTime BETWEEN '\" . date(\"Y-m-d H:i:s\", $distribution->distributionCurrent + 3600) . \"' AND '\" . date(\"Y-m-d H:i:s\", time() + 3600) . \"') validatedClaims\")->row();\n\n#By using this tool, you are agreed to donate to RaiBlocks's dev.\n?>\n<div id=\"modal\" class=\"modal fade\" tabindex=\"-1\" role=\"dialog\">\n\t<div class=\"modal-dialog\" role=\"document\">\n\t\t<div class=\"modal-content\">\n\t\t\t<div class=\"modal-header\">\n\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n\t\t\t\t<h4 class=\"modal-title\">Attention!</h4>\n\t\t\t</div>\n\t\t\t<div class=\"modal-body\">\n\t\t\t\t<p>\n\t\t\t\t\tHi, <br>\n\t\t\t\t\tI'm closing the pool on Sunday May 21 GMT+7. All the mrai balance from active users for the past two weeks will be processed without any fee.\n\t\t\t\t\t<br><br>\n\t\t\t\t\tBest regards,\n\t\t\t\t\tuoy14\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>\n<div class=\"container-fluid\">\n\t<div class=\"row\">\n\t\t<div class=\"col-md-offset-3 col-md-6\">\n\t\t\t<table class=\"table\">\n\t\t\t\t<thead>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th class=\"text-center\">Pool Claims</small></th>\n\t\t\t\t\t\t<th class=\"text-center\">Threshold </th>\n\t\t\t\t\t\t<th class=\"text-center\">Top 60</th>\n\t\t\t\t\t\t<th class=\"text-center\">Distribution</th>\n\t\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody style=\"font-size: 18px;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td class=\"text-center\" id=\"displayPoolClaims\">\n\t\t\t\t\t\t\t...\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td class=\"text-center\" id=\"displayThreshold\">\n\t\t\t\t\t\t\t...\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td class=\"text-center\" id=\"displayTop60\">\n\t\t\t\t\t\t\t...\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td class=\"text-center\" id=\"displayNextDistribution\">\n\t\t\t\t\t\t\t...\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>\n\t</div>\n</div>\n<div class=\"container-fluid\">\n\t<div class=\"col-md-6 col-md-offset-3\">\n\t\t<div id=\"validationMessage\" class=\"alert alert-danger text-center\" role=\"alert\" style=\"display: none;\">\n\t\t\tMaintenance\n\t\t</div>\n\t\t<button id=\"claimButton\" class=\"g-recaptcha btn btn-primary btn-lg col-xs-12\" data-sitekey=\"6Lf0qx8UAAAAAN1eEGr2nSAFckLjjVuzXAw4qhHM\" data-callback=\"onClaim\">Claim</button>\n\t\t<div class=\"clearfix\"></div>\n\t\t<br>\n\t\t<div class=\"row\">\n\t\t\t<div class=\"row\" id=\"claimStat\">\n\t\t\t\t<div class=\"col-md-4 text-center\">\n\t\t\t\t\t<h4>Current: <span id=\"currentClaims\" class=\"label label-primary\">0</span></h4>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"col-md-4 text-center\">\n\t\t\t\t\t<h4>Pending: <span id=\"pendingClaims\" class=\"label label-warning\"><?php echo $claimStat->pendingClaims ?></span></h4>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"col-md-4 text-center\">\n\t\t\t\t\t<h4>Validated: <span id=\"validatedClaims\" class=\"label label-success\"><?php echo $claimStat->validatedClaims ?></span></h4>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"row\">\n\t\t\t<div class=\"col-md-12 text-center\">\n\t\t\t\t<div class=\"checkbox\">\n\t\t\t\t\t<label>\n\t\t\t\t\t\t<input type=\"checkbox\" id=\"nightToggle\" value=\"1\"> Night Mode\n\t\t\t\t\t</label>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"row\">\n\t\t\t<div class=\"col-md-12\">\n\t\t\t\t<h4 class=\"text-center\"><a href=\"https://faucet.raiblockscommunity.net/paylist.php?acc=<?php echo $this->config->item('xrb_address') ?>\" target=\"_blank\">View Pool Progress</a></h4>\n\t\t\t\t<br>\n\t\t\t\t<p class=\"text-center\" id=\"donateInformation\"><b></b></p>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>\n<script type=\"text/javascript\">\n\t$(document).ready(function(){\n\t\t$('#modal').modal({\n\t\t\tshow: true\n\t\t});\n\t});\n</script>\n\n<script src=\"https://www.google.com/recaptcha/api.js\" async defer></script>\n<script src=\"<?php echo base_url('assets/js/faucet.js') ?>\"></script>\n" }, { "alpha_fraction": 0.6187363862991333, "alphanum_fraction": 0.6209150552749634, "avg_line_length": 18.954545974731445, "blob_id": "626a05b7f1c736cdd76cebfa5151fdc4a693fdd6", "content_id": "7be265ead5c450aaa8b8892bf036e6b3e2f13e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 459, "license_type": "permissive", "max_line_length": 63, "num_lines": 22, "path": "/pool/application/controllers/Payouts.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Payouts extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t// $this->output->cache(5);\r\n\t\t$data['active'] = 'payouts';\r\n\t\t$this->view('pages/payouts', $data);\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Payouts.php */\r\n/* Location: ./application/controllers/Payouts.php */" }, { "alpha_fraction": 0.6305854916572571, "alphanum_fraction": 0.6398305296897888, "avg_line_length": 69.1891860961914, "blob_id": "54485e96e77b6c28ed421178257b0cac4e7ad151", "content_id": "19c0092189c260b59f0c85a4b5ee384f2da471c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2596, "license_type": "permissive", "max_line_length": 304, "num_lines": 37, "path": "/XbitzPoolBot/lang.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "LANG = {\n\t\"EN\":{\n\t\t\"start_new\": \"Hi! Welcome to XbitzPoolBot. \\nSend:\\n*/register xrb_address* \\nto register.\",\n\t\t\"start_old\": \"Hi {}! \\nWelcome back to XbitzPoolBot.\\n\",\n\t\t\"help\": \"Here you can see your current claims, daily stats, claim reward, profile and pending payout.\\n\\n*/paylist* - See your current claims and pool's stats\\n*/stats* - See your daily stats\\n*/profile* - See your account details\\n*/pending* - See your pending payout\\n*/paid* - See your paid payout\",\n\t\t\"profile\": \"Account Details\\nName: *{}*\\nAddress: *{}*\\nPayout Threshold: *{:,} Mrai (XRB)*\\nBalance: *{:,.6f} Mrai (XRB)*\",\n\t\t\"no_pending\": \"You have no pending payout above threshold.\",\n\t\t\"has_pending\": \"You have one pending payout above threshold\\nPayout Time: *{}*\\nPayout Amount: *{:,.6f} Mrai (XRB)*\",\n\t\t\"header_paid\": \"Your last {:,} payout(s) details\",\n\t\t\"item_paid\": \"Payout Time: *{}*\\nPayout Amount: *{:,.6f} Mrai (XRB)*\\nPayout Hash: [hash in block explorer](https://raiblockscommunity.net/block/index.php?h={})\",\n\t\t\"no_today_distributions\": \"No distribution for you today.\",\n\t\t\"header_today_distributions\": \"Today's last {:,} distribution(s) details\",\n\t\t\"item_today_distributions\": \"Distribution Time: *{}*\\nClaims: *{:,}*\\nReward: *{:,.6f} Mrai (XRB)*\\nClaim Rate: *{:.6f} Mrai (XRB)*\",\n\t\t\"non_top60_paylist\": \"Valid Claims: *{:,}*\\nInvalid Claims: *{:,}*\\nPending Claims: *{:,}*\",\n\t\t\"top60_paylist\": \"Valid Claims: *{:,}*\\nInvalid Claims: *{:,}*\\nPending Claims: *{:,}*\\nYour Reward: *{:,.6f} Mrai (XRB)*\",\n\t\t\"non_top60_pool_paylist\": \"Pools Claims: *{:,}*\\nThreshold: *{:,}\\n*Top 60: *{}*\\nClaim Rate: *{:.6f} Mrai (XRB)*\",\n\t\t\"top60_pool_paylist\": \"Pools Claims: *{:,}*\\nThreshold: *{:,}\\n*Top 60: *{}*\\nPools Reward: *{:,.6f} Mrai (XRB)*\\nClaim Rate: *{:.6f} Mrai (XRB)*\",\n\t\t\"notify_distribution\": \"You made *{:,} claims* this hour.\\nReward: *{:,.6f} Mrai (XRB)*\\nClaim Reward: *{:.6f} Mrai (XRB)*\\nCurrent Balance: *{:,.6f} Mrai (XRB)*\",\n\t\t\"empty_broadcast\": \"You can't broadcast an empty message.\",\n\t\t\"processing_broadcast\": \"Sending message *{}* to *{:,}* member(s)\",\n\t\t\"sending_broadcast\": \"Sending message to *{}*\",\n\t\t\"content_broadcast\": \"Message from Admin\\n\\n{}\",\n\t\t\"done_broadcast\": \"Sent to *{:,}* member(s)\",\n\t\t\"empty_register\": \"Please specify an address.\",\n\t\t\"invalid_register\": \"Please specify a valid address.\",\n\t\t\"exist_register\": \"This address already in use, please use another address.\",\n\t\t\"not_found_register\": \"Please register [here](http://xbitzpool.com/login) before using this bot.\"\n\t}\n}\n\ndef lang(key):\n\tret = None\n\t\n\tif key in LANG[\"EN\"]:\n\t\tret = LANG[\"EN\"][key]\n\n\treturn ret" }, { "alpha_fraction": 0.5933412313461304, "alphanum_fraction": 0.6004756093025208, "avg_line_length": 33.125, "blob_id": "cd0b2703e8fc35ae46807550662f2924788c6a17", "content_id": "73ca518a16f25f739c11e92a568b274756f0b222", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 841, "license_type": "permissive", "max_line_length": 113, "num_lines": 24, "path": "/pool/application/views/pages/login.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<div class=\"container-fluid\">\r\n\t<div class=\"col-md-6 col-md-offset-3\">\r\n\t\t<form action=\"<?php echo base_url('login') ?>\" method=\"POST\">\r\n\t\t\t<?php\r\n\t\t\tif(NULL != $this->input->get('error')){\r\n\t\t\t\t?>\r\n\t\t\t\t<div class=\"alert alert-danger text-center\" role=\"alert\">\r\n\t\t\t\t\t<?php echo urldecode($this->input->get('error')) ?>\r\n\t\t\t\t</div>\r\n\t\t\t\t<?php\r\n\t\t\t}\r\n\t\t\t?>\r\n\t\t\t<legend>Sign In</legend>\r\n\t\t\t<div class=\"alert alert-info\" role=\"alert\">\r\n\t\t\t\t<p><b>Make sure</b> you use valid address.</p>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"form-group\">\r\n\t\t\t\t<label for=\"inputAddress\">XRB address</label>\r\n\t\t\t\t<input type=\"text\" class=\"form-control\" id=\"inputAddress\" placeholder=\"Your XRB Address\" name=\"inputAddress\">\r\n\t\t\t</div>\r\n\t\t\t<button type=\"submit\" name=\"submit\" value=\"login\" class=\"btn btn-primary col-md-12 col-xs-12\">Login</button>\r\n\t\t</form>\r\n\t</div>\r\n</div>" }, { "alpha_fraction": 0.5551658272743225, "alphanum_fraction": 0.5679209232330322, "avg_line_length": 39.84000015258789, "blob_id": "683d3b0f9c29319dda1bb5399c486803ac32fae9", "content_id": "91731bdae70b5b11bf4f39a0de81b2687658caf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3136, "license_type": "permissive", "max_line_length": 263, "num_lines": 75, "path": "/pool/application/views/pages/logs.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<div class=\"container-fluid\">\r\n\t<div class=\"col-md-12\">\r\n\t\t<div class=\"alert alert-info\" role=\"alert\">\r\n\t\t<b>Please note</b> that there will be invalid claims. We are trying our best to decrease it.\r\n\t\t</div>\r\n\t\t<div class=\"page-header\">\r\n\t\t\t<h1>FAUCET LOGS <small>LAST <b>20</b> RECORDS</small></h1>\r\n\t\t</div>\r\n\t\t<table class=\"table\">\r\n\t\t\t<thead>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th width=\"80\" class=\"text-right\">#</th>\r\n\t\t\t\t\t<th width=\"220\" class=\"text-center\">Datetime</th>\r\n\t\t\t\t\t<th>Status</th>\r\n\t\t\t\t\t<th width=\"120\" class=\"text-right\">Attempts</th>\r\n\t\t\t\t\t<th width=\"120\" class=\"text-right\">Claims Sent</th>\r\n\t\t\t\t\t<th width=\"120\" class=\"text-right\">Valid Claims</th>\r\n\t\t\t\t\t<th width=\"120\" class=\"text-right\">Invalid Claims</th>\r\n\t\t\t\t</tr>\r\n\t\t\t</thead>\r\n\t\t\t<tbody>\r\n\t\t\t\t<?php\r\n\t\t\t\t$arrAttemptColor = array(\r\n\t\t\t\t\t\"1\" => \"text-success\",\r\n\t\t\t\t\t\"2\" => \"text-warning\",\r\n\t\t\t\t\t\"3\" => \"text-danger\"\r\n\t\t\t\t\t);\r\n\t\t\t\t$no = 0;\r\n\t\t\t\t$lastCronTime = \"\";\r\n\t\t\t\t$totalClaimsSent = 0;\r\n\t\t\t\t$totalServerValidClaims = 0;\r\n\t\t\t\t$totalInvalidClaims = 0;\r\n\t\t\t\t$logs = $this->db->where('cronType', 'faucet')->order_by('cronTime', 'DESC')->limit(20)->get('cron_history')->result();\r\n\t\t\t\tforeach($logs as $log){\r\n\t\t\t\t\t$no++;\r\n\t\t\t\t\t$cronContent = json_decode($log->cronContent, TRUE);\r\n\t\t\t\t\t$claimsSent = count(json_decode($cronContent['claimsSent'], TRUE));\r\n\t\t\t\t\t$serverValidClaims = count(json_decode($cronContent['serverValidClaims'], TRUE));\r\n\t\t\t\t\t$invalidClaims = $claimsSent - $serverValidClaims;\r\n\r\n\t\t\t\t\t$totalClaimsSent += $claimsSent;\r\n\t\t\t\t\t$totalServerValidClaims += $serverValidClaims;\r\n\t\t\t\t\t$totalInvalidClaims += $invalidClaims;\r\n\t\t\t\t\t?>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\r\n\t\t\t\t\t\t<td class=\"text-center\"><?php echo date(\"M d H:i:s\", strtotime($log->cronTime)) ?></td>\r\n\t\t\t\t\t\t<td><b><?php echo $cronContent['serverError'] == \"no\" ? \"<span class=\\\"text-success\\\">OK ( \" . $log->cronDuration . \" )</span>\" : \"<span class=\\\"text-danger\\\">\" . strtoupper($cronContent['serverError']) . \" ( \" . $log->cronDuration . \" )</span>\" ?></b></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><b><?php echo isset($cronContent['validationAttemps']) ? \"<span class=\\\"{$arrAttemptColor[$cronContent['validationAttemps']]}\\\">{$cronContent['validationAttemps']}</span>\" : '-' ?></b></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($claimsSent, 0, '.', ',') ?></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($serverValidClaims, 0, '.', ',') ?></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($invalidClaims, 0, '.', ',') ?></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<?php\r\n\r\n\t\t\t\t}\r\n\t\t\t\t?>\r\n\t\t\t</tbody>\r\n\t\t\t<tfoot>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan=\"4\">&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class=\"info\">\r\n\t\t\t\t\t<td colspan=\"4\" class=\"text-right\">Total</td>\r\n\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalClaimsSent, 0, '.', ',') ?></td>\r\n\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalServerValidClaims, 0, '.', ',') ?></td>\r\n\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalInvalidClaims, 0, '.', ',') ?></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</tfoot>\r\n\t\t</table>\r\n\t</div>\r\n</div>" }, { "alpha_fraction": 0.7665369510650635, "alphanum_fraction": 0.7665369510650635, "avg_line_length": 24.799999237060547, "blob_id": "7b32ff072c4e80c88c0a8620ea35ab808b8d218a", "content_id": "25cf0fc21b31c908c84aec5e62a4c0a379006936", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 257, "license_type": "permissive", "max_line_length": 162, "num_lines": 10, "path": "/pool/readme.md", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "# XbitzPool - Main Site\nXbitzPool is one of RaiBlocks faucet pool based on mainly PHP CodeIgniter and Python. In this repository, there are pool, api, bot, and faucet validation sources.\n\n# Configuration\n - application/config/config.php\n \nLicense\n----\n\nMIT" }, { "alpha_fraction": 0.6039953231811523, "alphanum_fraction": 0.6063454747200012, "avg_line_length": 30.769229888916016, "blob_id": "af9e054bb09255917f5c470f5c60b69682496d43", "content_id": "9025011f8bf4380b12a7414bf48ec2b0b2b02f5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1702, "license_type": "permissive", "max_line_length": 126, "num_lines": 52, "path": "/pool/application/controllers/Register.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Register extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t\tif(NULL !== $this->session->userdata('xrb_address'))\r\n\t\t\tredirect('index');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\tif(NULL != $this->input->post('submit')){\r\n\t\t\t$continue = TRUE;\r\n\t\t\tif(strpos($this->input->post('inputAddress'), 'RaiWalletBot: ') !== false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(strpos($this->input->post('inputAddress'), 'xrb_') === false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(!filter_var($this->input->post('inputAddress'), FILTER_VALIDATE_EMAIL) === false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(strlen($this->input->post('inputAddress')) < 64 || strlen($this->input->post('inputAddress')) > 64){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif($continue){\r\n\t\t\t\tif($this->model->isUsernameExist(trim($this->input->post('inputFullname'))))\r\n\t\t\t\t\tredirect('login?error=' . urlencode(\"Account Exist\"));\r\n\t\t\t\tif($this->model->isAccountExist(trim($this->input->post('inputAddress'))))\r\n\t\t\t\t\tredirect('login?error=' . urlencode(\"Account Exist\"));\r\n\t\t\t\t$res = $this->model->registerAccount(trim($this->input->post('inputAddress')), trim($this->input->post('inputFullname')));\r\n\t\t\t\tif($res){\r\n\t\t\t\t\t$sess['xrb_address'] = array('address' => trim($this->input->post('inputAddress')));\r\n\t\t\t\t\t$this->session->set_userdata($sess);\r\n\t\t\t\t\tredirect('index');\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\tredirect('login?error=' . urlencode(\"Invalid Address\"));\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\tredirect('login');\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Register.php */\r\n/* Location: ./application/controllers/Register.php */" }, { "alpha_fraction": 0.6106785535812378, "alphanum_fraction": 0.6173526048660278, "avg_line_length": 28.03333282470703, "blob_id": "3449bb9280528a3e30da949b11b3d1d2e772966f", "content_id": "995557545b958b10bd7f4d395600240a607eecee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 899, "license_type": "permissive", "max_line_length": 95, "num_lines": 30, "path": "/pool/application/controllers/Profile.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Profile extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t\tif(NULL === $this->session->userdata('xrb_address'))\r\n\t\t\tredirect('login');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\tif(NULL !== $this->input->post('submit')){\r\n\t\t\t$account = $this->model->isAccountExist($this->session->userdata('xrb_address')['address']);\r\n\t\t\tif($this->input->post('threshold') >= 50 && $this->input->post('threshold') <= 1000)\r\n\t\t\t\t$this->db->where('accountId', $account->accountId)->update('app_account', array(\r\n\t\t\t\t\t'accountThreshold' => $this->input->post('threshold')\r\n\t\t\t\t));\r\n\t\t}\r\n\t\t$data['active'] = 'account';\r\n\t\t$this->view('pages/profile', $data);\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Profile.php */\r\n/* Location: ./application/controllers/Profile.php */" }, { "alpha_fraction": 0.5951417088508606, "alphanum_fraction": 0.5951417088508606, "avg_line_length": 18.66666603088379, "blob_id": "a5de06019ea205624fe66217df13eab24fc80a3d", "content_id": "fdc1c032e9932480182753e326b05d07f0d06a2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 494, "license_type": "permissive", "max_line_length": 63, "num_lines": 24, "path": "/pool/application/core/MY_Controller.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass MY_Controller extends CI_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t}\r\n\r\n\tprotected function view($view, $data = array()){\r\n\t\t$load = array();\r\n\t\t$load['content'] = $view;\r\n\t\t\r\n\t\tforeach($data as $key => $val){\r\n\t\t\t$load[$key] = $val;\r\n\t\t}\r\n\r\n\t\t$this->load->view('base', $load);\r\n\t}\r\n}\r\n\r\n/* End of file MY_Controller.php */\r\n/* Location: ./application/core/MY_Controller.php */" }, { "alpha_fraction": 0.5440295934677124, "alphanum_fraction": 0.5544205904006958, "avg_line_length": 37.11409378051758, "blob_id": "db0bf3f91b11a6c45a147ae668ed6fd67af1ead2", "content_id": "3a4b36fc243449b6feb7bc33055df8af40f0f98a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5678, "license_type": "permissive", "max_line_length": 230, "num_lines": 149, "path": "/pool/application/views/pages/profile.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\n$account = $this->model->isAccountExist($this->session->userdata('xrb_address')['address']);\n?>\n<div class=\"container-fluid\">\n\t<div class=\"col-md-8 col-md-offset-2\">\n\t\t<div class=\"panel panel-default\">\n\t\t\t<div class=\"panel-heading\">General Information</div>\n\t\t\t<div class=\"panel-body\">\n\t\t\t\t<form class=\"form-horizontal\" action=\"<?php echo base_url('profile') ?>\" method=\"POST\">\n\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Fullname</label>\n\t\t\t\t\t\t<div class=\"col-sm-9\">\n\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo $account->accountName ?></p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">XRB Address</label>\n\t\t\t\t\t\t<div class=\"col-sm-9\">\n\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo $account->accountAddress ?></p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Available Balance</label>\n\t\t\t\t\t\t<div class=\"col-sm-9\">\n\t\t\t\t\t\t\t<p class=\"form-control-static\" style=\"word-wrap: break-word;\"><?php echo number_format($account->accountBalance, 6, '.', ',') ?> Mrai</p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t<label class=\"col-sm-3 control-label\">Payout Threshold (Mrai)</label>\n\t\t\t\t\t\t<div class=\"col-sm-9\">\n\t\t\t\t\t\t\t<input type=\"number\" name=\"threshold\" class=\"form-control\" style=\"text-align: right\" value=\"<?php echo $account->accountThreshold ?>\" >\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t<div class=\"col-sm-offset-3 col-sm-9\">\n\t\t\t\t\t\t\t<button type=\"submit\" name=\"submit\" value=\"save\" class=\"btn btn-primary col-md-12 col-xs-12\">Save</button>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</form>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"panel panel-default\">\n\t\t\t<div class=\"panel-heading\">Claim History <small>Today</small></div>\n\t\t\t<div class=\"panel-body\">\n\t\t\t\t<table class=\"table\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"40\">#</th>\n\t\t\t\t\t\t\t<th class=\"text-center\">Datetime</th>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"180\">Claim Rate</th>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"180\">Total Claim</th>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"180\">Mrai Received</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t$claims = $this->db->where('accountId', $account->accountId)->where('DATE(createdTime)', date(\"Y-m-d\"))->order_by('createdTime', 'DESC')->get('app_account_claim')->result();\n\t\t\t\t\t\t$no = 0;\n\t\t\t\t\t\t$totalClaim = 0;\n\t\t\t\t\t\t$totalMrai = 0;\n\t\t\t\t\t\tforeach ($claims as $row) {\n\t\t\t\t\t\t\t$no++;\n\t\t\t\t\t\t\t$totalClaim += $row->claimQty;\n\t\t\t\t\t\t\t$totalMrai += $row->claimMrai;\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\n\t\t\t\t\t\t\t\t<td class=\"text-center\"><?php echo date(\"M d H:i:s\", strtotime($row->createdTime)) ?></td>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->claimRate, 6, '.', ',') ?> Mrai</td>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->claimQty, 0, '.', ',') ?> Claims</td>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->claimMrai, 6, '.', ',') ?> Mrai</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t</tbody>\n\t\t\t\t\t<tfoot>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan=\"3\">&nbsp;</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class=\"info\">\n\t\t\t\t\t\t\t<td colspan=\"3\" class=\"text-right\">Total</td>\n\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalClaim, 0, '.', ',') ?> Claims</td>\n\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalMrai, 6, '.', ',') ?> Mrai</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</tfoot>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t</div>\n\n\t\t<?php\n\t\tif(isBTC($account->accountAddress)){\n\t\t\t?>\n\t\t\t<div class=\"alert alert-info\" role=\"alert\">\n\t\t\t\t<b>Please note</b> that this payout is from pool. BTC Payout will be processed by your leader.\n\t\t\t</div>\n\t\t\t<?php\n\t\t}\n\t\t?>\n\t\t<div class=\"panel panel-default\">\n\t\t\t<div class=\"panel-heading\">Payout History <small>Last <b>10</b> Records</small></div>\n\t\t\t<div class=\"panel-body\">\n\t\t\t\t<table class=\"table\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"40\">#</th>\n\t\t\t\t\t\t\t<th class=\"text-center\" width=\"180\">Datetime</th>\n\t\t\t\t\t\t\t<th class=\"text-center\">Block</th>\n\t\t\t\t\t\t\t<th class=\"text-center\" width=\"80\">Status</th>\n\t\t\t\t\t\t\t<th class=\"text-right\" width=\"80\">Amount</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<tbody>\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t$payouts = $this->db->where('accountId', $account->accountId)->order_by('payoutTime', 'DESC')->limit(10)->get('payout_history')->result();\n\t\t\t\t\t\t$no = 0;\n\t\t\t\t\t\t$totalMrai = 0;\n\t\t\t\t\t\tforeach($payouts as $row){\n\t\t\t\t\t\t\t$no++;\n\t\t\t\t\t\t\t$totalMrai += $row->payoutQty;\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\n\t\t\t\t\t\t\t\t<td class=\"text-center\"><?php echo date(\"M d H:i:s\", strtotime($row->payoutTime)) ?></td>\n\t\t\t\t\t\t\t\t<td class=\"text-center\"><?php echo $row->payoutStatus == \"p\" ? \"...\" : '<a href=\"https://raiblockscommunity.net/block/index.php?h=' . $row->payoutHash . '\" target=\"_blank\">' . truncate($row->payoutHash, 40). '</a>' ?></td>\n\t\t\t\t\t\t\t\t<td class=\"text-center\"><?php echo $row->payoutStatus == \"p\" ? \"<span class=\\\"label label-warning\\\">Pending</span>\" : \"<span class=\\\"label label-success\\\">Completed</span>\" ?></td>\n\t\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->payoutQty, 6, '.', ',') ?> Mrai</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t</tbody>\n\t\t\t\t\t<tfoot>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan=\"4\">&nbsp;</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class=\"info\">\n\t\t\t\t\t\t\t<td colspan=\"4\" class=\"text-right\">Total</td>\n\t\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalMrai, 6, '.', ',') ?> Mrai</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</tfoot>\n\t\t\t\t</table>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>" }, { "alpha_fraction": 0.6425829529762268, "alphanum_fraction": 0.6502596735954285, "avg_line_length": 25.018293380737305, "blob_id": "d3f512acb245d33963a61417cd0d3ae664d440c6", "content_id": "2f1bc2b095b59c8379e6cf76e54244335ba59100", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4429, "license_type": "permissive", "max_line_length": 140, "num_lines": 164, "path": "/faucet.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import os\r\nimport logging\r\nfrom urllib.parse import urlencode\r\nfrom urllib.request import Request, urlopen\r\nfrom urllib.error import URLError, HTTPError\r\nimport json\r\nimport mysql.connector\r\nfrom time import sleep, time\r\nfrom datetime import datetime\r\n\r\nmysql_config = {\r\n 'user': 'root',\r\n 'password': '',\r\n 'host': '127.0.0.1',\r\n 'database': 'app_pool',\r\n 'raise_on_warnings': True,\r\n}\r\nattempt = 0\r\nxrb_address = \"xrb_1bawnqs6cc9a91ziwoy7fgmdycyjk9r6dt7eerfgzdbysrfnbihfxzobt8c8\"\r\n\r\ndef log_insert(data):\r\n\tcnx = mysql.connector.connect(**mysql_config)\r\n\tcursor = cnx.cursor()\r\n\t\r\n\tquery = (\"INSERT INTO cron_history (cronDuration, cronTime, cronType, cronContent) VALUES (%(duration)s, %(time)s, 'faucet', %(content)s)\")\r\n\t\r\n\tcursor.execute(query, data)\r\n\tcnx.commit()\r\n\tcursor.close()\r\n\tcnx.close()\r\n\r\n\r\ndef log_clear(claimCaptchas, claimStatus):\r\n\tcnx = mysql.connector.connect(**mysql_config)\r\n\tcursor = cnx.cursor()\r\n\t\r\n\tquery = (\"TRUNCATE cron_history\")\r\n\t\r\n\tcursor.execute(query)\r\n\tcnx.commit()\r\n\tcursor.close()\r\n\tcnx.close()\r\n\r\ndef log_count():\r\n\tcnx = mysql.connector.connect(**mysql_config)\r\n\tcursor = cnx.cursor(buffered=True)\r\n\tquery = \"SELECT COUNT(*) count FROM cron_history\"\r\n\tcursor.execute(query)\r\n\tlog = cursor.fetchone()\r\n\tcursor.close()\r\n\tcnx.close()\r\n\treturn(log)\r\n\r\ndef set_claim_status(status, captchas):\r\n\tcnx = mysql.connector.connect(**mysql_config)\r\n\tcursor = cnx.cursor()\r\n\r\n\tformat_strings = ','.join(['%s'] * len(captchas))\r\n\tcursor.execute(\"UPDATE pending_claims SET claimStatus = '\" + status + \"' WHERE claimCaptcha IN (%s)\" % format_strings, tuple(captchas))\r\n\tcnx.commit()\r\n\tcursor.close()\r\n\tcnx.close()\r\n\r\ndef collect_pending_claims():\r\n\tcnx = mysql.connector.connect(**mysql_config)\r\n\tcursor = cnx.cursor(buffered=True)\r\n\tquery = \"SELECT * FROM pending_claims WHERE claimStatus = 'p' ORDER BY claimTime\"\r\n\tcursor.execute(query)\r\n\tpending_claims = cursor.fetchall()\r\n\tcursor.close()\r\n\tcnx.close()\r\n\treturn(pending_claims)\r\n\r\ndef elaborate(captchas, retry):\r\n\tglobal attempt\r\n\turl = 'https://faucet.raiblockscommunity.net/elaborate.php' # Set destination URL here\r\n\r\n\ttry:\r\n\t\tprint(\"Trying to elaborate, attemp #{}\".format(retry+1))\r\n\r\n\t\tattempt += 1\r\n\t\tdata = {}\r\n\t\tdata['ask_address'] = xrb_address\r\n\t\tdata['donate'] = 1\r\n\t\tdata['accepted'] = 1\r\n\t\tdata['captchas'] = json.dumps(captchas)\r\n\r\n\t\trequest = Request(url, urlencode(data).encode())\r\n\t\tret = urlopen(request).read().decode()\r\n\t\t\r\n\t\treturn json.loads(str(ret))\r\n\texcept HTTPError as e:\r\n\t\tif retry < 3:\r\n\t\t\tretry += 1\r\n\t\t\telaborate(captchas, retry)\r\n\r\ndef main():\r\n\tstart_time = time()\r\n\tprint(\"[INFO] Starting at {}\".format(datetime.utcnow()))\r\n\r\n\tarrCaptcha = []\r\n\tarrClaimId = []\r\n\tarrValid = []\r\n\tarrValidId = []\r\n\r\n\tprint(\"[INFO] Collecting pending claims\")\r\n\tcaptchas = collect_pending_claims()\r\n\tfor captcha in captchas:\r\n\t\tarrCaptcha.append(captcha[2])\r\n\t\tarrClaimId.append(captcha[0])\r\n\r\n\tif len(arrCaptcha) > 0:\r\n\t\tprint(\"[INFO] Attempting to elaborate {:,} claims\".format(len(arrCaptcha)))\r\n\t\tret = elaborate(arrCaptcha, 0)\r\n\t\tif ret is not None:\r\n\t\t\terror = ret[\"error\"]\r\n\r\n\t\t\tif error == \"no\":\r\n\t\t\t\tprint(\"[INFO] Checking valid claims\")\r\n\t\t\t\tfor valid in ret[\"valid_captchas\"]:\r\n\t\t\t\t\tarrValid.append(arrCaptcha[int(valid)])\r\n\t\t\t\t\tarrValidId.append(arrClaimId[int(valid)])\r\n\r\n\t\t\t\t\tarrCaptcha[int(valid)] = ''\r\n\r\n\t\t\t\tprint(\"[INFO] Storing valid claims\")\r\n\t\t\t\tset_claim_status(\"d\", arrValid)\r\n\r\n\t\t\t\tprint(\"[INFO] Storing invalid claims\")\r\n\t\t\t\tset_claim_status(\"i\", arrCaptcha)\r\n\t\t\telse:\r\n\t\t\t\tprint(\"[ERROR] Error while elaborating '{}'\".format(error))\r\n\t\t\t\tif error == \"Invalid claims.\":\r\n\t\t\t\t\tprint(\"[INFO] Storing invalid claims\")\r\n\t\t\t\t\tset_claim_status(\"i\", arrCaptcha)\r\n\t\t\t\telif error == \"Faucet maintenance.\":\r\n\t\t\t\t\tset_claim_status(\"i\", arrCaptcha)\r\n\r\n\t\t\tcronContent = {\r\n\t\t\t\t\"claimsSent\": json.dumps(arrClaimId),\r\n\t\t\t\t\"serverError\": error,\r\n\t\t\t\t\"serverValidClaims\": json.dumps(arrValidId),\r\n\t\t\t\t\"validationAttemps\": attempt\r\n\t\t\t}\r\n\r\n\t\t\tif log_count()[0] > 1000:\r\n\t\t\t\tprint(\"[INFO] Clearing log\")\r\n\t\t\t\tlog_clear()\r\n\r\n\t\t\tprint(\"[INFO] Inserting log\")\r\n\t\t\tdata = {\r\n\t\t\t\t\"duration\": \"{:.3f} ms\".format(time() - start_time),\r\n\t\t\t\t\"time\": \"{:%Y-%m-%d %H:%M:%S}\".format(datetime.utcnow()),\r\n\t\t\t\t\"content\": json.dumps(cronContent)\r\n\t\t\t}\r\n\t\t\tlog_insert(data)\r\n\telse:\r\n\t\tprint(\"[INFO] No pending claims\")\r\n\r\n\tprint(\"[INFO] Finishing at {}\".format(datetime.utcnow()))\r\n\tprint(\"\")\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.5767335891723633, "alphanum_fraction": 0.5987116098403931, "avg_line_length": 40.88888931274414, "blob_id": "6154738a6e61f0db834068539dc8ed89281b2302", "content_id": "05a067091fc9568bea9237d865e215f57b62dffb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2639, "license_type": "permissive", "max_line_length": 157, "num_lines": 63, "path": "/pool/application/views/pages/payout.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\n$account = $this->model->isAccountExist($this->session->userdata('xrb_address')['address']);\nif($account->accountName != \"AuliaYF\")\n\tredirect('index');\n?>\n<div class=\"container-fluid\">\n\t<div class=\"col-md-12\">\n\t\t<?php\n\t\t$arrDistribution = NULL;\n\t\twhile(!$arrDistribution){\n\t\t\t$json = file_get_contents('https://raiblockscommunity.net/faucet/distribution.php?json=1');\n\t\t\t$arrDistribution = json_decode($json, TRUE);\n\t\t}\n\n\t\t$dbDistribution = $this->db->get('distribution_history')->row();\n\t\t$disStart = $arrDistribution[0]['time_start'];\n\t\t// $disStart = 1491868800;\n\t\t$disMrai = $arrDistribution[0]['reward'] / 1000000;\n\t\tif($dbDistribution->distributionCurrent != $disStart){\n\t\t\t$paylist = $this->model->populatePaylist(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 1 * 3600), date(\"Y-m-d H:i:s\", $disStart + 1 * 3600));\n\t\t\t$poolClaim = $this->model->countClaims(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 1 * 3600), date(\"Y-m-d H:i:s\", $disStart + 1 * 3600));\n\n\t\t\tforeach ($paylist as $row) {\n\t\t\t\tif($row->totalClaim > 0){\n\t\t\t\t\t$memberMrai = $row->totalClaim / $poolClaim * ($poolClaim * $disMrai);\n\t\t\t\t\tif($memberMrai >= 100){\n\t\t\t\t\t\t$payoutMrai = $memberMrai - ((1 / 100) * $memberMrai);\n\t\t\t\t\t\t$this->db->insert('payout_history', array(\n\t\t\t\t\t\t\t'accountId' => $row->accountId,\n\t\t\t\t\t\t\t'payoutQty' => number_format($payoutMrai, 0, '.', ''),\n\t\t\t\t\t\t\t'payoutTime' => date(\"Y-m-d H:i:s\"),\n\t\t\t\t\t\t\t'payoutStatus' => 'p'\n\t\t\t\t\t\t));\n\t\t\t\t\t\tif($row->accountBalance > 0){\n\t\t\t\t\t\t\t$this->db->where('accountId', $row->accountId)->update('app_account', array(\n\t\t\t\t\t\t\t\t'accountBalance' => $row->accountBalance - number_format($memberMrai, 0, '.', '')\n\t\t\t\t\t\t\t));\n\t\t\t\t\t\t}\n\t\t\t\t\t\techo \"payout to: \" . $row->accountAddress . ' ' . number_format($payoutMrai, 0, '.', '') . \" mrai <br>\";\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$this->db->where('accountId', $row->accountId)->update('app_account', array(\n\t\t\t\t\t\t\t'accountBalance' => $row->accountBalance + number_format($memberMrai, 0, '.', '')\n\t\t\t\t\t\t));\n\t\t\t\t\t\techo \"updating balance to: \" . $row->accountAddress . ' ' . number_format($memberMrai, 0, '.', '') . \" mrai <br>\";\n\t\t\t\t\t}\n\t\t\t\t\t$this->db->insert('app_account_claim', array(\n\t\t\t\t\t\t'accountId' => $row->accountId,\n\t\t\t\t\t\t'claimQty' => $row->totalClaim,\n\t\t\t\t\t\t'claimMrai' => number_format($memberMrai, '0', '.', ''),\n\t\t\t\t\t\t'createdTime' => date(\"Y-m-d H:i:s\")\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->db->where('distributionId', 1)->update('distribution_history', array(\n\t\t\t\t'distributionPrevious' => $dbDistribution->distributionCurrent,\n\t\t\t\t'distributionCurrent' => $disStart\n\t\t\t));\n\t\t}else{\n\t\t\techo 'distribution already done.';\n\t\t}\n\t\t?>\n\t</div>\n</div>\n" }, { "alpha_fraction": 0.6414141654968262, "alphanum_fraction": 0.6414141654968262, "avg_line_length": 17.904762268066406, "blob_id": "d37da086681b1a17de334c0eb8346342a2cede5e", "content_id": "bfdf32e5810313cc4f9e613792a51a797bd0c253", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 396, "license_type": "permissive", "max_line_length": 63, "num_lines": 21, "path": "/pool/application/controllers/Logs.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\nclass Logs extends MY_Controller {\n\n\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n \t$this->load->model('accountmodel', 'model');\n\t}\n\n\tpublic function index()\n\t{\n\t\t$data['active'] = 'logs';\n\t\t$this->view('pages/logs', $data);\n\t}\n\n}\n\n/* End of file Logs.php */\n/* Location: ./application/controllers/Logs.php */" }, { "alpha_fraction": 0.5474944114685059, "alphanum_fraction": 0.5684368014335632, "avg_line_length": 28.43181800842285, "blob_id": "655f0648c1b6be38d9ac15d989e78a194b179edd", "content_id": "4fe3b6a30872f3b94799ac5bb3bef3014fa2cb29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 170, "num_lines": 44, "path": "/pool/application/controllers/Paylist.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Paylist extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t\tif(NULL === $this->session->userdata('xrb_address'))\r\n\t\t\tredirect('login');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t$this->output->cache(5);\r\n\t\t$data['active'] = 'paylist';\r\n\t\t$this->view('pages/paylist', $data);\r\n\t\t// echo 'Maintenance';\r\n\t}\r\n\r\n\tpublic function test(){\r\n\t\t// $dbDistribution = $this->db->get('distribution_history')->row();\r\n\t\t// $arr = $this->model->populatePaylist(date(\"Y-m-d H:i:s\", $dbDistribution->distributionCurrent + 3600), date(\"Y-m-d H:i:s\", time() + 3600));\r\n\t\t// foreach ($arr as $row) {\r\n\t\t// \tif($row->totalClaim > 0){\r\n\t\t// \t\techo $row->accountName . \", \";\r\n\t\t// \t\t$totalClaim = 0;\r\n\t\t// \t\tfor ($i = 0; $i < 60; $i++) {\r\n\t\t// \t\t\t$totalClaim++;\r\n\t\t// \t\t\t$this->db->insert('pending_claims', array('accountId' => $row->accountId, 'claimCaptcha' => 'bonus', 'claimTime' => '2017-04-20 07:10:12', 'claimStatus' => 'd'));\r\n\t\t// \t\t}\r\n\r\n\t\t// \t\techo $totalClaim . '<br>';\r\n\t\t// \t}\r\n\t\t// }\r\n\r\n\t\t// $this->db->where('claimStatus', 'i')->update('pending_claims', array('claimStatus' => 'd'));\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Paylist.php */\r\n/* Location: ./application/controllers/Paylist.php */" }, { "alpha_fraction": 0.6488651633262634, "alphanum_fraction": 0.6568758487701416, "avg_line_length": 44.9375, "blob_id": "30f978e616266d12c22320658c0b0e69b52c6c0f", "content_id": "d627e1dca67091a7000e7c3349a172812861f1c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 749, "license_type": "permissive", "max_line_length": 144, "num_lines": 16, "path": "/pool/application/views/pages/password.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<div class=\"container-fluid\">\r\n\t<div class=\"col-md-6 col-md-offset-3\">\r\n\t\t<form action=\"<?php echo base_url('login') ?>\" method=\"POST\">\r\n\t\t\t<legend>Login</legend>\r\n\t\t\t<div class=\"form-group\">\r\n\t\t\t\t<label for=\"inputAddress\">XRB address</label>\r\n\t\t\t\t<input type=\"text\" class=\"form-control\" id=\"inputAddress\" placeholder=\"Your XRB Address\" name=\"inputAddress\" value=\"<?php echo $address ?>\">\r\n\t\t\t</div>\r\n\t\t\t<div class=\"form-group\">\r\n\t\t\t\t<label for=\"inputPassword\">Password</label>\r\n\t\t\t\t<input type=\"password\" class=\"form-control\" id=\"inputPassword\" placeholder=\"Admin Password\" name=\"inputPassword\">\r\n\t\t\t</div>\r\n\t\t\t<button type=\"submit\" name=\"submit\" value=\"register\" class=\"btn btn-primary col-md-12 col-xs-12\">Login</button>\r\n\t\t</form>\r\n\t</div>\r\n</div>" }, { "alpha_fraction": 0.5679333806037903, "alphanum_fraction": 0.5700156092643738, "avg_line_length": 27.58461570739746, "blob_id": "e058785c112d26182fd3eee9249f14b84fef1435", "content_id": "d3e1ebdcc5edefa40b2e31c47de05593f34bed66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1921, "license_type": "permissive", "max_line_length": 106, "num_lines": 65, "path": "/pool/application/controllers/Login.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\ndefined('BASEPATH') OR exit('No direct script access allowed');\r\n\r\nclass Login extends MY_Controller {\r\n\r\n\tpublic function __construct()\r\n\t{\r\n\t\tparent::__construct();\r\n\t\t$this->load->model('accountmodel', 'model');\r\n\t}\r\n\r\n\tpublic function index()\r\n\t{\r\n\t\t$content = 'pages/login';\r\n\t\t$data['active'] = 'login';\r\n\r\n\t\tif(NULL != $this->input->post('submit')){\r\n\t\t\t$continue = TRUE;\r\n\t\t\tif(strpos($this->input->post('inputAddress'), 'RaiWalletBot: ') !== false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(strpos($this->input->post('inputAddress'), 'xrb_') === false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(!filter_var($this->input->post('inputAddress'), FILTER_VALIDATE_EMAIL) === false){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\t\t\tif(strlen($this->input->post('inputAddress')) < 64 || strlen($this->input->post('inputAddress')) > 64){\r\n\t\t\t\t$continue = FALSE;\r\n\t\t\t}\r\n\r\n\t\t\tif($continue){\r\n\t\t\t\t$account = $this->model->isAccountExist(trim($this->input->post('inputAddress')));\r\n\t\t\t\tif(NULL == $account){\r\n\t\t\t\t\t$data['address'] = $this->input->post('inputAddress');\r\n\t\t\t\t\t$content = 'pages/register';\r\n\t\t\t\t}else{\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(isAdmin(trim($this->input->post('inputAddress')))){\r\n\t\t\t\t\t\tif(trim($this->input->post('inputPassword')) != 'p0ol4dmin'){\r\n\t\t\t\t\t\t\t$data['address'] = trim($this->input->post('inputAddress'));\r\n\t\t\t\t\t\t\t$content = 'pages/password';\r\n\t\t\t\t\t\t\t$this->view($content, $data);\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif($account->accountStatus == 't'){\r\n\t\t\t\t\t\t$sess['xrb_address'] = array('address' => trim($this->input->post('inputAddress')));\r\n\t\t\t\t\t\t$this->session->set_userdata($sess);\r\n\t\t\t\t\t\tredirect('index');\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tredirect('login?error=' . urlencode(\"Account Suspended.\"));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\tredirect('login?error=' . urlencode(\"Invalid Address\"));\r\n\t\t\t}\r\n\t\t}\r\n\t\t$this->view($content, $data);\r\n\t}\r\n\r\n}\r\n\r\n/* End of file Login.php */\r\n/* Location: ./application/controllers/Login.php */" }, { "alpha_fraction": 0.6751628518104553, "alphanum_fraction": 0.6873406767845154, "avg_line_length": 32.21002960205078, "blob_id": "4a4d1095df6b87b97c464de25b9e062425215bf6", "content_id": "2ee5237eb5797a469b683fd93c9a3d110c1740e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10593, "license_type": "permissive", "max_line_length": 214, "num_lines": 319, "path": "/XbitzPoolBot/bot.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import logging\nimport requests\nfrom db import *\nfrom lang import *\nfrom common import *\nfrom functools import wraps\nfrom datetime import (datetime, timedelta)\nfrom telegram.ext import Updater, CommandHandler, Job\nfrom telegram import (ReplyKeyboardMarkup, ChatAction, ParseMode)\nfrom telegram.error import (TelegramError, Unauthorized, BadRequest, TimedOut, ChatMigrated, NetworkError)\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO, filename=\"bot.log\")\nlogger = logging.getLogger(__name__)\n\nTOKEN = \"\";\n\n# Specify bot admins\nLIST_OF_ADMINS = []\nxrb_address = 'xrb_1bawnqs6cc9a91ziwoy7fgmdycyjk9r6dt7eerfgzdbysrfnbihfxzobt8c8'\n\nlastDistribution = db_last_distribution()[0]\n\ndef typing_illusion(bot, chat_id):\n\ttry:\n\t\tbot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # typing illusion\n\texcept Unauthorized:\n\t\treturn False\n\texcept BadRequest:\n\t\treturn False\n\texcept:\n\t\tsleep(0.3)\n\t\tbot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # typing illusion\n\ndef restricted(func):\n @wraps(func)\n def wrapped(bot, update, *args, **kwargs):\n # extract user_id from arbitrary update\n try:\n user_id = update.message.from_user.id\n except (NameError, AttributeError):\n try:\n user_id = update.inline_query.from_user.id\n except (NameError, AttributeError):\n try:\n user_id = update.chosen_inline_result.from_user.id\n except (NameError, AttributeError):\n try:\n user_id = update.callback_query.from_user.id\n except (NameError, AttributeError):\n print(\"No user_id available in update.\")\n return\n if user_id not in LIST_OF_ADMINS:\n print(\"Unauthorized access denied for {}.\".format(user_id))\n return\n return func(bot, update, *args, **kwargs)\n return wrapped\n\n\ndef send_msg(bot, userId, msg):\n\ttry:\n\t\tbot.sendMessage(chat_id=userId, parse_mode=ParseMode.MARKDOWN, text=msg)\n\t\treturn True\n\texcept Unauthorized:\n\t\treturn False\n\texcept BadRequest:\n\t\treturn False\n\ndef send_msg_kbrd(bot, userId, msg, markup):\n\tbot.sendMessage(chat_id=userId, parse_mode=ParseMode.MARKDOWN, text=msg, reply_markup=markup)\n\ndef notify_distribution(bot, job):\n\tglobal lastDistribution\n\n\ttempDistribution = db_last_distribution()[0]\n\n\tif tempDistribution != lastDistribution:\n\t\tdistributions = db_last_distributions(lastDistribution);\n\n\t\tfor distribution in distributions:\n\t\t\ttyping_illusion(bot, distribution[0])\n\t\t\tif send_msg(bot, distribution[0], lang(\"notify_distribution\").format(int(distribution[2]), float(distribution[3]), float(distribution[6]), float(distribution[4]))):\t\t\t\n\t\t\t\tpending_po = db_pending(distribution[1], distribution[5])\n\t\t\t\tif pending_po is None:\n\t\t\t\t\tsend_msg(bot, distribution[0], lang(\"no_pending\"))\n\t\t\t\telse:\n\t\t\t\t\tsend_msg(bot, distribution[0], lang(\"has_pending\").format(datetime.strftime(pending_po[4], \"%b %d %H:%M:%S\"), float(pending_po[3])))\n\n\t\tlastDistribution = tempDistribution\n\n@restricted\ndef notify(bot, update):\n\tglobal lastDistribution\n\n\tuserId = update.message.from_user.id\n\n\ttempDistribution = db_last_distribution()[0]\n\tdistributions = db_current_distributions(tempDistribution);\n\n\ttyping_illusion(bot, userId)\n\tsend_msg(bot, userId, lang(\"processing_broadcast\").format('Distribution Notification {}'.format(tempDistribution), len(distributions)))\n\n\tcnt = 0\n\tfor distribution in distributions:\n\t\ttyping_illusion(bot, userId)\n\t\tsend_msg(bot, userId, lang(\"sending_broadcast\").format(distribution[0]))\n\n\t\ttyping_illusion(bot, distribution[0])\n\t\tif send_msg(bot, distribution[0], lang(\"notify_distribution\").format(int(distribution[2]), float(distribution[3]), float(distribution[6]), int(distribution[4]))):\t\t\t\n\t\t\tpending_po = db_pending(distribution[1], distribution[5])\n\t\t\tif pending_po is None:\n\t\t\t\tsend_msg(bot, distribution[0], lang(\"no_pending\"))\n\t\t\telse:\n\t\t\t\tsend_msg(bot, distribution[0], lang(\"has_pending\").format(datetime.strftime(pending_po[4], \"%b %d %H:%M:%S\"), float(pending_po[3])))\n\n\t\t\tcnt += 1\n\n\ttyping_illusion(bot, userId)\n\tsend_msg(bot, userId, lang(\"done_broadcast\").format(cnt))\n\n@restricted\ndef broadcast(bot, update, args):\n\tuserId = update.message.from_user.id\n\tif not args:\n\t\ttyping_illusion(bot, userId)\n\t\tsend_msg(bot, userId, lang(\"empty_broadcast\"))\n\telse:\n\t\tmembers = db_members()\n\t\tmsg = ' '.join(args)\n\t\ttyping_illusion(bot, userId)\n\t\tsend_msg(bot, userId, lang(\"processing_broadcast\").format(msg, len(members)))\n\n\t\tcnt = 0\n\t\tfor member in members:\n\t\t\ttyping_illusion(bot, userId)\n\t\t\tsend_msg(bot, userId, lang(\"sending_broadcast\").format(member[0]))\n\t\t\tif send_msg(bot, member[0], lang(\"content_broadcast\").format(msg)):\n\t\t\t\tcnt += 1\n\n\t\ttyping_illusion(bot, userId)\n\t\tsend_msg(bot, userId, lang(\"done_broadcast\").format(cnt))\n\ndef start(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tcustom_keyboard = [[\"/stats\", \"/paylist\"], [\"/pending\", \"/paid\"], [\"/profile\", \"/help\"]]\n\t\treply_markup = ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=False, resize_keyboard = True)\n\t\tsend_msg_kbrd(bot, userId, lang(\"start_old\").format(account[2]), reply_markup)\n\t\thelp(bot, update)\n\ndef help(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tsend_msg(bot, userId, lang(\"help\"))\n\ndef register(bot, update, args):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tif not args:\n\t\t\tsend_msg(bot, userId, lang(\"empty_register\"))\n\t\telse:\n\t\t\tvalid = raiblocks_account_validate(args[0])\n\n\t\t\tif not valid:\n\t\t\t\tsend_msg(bot, userId, lang(\"invalid_register\"))\n\t\t\telse:\n\t\t\t\texist = db_account_exist(args[0])\n\t\t\t\tif exist is None:\n\t\t\t\t\tsend_msg(bot, userId, lang(\"not_found_register\"))\n\t\t\t\telse:\t\n\t\t\t\t\texist2 = db_user_exist(args[0])\n\t\t\t\t\tif exist2 is None:\n\t\t\t\t\t\tdata = {\n\t\t\t\t\t\t\t'chatId': userId,\n\t\t\t\t\t\t\t'userId': userId,\n\t\t\t\t\t\t\t'accountId': exist[0]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdb_register(data)\n\n\t\t\t\t\t\tstart(bot, update)\n\t\t\t\t\telse:\n\t\t\t\t\t\tsend_msg(bot, userId, lang(\"exist_register\"))\n\telse:\n\t\tstart(bot, update)\n\ndef profile(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tsend_msg(bot, userId, lang(\"profile\").format(account[2], account[3], int(account[4]), float(account[5])))\n\ndef pending(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tpending_po = db_pending(account[1], account[4])\n\t\tif pending_po is None:\n\t\t\tsend_msg(bot, userId, lang(\"no_pending\"))\n\t\telse:\n\t\t\tsend_msg(bot, userId, lang(\"has_pending\").format(datetime.strftime(pending_po[4], \"%b %d %H:%M:%S\"), float(pending_po[3])))\n\ndef paid(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tpaids = db_paid(account[1])\n\t\tsend_msg(bot, userId, lang(\"header_paid\").format(len(paids)))\n\n\t\tfor paid in paids:\n\t\t\tsend_msg(bot, userId, lang(\"item_paid\").format(datetime.strftime(paid[4], \"%b %d %H:%M:%S\"), float(paid[3]), paid[5]))\n\ndef stats(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\ttoday_distributions = db_today_distributions(account[1], datetime.strftime(datetime.utcnow(), \"%Y-%m-%d\"))\n\t\tif len(today_distributions) < 1:\n\t\t\tsend_msg(bot, userId, lang(\"no_today_distributions\"))\n\t\telse:\n\t\t\tsend_msg(bot, userId, lang(\"header_today_distributions\").format(len(today_distributions)))\n\n\t\t\tfor today_distribution in today_distributions:\n\t\t\t\tsend_msg(bot, userId, lang(\"item_today_distributions\").format(datetime.strftime(today_distribution[5], \"%b %d %H:%M:%S\"), int(today_distribution[2]), float(today_distribution[4]), float(today_distribution[3])))\n\ndef paylist(bot, update):\n\tuserId = update.message.from_user.id\n\ttyping_illusion(bot, userId)\n\n\taccount = db_select_user(userId)\n\n\tif account is None:\n\t\tsend_msg(bot, userId, lang(\"start_new\"))\n\telse:\n\t\tjson = requests.get(url='https://faucet.raiblockscommunity.net/paylist.php?acc={}&json=1'.format(xrb_address)).json()\n\t\tpoolClaim = int(json['pending'][0]['pending'])\n\t\tpoolMrai = int(float(json['pending'][0]['expected-pay'])) / 1000000\n\t\tthreshold = int(float(json['threshold']))\n\t\tclaimRate = json['reward'] / 1000000\n\t\ttop60 = \"Yes\"\n\t\tif poolClaim < threshold:\n\t\t\ttop60 = \"No {:,} to go\".format(threshold - poolClaim)\n\n\t\tpaylist = db_paylist(account[1])\n\t\tif paylist[0] > 0 or paylist[1] > 0 or paylist[2] > 0:\n\t\t\tif top60 == \"Yes\":\n\t\t\t\tsend_msg(bot, userId, lang(\"top60_paylist\").format(int(paylist[1]), int(paylist[2]), int(paylist[0]), float(int(paylist[1]) * claimRate)))\n\t\t\telse:\n\t\t\t\tsend_msg(bot, userId, lang(\"non_top60_paylist\").format(int(paylist[1]), int(paylist[2]), int(paylist[0])))\n\n\t\tif top60 == \"Yes\":\n\t\t\tsend_msg(bot, userId, lang(\"top60_pool_paylist\").format(poolClaim, threshold, top60, float(poolMrai), claimRate))\n\t\telse:\n\t\t\tsend_msg(bot, userId, lang(\"non_top60_pool_paylist\").format(poolClaim, threshold, top60, claimRate))\n\ndef error(bot, update, error):\n\tlogger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\ndef main():\n\tupdater = Updater(TOKEN)\n\tdp = updater.dispatcher\n\tj = updater.job_queue\n\t\n\tdp.add_handler(CommandHandler(\"start\", start))\n\tdp.add_handler(CommandHandler(\"help\", help))\n\tdp.add_handler(CommandHandler(\"register\", register, pass_args=True))\n\tdp.add_handler(CommandHandler(\"profile\", profile))\n\tdp.add_handler(CommandHandler(\"pending\", pending))\n\tdp.add_handler(CommandHandler(\"paid\", paid))\n\tdp.add_handler(CommandHandler(\"stats\", stats))\n\tdp.add_handler(CommandHandler(\"paylist\", paylist))\n\tdp.add_handler(CommandHandler(\"notify\", notify))\n\tdp.add_handler(CommandHandler(\"broadcast\", broadcast, pass_args=True))\n\n\tdp.add_error_handler(error)\n\n\tjob_minute = Job(notify_distribution, 300.0)\n\tj.put(job_minute, next_t=0.0)\n\n\tupdater.start_polling()\n\tupdater.idle()\n\nif __name__ == \"__main__\":\n\tprint(\"Starting bot server\")\n\tmain()" }, { "alpha_fraction": 0.7106557488441467, "alphanum_fraction": 0.723975419998169, "avg_line_length": 25.96685028076172, "blob_id": "a96a5e2c8e902f33844192d0e8d17ffe047a22c8", "content_id": "249d2e4fdc2089d34ea21cc2a65da399583768ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4880, "license_type": "permissive", "max_line_length": 292, "num_lines": 181, "path": "/XbitzPoolBot/db.py", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "import time\nimport mysql.connector\nfrom datetime import datetime\n\nmysql_config = {\n \"user\": \"root\",\n \"password\": \"\",\n \"host\": \"127.0.0.1\",\n \"database\": \"app_pool\",\n \"raise_on_warnings\": True,\n \"use_unicode\": True,\n \"charset\": \"utf8\",\n}\n\ndef db_register(data):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor()\n\t\n\tadd_user = (\"INSERT INTO pool_bot \"\n\t\t\t \"(userId, accountId, chatId) \"\n\t\t\t \"VALUES (%(userId)s, %(accountId)s, %(chatId)s)\")\n\t\n\tcursor.execute(add_user, data)\n\tcnx.commit()\n\t\n\tcursor.close()\n\tcnx.close()\n\ndef db_select_user(userId):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT t1.userId, t2.accountId, t2.accountName, t2.accountAddress, t2.accountThreshold, t2.accountBalance FROM pool_bot t1 JOIN app_account t2 ON t2.accountId = t1.accountId WHERE t1.userId = {0}\".format(userId)\n\t\n\tcursor.execute(query)\n\taccount = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(account)\n\ndef db_account_exist(accountAddress):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT accountId FROM app_account WHERE accountAddress = '{}'\".format(accountAddress)\n\t\n\tcursor.execute(query)\n\taccount = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(account)\n\ndef db_user_exist(accountAddress):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT t1.userId FROM pool_bot t1 JOIN app_account t2 ON t2.accountId = t1.accountId WHERE t2.accountAddress = '{}'\".format(accountAddress)\n\t\n\tcursor.execute(query)\n\taccount = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(account)\n\ndef db_pending(accountId, accountThreshold):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT * FROM payout_history WHERE payoutStatus = 'p' AND accountId = '{}' AND payoutQty > {}\".format(accountId, int(accountThreshold))\n\t\n\tcursor.execute(query)\n\tpending = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(pending)\n\ndef db_paid(accountId):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT * FROM payout_history WHERE payoutStatus = 'c' AND accountId = '{}' ORDER BY payoutTime DESC LIMIT 5\".format(accountId)\n\t\n\tcursor.execute(query)\n\tpaid = cursor.fetchall()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(paid)\n\ndef db_today_distributions(accountId, date):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT * FROM app_account_claim WHERE accountId = '{}' AND DATE(createdTime) = '{}' ORDER BY createdTime DESC\".format(accountId, date)\n\t\n\tcursor.execute(query)\n\tdistributions = cursor.fetchall()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(distributions)\n\ndef db_paylist(accountId):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT COALESCE(SUM(t1.claimStatus = 'p'), 0) pending, COALESCE(SUM(t1.claimStatus = 'd'), 0) valid, COALESCE(SUM(t1.claimStatus = 'i'), 0) invalid FROM pending_claims t1 WHERE t1.accountId = {}\".format(accountId)\n\t\n\tcursor.execute(query)\n\tpaylist = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(paylist)\n\ndef db_last_distribution():\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT createdTime FROM app_account_claim ORDER BY createdTime DESC LIMIT 1\"\n\t\n\tcursor.execute(query)\n\tlast_distribution = cursor.fetchone()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(last_distribution)\n\ndef db_last_distributions(datetime):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT t2.chatId, t2.accountId, t1.claimQty, t1.claimMrai, t3.accountBalance, t3.accountThreshold, t1.claimRate FROM app_account_claim t1 JOIN pool_bot t2 ON t2.accountId = t1.accountId JOIN app_account t3 ON t3.accountId = t1.accountId WHERE t1.createdTime > '{}'\".format(datetime)\n\t\n\tcursor.execute(query)\n\tlast_distributions = cursor.fetchall()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(last_distributions)\n\ndef db_current_distributions(datetime):\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT t2.chatId, t2.accountId, t1.claimQty, t1.claimMrai, t3.accountBalance, t3.accountThreshold, t1.claimRate FROM app_account_claim t1 JOIN pool_bot t2 ON t2.accountId = t1.accountId JOIN app_account t3 ON t3.accountId = t1.accountId WHERE t1.createdTime = '{}'\".format(datetime)\n\t\n\tcursor.execute(query)\n\tlast_distributions = cursor.fetchall()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(last_distributions)\n\ndef db_members():\n\tcnx = mysql.connector.connect(**mysql_config)\n\tcursor = cnx.cursor(buffered=True)\n\n\tquery = \"SELECT chatId FROM pool_bot\"\n\t\n\tcursor.execute(query)\n\tmembers = cursor.fetchall()\n\t\n\tcursor.close()\n\tcnx.close()\n\n\treturn(members)" }, { "alpha_fraction": 0.6834090352058411, "alphanum_fraction": 0.6922255158424377, "avg_line_length": 55.727272033691406, "blob_id": "701ac8caabe4b4712d5de558244dbd26a7914ddd", "content_id": "0d47fdeff9c75ed4be7bf4ba9d7f51970b7f376c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3743, "license_type": "permissive", "max_line_length": 431, "num_lines": 66, "path": "/pool/application/models/Accountmodel.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\nclass AccountModel extends CI_Model {\n\n\tprivate $tableName = \"app_account\";\n\tpublic function __construct()\n\t{\n\t\tparent::__construct();\n\t}\n\n\tpublic function getPoolStat($timeStart, $timeEnd){\n\t\treturn $this->db->query(\"SELECT (SELECT COUNT(*) FROM (SELECT * FROM app_account_claim WHERE createdTime BETWEEN '$timeStart' AND '$timeEnd' GROUP BY accountId) x1) activeWorker, (SELECT SUM(x1.claimQty) FROM app_account_claim x1 WHERE x1.createdTime BETWEEN '$timeStart' AND '$timeEnd') totalClaim, (SELECT SUM(x1.claimMrai) FROM app_account_claim x1 WHERE x1.createdTime BETWEEN '$timeStart' AND '$timeEnd') totalMrai\")->row();\n\t}\n\n\tpublic function populatePaylist($timeStart = NULL, $timeEnd = NULL){\n\t\tif(NULL == $timeStart && NULL == $timeEnd)\n\t\t\treturn $this->db->query(\"SELECT t1.accountId, t1.accountName, t1.accountAddress, t1.accountThreshold, t1.accountBalance, (SELECT COUNT(*) FROM pending_claims x1 WHERE x1.accountId = t1.accountId AND DATE(x1.claimTime) = '\" . date(\"Y-m-d\") . \"') totalClaim FROM app_account t1 ORDER BY 1\")->result();\n\t\telse\n\t\t\treturn $this->db->query(\"SELECT t1.accountId, t1.accountName, t1.accountAddress, t1.accountThreshold, t1.accountBalance, (SELECT COUNT(*) FROM pending_claims x1 WHERE x1.accountId = t1.accountId AND x1.claimTime BETWEEN '$timeStart' AND '$timeEnd' AND x1.claimStatus = 'd') totalClaim FROM app_account t1 ORDER BY 6 DESC\")->result();\n\t}\n\n\tpublic function countMember($timeStart = NULL, $timeEnd = NULL){\n\t\tif(NULL === $timeStart && NULL === $timeEnd)\n\t\t\treturn $this->db->query(\"SELECT accountId FROM pending_claims WHERE DATE(claimTime) = '\" . date(\"Y-m-d\") . \"' GROUP BY accountId\")->result();\n\t\telse\n\t\t\treturn $this->db->query(\"SELECT accountId FROM pending_claims WHERE claimTime BETWEEN '$timeStart' AND '$timeEnd' AND claimStatus = 'd' GROUP BY accountId\")->result();\n\t}\n\n\tpublic function countClaims($timeStart = NULL, $timeEnd = NULL){\n\t\tif(NULL === $timeStart && NULL === $timeEnd)\n\t\t\treturn $this->db->query(\"SELECT COUNT(*) total FROM pending_claims WHERE DATE(claimTime) = '\" . date(\"Y-m-d\") . \"'\")->row()->total;\n\t\telse\n\t\t\treturn $this->db->query(\"SELECT COUNT(*) total FROM pending_claims WHERE claimTime BETWEEN '$timeStart' AND '$timeEnd' AND claimStatus = 'd'\")->row()->total;\n\t}\n\n\tpublic function isUsernameExist($username){\n\t\treturn $this->db->where('accountName', $username)->get($this->tableName)->row();\n\t}\n\n\tpublic function isAccountExist($address){\n\t\treturn $this->db->where('accountAddress', $address)->get($this->tableName)->row();\n\t}\n\n\tpublic function registerAccount($address, $fullname){\n\t\treturn $this->db->insert($this->tableName, array('accountName' => $fullname, 'accountAddress' => $address, 'accountThreshold' => 50, 'accountStatus' => 't', 'createdTime' => date(\"Y-m-d H:i:s\")));\n\t}\n\n\tpublic function storeClaim($address, $claimQty){\n\t\t$res = $this->isAccountExist($address);\n\t\tif($claimQty > 0){\n\t\t\t$this->db->insert('claims_history', array('accountId' => $res->accountId, 'claimQty' => $claimQty, 'claimTime' => date(\"Y-m-d H:i:s\")));\n\t\t}\n\t}\n\n\tpublic function getTotalClaim($address, $timeStart = NULL, $timeEnd = NULL){\n\t\t$res = $this->isAccountExist($address);\n\t\tif(NULL === $timeStart && NULL === $timeEnd)\n\t\t\treturn $this->db->query(\"SELECT COUNT(*) total FROM pending_claims WHERE accountId = '{$res->accountId}' AND DATE(claimTime) = '\" . date(\"Y-m-d\") . \"'\")->row()->total;\n\t\telse\n\t\t\treturn $this->db->query(\"SELECT COUNT(*) total FROM pending_claims WHERE accountId = '{$res->accountId}' AND claimTime BETWEEN '$timeStart' AND '$timeEnd' AND claimStatus = 'd'\")->row()->total;\n\t}\n}\n\n/* End of file Accountmodel.php */\n/* Location: ./application/models/Accountmodel.php */" }, { "alpha_fraction": 0.5173617601394653, "alphanum_fraction": 0.536954402923584, "avg_line_length": 31.705883026123047, "blob_id": "1555f931227f710b9252a188378403405631665d", "content_id": "c7841fb68aca04f6f4420b5bf93b55d8f88889a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5155, "license_type": "permissive", "max_line_length": 346, "num_lines": 153, "path": "/pool/application/views/pages/payouts.php", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "<?php\r\n$timeStart = date(\"Y-m-d H:i:s\", ((time() + 1 * 3600) - (24 * 3600)));\r\n$timeEnd = date(\"Y-m-d H:i:s\", time() + 1 * 3600);\r\n$poolStat = $this->model->getPoolStat($timeStart, $timeEnd);\r\n?>\r\n<div class=\"container-fluid\">\r\n\t<div class=\"col-md-12\">\r\n\t\t<div class=\"page-header\">\r\n\t\t\t<h1>\r\n\t\t\t\tPool Statistics <small>Last <b>24h</b></small>\r\n\t\t\t</h1>\r\n\t\t</div>\r\n\t\t<div class=\"row\">\r\n\t\t\t<div class=\"col-md-offset-3 col-md-6\">\r\n\t\t\t\t<table class=\"table\">\r\n\t\t\t\t\t<thead>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th class=\"text-center\">Active Workers</th>\r\n\t\t\t\t\t\t\t<th class=\"text-center\">Total Claims</th>\r\n\t\t\t\t\t\t\t<th class=\"text-center\">Total Mrai</small></th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</thead>\r\n\t\t\t\t\t<tbody style=\"font-size: 18px;\">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td class=\"text-center\">\r\n\t\t\t\t\t\t\t\t<?php echo number_format($poolStat->activeWorker, 0, '.', ','); ?>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td class=\"text-center\">\r\n\t\t\t\t\t\t\t\t<?php echo number_format($poolStat->totalClaim, 0, '.', ','); ?>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td class=\"text-center\">\r\n\t\t\t\t\t\t\t\t<?php echo number_format($poolStat->totalMrai, 6, '.', ','); ?>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</tbody>\r\n\t\t\t\t</table>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n<div class=\"container-fluid\">\r\n\t<div class=\"col-md-12\">\r\n\t\t<div class=\"alert alert-info\" role=\"alert\">\r\n\t\t\t<p><b>Please note</b> that all payouts are being done manually due to no running node yet.</p>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n<div class=\"container-fluid\">\r\n\t<div class=\"col-md-6\">\r\n\t\t<div class=\"page-header\">\r\n\t\t\t<h1>Pending <small>Last <b>24h</b></small></h1>\r\n\t\t</div>\r\n\t\t<table class=\"table\">\r\n\t\t\t<thead>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th width=\"80\" class=\"text-right\">#</th>\r\n\t\t\t\t\t<th>Account</th>\r\n\t\t\t\t\t<th width=\"220\" class=\"text-center\">Datetime</th>\r\n\t\t\t\t\t<th width=\"220\" class=\"text-right\">Mrai</th>\r\n\t\t\t\t</tr>\r\n\t\t\t</thead>\r\n\t\t\t<tbody>\r\n\t\t\t\t<?php\r\n\t\t\t\t$totalMrai = 0;\r\n\t\t\t\t$no = 0;\r\n\t\t\t\t$res = $this->db->select('t2.accountName, t2.accountAddress, t2.accountThreshold, t1.payoutId, t1.payoutQty, t1.payoutTime')->join('app_account t2', 't2.accountId = t1.accountId')->where('t1.payoutStatus', 'p')->where(\"t1.payoutTime BETWEEN '$timeStart' AND '$timeEnd'\")->order_by('t1.payoutTime', 'DESC')->get('payout_history t1')->result();\r\n\t\t\t\tforeach($res as $row){\r\n\t\t\t\t\t$no++;\r\n\t\t\t\t\t$totalMrai += $row->payoutQty;\r\n\t\t\t\t\t?>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\r\n\t\t\t\t\t\t<td><a href=\"https://raiblockscommunity.net/account/index.php?acc=<?php echo $row->accountAddress ?>\" target=\"_blank\"><?php echo $row->accountName ?></a></td>\r\n\t\t\t\t\t\t<td class=\"text-center\"><?php echo date(\"M d H:i:s\", strtotime($row->payoutTime)) ?></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->payoutQty, 6, '.', ',') ?> Mrai</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<?php\r\n\t\t\t\t}\r\n\t\t\t\tif($no == 0){\r\n\t\t\t\t\t?>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td colspan=\"4\" class=\"text-center\">No Data Available</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<?php\r\n\t\t\t\t}\r\n\t\t\t\t?>\r\n\t\t\t</tbody>\r\n\t\t\t<tfoot>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan=\"3\">&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class=\"info\">\r\n\t\t\t\t\t<td colspan=\"3\" class=\"text-right\">Total</td>\r\n\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalMrai, 6, '.', ',') ?> Mrai</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</tfoot>\r\n\t\t</table>\r\n\t</div>\r\n\t<div class=\"col-md-6\">\r\n\t\t<div class=\"page-header\">\r\n\t\t\t<h1>Paid <small>Last <b>24h</b></small></h1>\r\n\t\t</div>\r\n\t\t<table class=\"table\">\r\n\t\t\t<thead>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th width=\"80\" class=\"text-right\">#</th>\r\n\t\t\t\t\t<th>Account</th>\r\n\t\t\t\t\t<th>Hash</th>\r\n\t\t\t\t\t<th width=\"220\" class=\"text-center\">Datetime</th>\r\n\t\t\t\t\t<th width=\"150\" class=\"text-right\">Mrai</th>\r\n\t\t\t\t</tr>\r\n\t\t\t</thead>\r\n\t\t\t<tbody>\r\n\t\t\t\t<?php\r\n\t\t\t\t$totalMrai = 0;\r\n\t\t\t\t$no = 0;\r\n\t\t\t\t$res = $this->db->select('t2.accountName, t2.accountAddress, t1.payoutId, t1.payoutHash, t1.payoutQty, t1.payoutTime')->join('app_account t2', 't2.accountId = t1.accountId')->where('t1.payoutStatus', 'c')->where(\"t1.payoutTime BETWEEN '$timeStart' AND '$timeEnd'\")->order_by('t1.payoutTime', 'DESC')->get('payout_history t1')->result();\r\n\t\t\t\tforeach($res as $row){\r\n\t\t\t\t\t$no++;\r\n\t\t\t\t\t$totalMrai += $row->payoutQty;\r\n\t\t\t\t\t?>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo $no ?>.</td>\r\n\t\t\t\t\t\t<td><a href=\"https://raiblockscommunity.net/account/index.php?acc=<?php echo $row->accountAddress ?>\" target=\"_blank\"><?php echo $row->accountName ?></a></td>\r\n\t\t\t\t\t\t<td><a href=\"https://raiblockscommunity.net/block/index.php?h=<?php echo $row->payoutHash ?>\" target=\"_blank\"><?php echo truncate($row->payoutHash, 20) ?></a></td>\r\n\t\t\t\t\t\t<td class=\"text-center\"><?php echo date(\"M d H:i:s\", strtotime($row->payoutTime)) ?></td>\r\n\t\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($row->payoutQty, 6, '.', ',') ?> Mrai</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<?php\r\n\t\t\t\t}\r\n\t\t\t\tif($no == 0){\r\n\t\t\t\t\t?>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td colspan=\"5\" class=\"text-center\">No Data Available</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<?php\r\n\t\t\t\t}\r\n\t\t\t\t?>\r\n\t\t\t</tbody>\r\n\t\t\t<tfoot>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan=\"4\">&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class=\"info\">\r\n\t\t\t\t\t<td colspan=\"4\" class=\"text-right\">Total</td>\r\n\t\t\t\t\t<td class=\"text-right\"><?php echo number_format($totalMrai, 6, '.', ',') ?> Mrai</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</tfoot>\r\n\t\t</table>\r\n\t</div>\r\n</div>" }, { "alpha_fraction": 0.5715384483337402, "alphanum_fraction": 0.5876923203468323, "avg_line_length": 27.786258697509766, "blob_id": "243183af3267640e9b8666a494400a6f8e3e1d9b", "content_id": "da79fc012fcbc6ae7cb7f9cb5aafae41c66f08e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3900, "license_type": "permissive", "max_line_length": 156, "num_lines": 131, "path": "/pool/assets/js/faucet.js", "repo_name": "AuliaYF/XbitzPool", "src_encoding": "UTF-8", "text": "var cuclaims = 0; var prclaims = 0; var validclaims = 0;\r\nvar captchas = [];\r\nvar interval = 10;\r\nvar currTimer = interval;\r\nvar state = true;\r\nNumber.prototype.formatMoney = function(c, d, t){\r\n\tvar n = this, \r\n\tc = isNaN(c = Math.abs(c)) ? 2 : c, \r\n\td = d == undefined ? \".\" : d, \r\n\tt = t == undefined ? \",\" : t, \r\n\ts = n < 0 ? \"-\" : \"\", \r\n\ti = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), \r\n\tj = (j = i.length) > 3 ? j % 3 : 0;\r\n\treturn s + (j ? i.substr(0, j) + t : \"\") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : \"\");\r\n};\r\nfunction grabStat(){\r\n\t$.ajax({\r\n\t\ttype: \"GET\",\r\n\t\turl: \"https://faucet.raiblockscommunity.net/paylist.php\",\r\n\t\tdata: 'acc=' + xrb_address + '&json=1',\r\n\t\tdataType : \"JSON\",\r\n\t\tsuccess: function(data){\r\n\t\t\tvar poolClaim = parseFloat(data.pending[0].pending);\r\n\t\t\tvar threshold = parseFloat(data.threshold.replace('.0', ''));\r\n\t\t\tvar toGo = threshold - poolClaim;\r\n\t\t\t$(\"#displayPoolClaims\").html( poolClaim.formatMoney(0, '.', ',') );\r\n\t\t\t$(\"#displayThreshold\").html( threshold.formatMoney(0, '.', ',') );\r\n\t\t\tif(poolClaim < threshold)\r\n\t\t\t\t$(\"#displayTop60\").html('<span class=\"text-danger\">' + toGo.formatMoney(0, '.', ',') + ' to Top 60</span>');\r\n\t\t\telse\r\n\t\t\t\t$(\"#displayTop60\").html('<span class=\"text-success\">Yes <i class=\"fa fa-check\" aria-hidden=\"true\"></i></span>');\r\n\r\n\t\t\t$(\"#displayNextDistribution\").html(Math.floor(data.eta / 60) + \" <small>min</small>\");\r\n\t\t}\r\n\t});\r\n}\r\n\r\nfunction doTick(){\r\n\tif(state){\r\n\t\tcurrTimer--;\r\n\r\n\t\tif(currTimer < 0){\r\n\t\t\tonFlush();\r\n\t\t\tcurrTimer = interval;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction onClaim(token){\r\n\t$(\"#claimButton\").prop(\"disabled\",true); \r\n\r\n\tcaptchas.push( grecaptcha.getResponse() );\r\n\tcuclaims = captchas.length;\r\n\r\n\t$(\"#currentClaims\").text( cuclaims );\r\n\r\n\t$(\"#claimButton\").prop(\"disabled\",false);\r\n\r\n\t$(\"#claimButton\").trigger(\"click\");\r\n}\r\n\r\nfunction onFlush(){\r\n\tif( cuclaims > 0 ){\r\n\t\tstate = false;\r\n\t\tprclaims = cuclaims;\r\n\r\n\t\t$.ajax({\r\n\t\t\ttype: \"POST\",\r\n\t\t\turl: base_url + \"faucet/validate\",\r\n\t\t\tdataType : \"JSON\",\r\n\t\t\tdata: \"captchas=\" + JSON.stringify( captchas ),\r\n\t\t\tsuccess: function(data){\r\n\t\t\t\tcuclaims = cuclaims - prclaims;\r\n\t\t\t\tcaptchas = captchas.slice( prclaims, captchas.length );\r\n\r\n\t\t\t\tstate = true;\r\n\t\t\t\t$(\"#currentClaims\").text( cuclaims );\r\n\t\t\t\t$(\"#validationMessage\").css('display', 'none').removeClass('alert-success').addClass('alert-danger');\r\n\t\t\t\tupdateStat();\r\n\t\t\t},\r\n\t\t\terror: function(data){\r\n\t\t\t\t$(\"#validationMessage\").css('display', 'block').removeClass('alert-success').addClass('alert-danger').html(\"<b>Trouble processing claims.</b>\");\r\n\t\t\t\tstate = true;\r\n\t\t\t}\r\n\t\t});\r\n\t}else{\r\n\t\tupdateStat();\r\n\t}\r\n}\r\n\r\nfunction updateStat(){\r\n\t$.ajax({\r\n\t\ttype: \"POST\",\r\n\t\turl: base_url + \"faucet/stat\",\r\n\t\tdataType : \"JSON\",\r\n\t\tsuccess: function(data){\r\n\r\n\t\t\t$(\"#pendingClaims\").text( data.pendingClaims );\r\n\t\t\t$(\"#validatedClaims\").text ( data.validatedClaims );\r\n\r\n\t\t}\r\n\t});\r\n}\r\n\r\n$(document).ready(function(){\r\n\tgrabStat();\r\n\tsetInterval(grabStat, 60000*5);\r\n\tsetInterval(doTick, 1000);\r\n\t$(\"#claimButton\").click(function(){\r\n\t\tgrecaptcha.reset();\r\n\t});\r\n\r\n\t$(\"#nightToggle\").change(function(){\r\n\r\n\t\tvar val = $(this).is(\":checked\") ? '1' : '0';\r\n\r\n\t\tif(val == '1'){\r\n\t\t\t$(\"nav\").removeClass('navbar-default').addClass('navbar-inverse');\r\n\t\t\t$(\"#claimStat, #donateInformation, #displayPoolClaims, #displayThreshold, #displayTop60, #displayNextDistribution, thead tr th\").css(\"color\", \"#9d9d9d\");\r\n\t\t\t$(this).parent().css(\"color\", \"#9d9d9d\");\r\n\t\t\t$(\"body\").css(\"background\", \"#222\");\r\n\t\t}else{\r\n\t\t\t$(\"nav\").removeClass('navbar-inverse').addClass('navbar-default');\r\n\t\t\t$(\"#claimStat, #donateInformation, #displayPoolClaims, #displayThreshold, #displayTop60, #displayNextDistribution, thead tr th\").css(\"color\", \"#333\");\r\n\t\t\t$(this).parent().css(\"color\", \"#333\");\r\n\t\t\t$(\"body\").css(\"background\", \"#fff\");\r\n\t\t}\r\n\r\n\t});\r\n\r\n});" } ]
36
lantzmarlene/Session7and8_Exercises
https://github.com/lantzmarlene/Session7and8_Exercises
a4633cfc23b0e5ecffc96638018a6bec9e0e10bb
39901dafda913dd0c619535026576abd372a5e52
3001028393441f74dff7c0018d70b9e97f42e1b6
refs/heads/master
2020-03-30T10:58:38.995533
2018-10-01T19:36:24
2018-10-01T19:36:24
150,237,997
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6220472455024719, "alphanum_fraction": 0.6220472455024719, "avg_line_length": 20.33333396911621, "blob_id": "fb40b5e956b22ebd778649d15fd709641df0b2b3", "content_id": "a97097593f80c2255c1ac03b852e6f8278d1ac6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/FileExercise.py", "repo_name": "lantzmarlene/Session7and8_Exercises", "src_encoding": "UTF-8", "text": "fp = open(\"text.txt\", \"a\")\nprint(fp)\nline = input(\"Give me some text, don't be shy: \")\nfp.write(line)\nfp.write(\"\\n\")\nfp.close()" } ]
1
RandomDuck/logbot
https://github.com/RandomDuck/logbot
86ef5bcd5299c791e2474b7ceacba69f313b8e1c
c5ee221df1497701569eb7c8aa71791b4e740cdc
462bb755f8ab1a8c06be84e54a818437ca6dd55f
refs/heads/master
2020-04-23T10:55:03.178331
2019-02-17T12:27:18
2019-02-17T12:27:18
171,118,386
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5489662885665894, "alphanum_fraction": 0.5550870299339294, "avg_line_length": 27.83137321472168, "blob_id": "5f1d83e848ada8cd844933e5c4628695f52a5ad6", "content_id": "332baeecc7fe87f6463242d8f0f3ff811b81b614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7352, "license_type": "no_license", "max_line_length": 160, "num_lines": 255, "path": "/logbot.js", "repo_name": "RandomDuck/logbot", "src_encoding": "UTF-8", "text": "// Imports and constants\nconst jsondata = require('./data.json');\nconst Discord = require('discord.js');\nconst fs = require('fs');\nconst client = new Discord.Client();\n\n//html default template\nconst htmlbase=`<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <link rel=\"stylesheet\" href=\"logs.css\">\n <title>Log</title>\n <script>\n function hide(type){\n reset();\n x = document.getElementsByClassName(\"message\")\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"none\"\n }\n x = document.getElementsByClassName(type)\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"inline-block\"\n }\n }\n function reset(){\n x = document.getElementsByClassName(\"message\")\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"inline-block\"\n }\n }\n </script>\n </head>\n <body>\n <button onclick=\"reset()\">Reset</button>\n <div class=\"wrapper\">\n </div>\n </body>\n</html>\n`\n// return html string for attachemt based on type\nfunction handleAttachments(message){\n var atmnt=message.attachments.array()[0]\n var imgLineEnds=[\"jpg\",\"png\",\"svg\",\"gif\",\"jpeg\"]\n var vidLineEnds=[\"mp4\",\"webm\",\"ogg\",\"flac\",\"mov\"]\n var img=false\n var vid=false\n var link=''\n \n imgLineEnds.forEach((i)=>{\n if (atmnt.filename.slice(-i.length).toLowerCase()===i.toLowerCase()) {\n img=true;\n }\n });\n \n vidLineEnds.forEach((i)=>{\n if (atmnt.filename.slice(-i.length).toLowerCase()===i.toLowerCase()) {\n vid=true;\n }\n });\n\n if (img) {\n link=(`<a href=\"${atmnt.url}\"><img src=\"${atmnt.url}\" class=\"img\"></a>`)\n } else if (vid) {\n link=(`<video controls class=\"vid\" src=\"${atmnt.url}\"></video>`)\n } else {\n link=(`<a class=\"attachment\" href=\"${atmnt.url}\" download><img src=\"./file.png\"><span class=\"attachmentText\">${atmnt.filename}</span></a>`)\n }\n return link\n}\n\n// return parsed embeds inside html template\nfunction handleEmbeds(message) {\n var thisFields=\"\"\n var index=1\n var embed=\"\"\n message.embeds[0].fields.forEach((i)=>{\n\n thisFields+=`\n <details class=\"subDet\">\n <summary>\n Field ${index}: ${i.name}\n </summary>\n ${i.value}\n </details>\n `;\n index+=1\n });\n embed+=`\n <details style=\"background-color: ${message.embeds[0].hexColor};\" class=\"detailWrap\">`\n if(message.embeds[0].title!=null){\n embed+=`\n <summary>\n Title: ${message.embeds[0].title}\n </summary>\n `;\n }\n if(message.embeds[0].description!=null){\n embed+=`\n <details class=\"subDet\">\n <summary>\n Description\n </summary>\n ${message.embeds[0].description}<br>\n </details> \n `;\n }\n if(message.embeds[0].footer!=null){\n if(message.embeds[0].footer.text!=null){\n embed+=`\n <details class=\"subDet\">\n <summary>\n footer\n </summary>\n ${message.embeds[0].footer.text}<br>\n </details>\n `;\n }\n }\n if(thisFields!=\"\"){\n embed+=`\n <details style=\"padding: 0.5em;\" class=\"subDet\">\n <summary>\n Fields:\n </summary>\n ${thisFields}\n </details> \n `;\n }\n if(message.embeds[0].image!=null){\n if(message.embeds[0].image.url!=null){\n embed+=`\n <details class=\"subDet\">\n <summary>\n Image url: <a href=\"${message.embeds[0].image.url}\">${message.embeds[0].image.url}</a><br>\n </summary>\n <img src=\"${message.embeds[0].image.url}\">\n </details>\n `;\n }\n }\n if(message.embeds[0].color!=null){\n embed+=`\n Color hex: ${message.embeds[0].hexColor}<br>\n `;\n }\n if(message.embeds[0].author!=null){\n if(message.embeds[0].author.tag!=null){\n embed+=`\n Author: ${message.embeds[0].author.tag}<br>\n `;\n }\n }\n if(message.embeds[0].url!=null){\n embed+=`\n Url: <a href=\"${message.embeds[0].url}\">${message.embeds[0].url}</a><br>\n `;\n }\n embed+=`\n </details>\n `;\n return embed;\n}\n\n// Primary function read and write files and handle message data.\nfunction logThatShit(message,date,time){\n var writedata=\"\"\n var insertpoint=0;\n var filepath=`./logs/${message.guild.name}.html`;\n var data=\" \"\n\n if (!fs.existsSync(filepath)){\n fs.writeFileSync(filepath,htmlbase);\n logdata=fs.readFileSync(\"./logs/Log.html\",'utf8');\n inputdata=(`\\n<a href=\"./${message.guild.name}.html\" class=\"loglink\" ><img src=\"./file.png\"><span class=\"attachmentText\">${message.guild.name}</span></a>`);\n insertpoint=logdata.indexOf('<div class=\"wrapper\">')+'<div class=\"wrapper\">'.length+1;\n writedata=logdata.slice(0,insertpoint)+inputdata+logdata.slice(insertpoint);\n fs.writeFileSync(\"./logs/Log.html\",writedata)\n data=htmlbase;\n }else{\n data=fs.readFileSync(filepath,'utf8');\n if (data.startsWith(\"<!DOCTYPE html>\")==false){\n data=htmlbase;\n }\n }\n \n var msgattachmentstr=\"\";\n var msgembed=\"\";\n \n if (message.attachments.array().length>0){\n var msgattachmentstr=handleAttachments(message);\n }\n\n if (message.embeds.length>0){\n var msgembed=handleEmbeds(message);\n }\n\n insertpoint=data.indexOf('<div class=\"wrapper\">')+'<div class=\"wrapper\">'.length+1;\n var inputdata=`\n <div class=\"message ${message.channel.name}\">\n ${msgattachmentstr}\n <a onclick=\"hide('${message.channel.name}')\">\n <span class=\"guild\">\n ${message.guild.name} \n </span>\n <span class=\"channel\">\n [${message.channel.name}]:\n </span>\n </a>\n <span class=\"date\">\n ${date} \n </span>\n <span class=\"time\">\n [${time}]: \n </span>\n <span class=\"author\">\n ${message.author.tag} \n </span>\n <span class=\"authorname\">\n (${message.member.displayName}): \n </span>\n <span class=\"content\">\n ${message.cleanContent}\n </span>\n ${msgembed}\n </div>\n `;\n writedata=data.slice(0,insertpoint)+inputdata+data.slice(insertpoint);\n fs.writeFileSync(filepath,writedata)\n}\n\n// Activates on start\nclient.on('ready', () => {\n var datetime=client.readyAt\n var date=`${datetime.getFullYear()}-${datetime.getMonth()+1}/${datetime.getDate()}`\n var time=`${datetime.getHours()}:${datetime.getMinutes()}:${datetime.getSeconds()}`\n console.log(`\n Connected: logged in as ${client.user.tag}\n Running bot started: ${date} [${time}]\n Running LogBot version: ${jsondata.botversion}\n `);\n});\n\n// Activates on message\nclient.on('message', message => {\n var datetime=message.createdAt;\n var date=`${datetime.getFullYear()}-${datetime.getMonth()+1}/${datetime.getDate()}`\n var time=`${datetime.getHours()}:${datetime.getMinutes()}:${datetime.getSeconds()}`\n logThatShit(message,date,time)\n});\n\n// Login using token in data.json\nclient.login(jsondata.token);\n" }, { "alpha_fraction": 0.5411278009414673, "alphanum_fraction": 0.5450077652931213, "avg_line_length": 32.32758712768555, "blob_id": "b53e4d366005f7068c5b7637e957c5ebb60bee5e", "content_id": "db99e037e7fe5d3b9f2923fbcf4b260aadd62694", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7732, "license_type": "no_license", "max_line_length": 171, "num_lines": 232, "path": "/logbot.py", "repo_name": "RandomDuck/logbot", "src_encoding": "UTF-8", "text": "import discord\nimport logging\nimport datetime\nimport json\nimport os\nimport time as sleeper\n\nhtmlbase='''<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <link rel=\"stylesheet\" href=\"logs.css\">\n <title>Log</title>\n <script>\n function hide(type){\n reset();\n x = document.getElementsByClassName(\"message\")\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"none\"\n }\n x = document.getElementsByClassName(type)\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"inline-block\"\n }\n }\n function reset(){\n x = document.getElementsByClassName(\"message\")\n for (i = 0;i < x.length;i++) {\n x[i].style.display=\"inline-block\"\n }\n }\n </script>\n </head>\n <body>\n <button onclick=\"reset()\">Reset</button>\n <div class=\"wrapper\">\n </div>\n </body>\n</html>\n'''\n\ndef handleAttachments(message):\n atmnt=message.attachments[0]\n imgLineEnds=[\"jpg\",\"png\",\"svg\",\"gif\",\"jpeg\"]\n vidLineEnds=[\"mp4\",\"webm\",\"ogg\",\"flac\",\"mov\"]\n img=False\n vid=False\n link=''\n \n for i in imgLineEnds:\n if atmnt.filename[-len(i):].lower()==i.lower():\n img=True\n \n for i in vidLineEnds:\n if atmnt.filename[-len(i):].lower()==i.lower():\n vid=True\n\n if img:\n link=(f'<a href=\"{atmnt.url}\"><img src=\"{atmnt.url}\" class=\"img\"></a>')\n elif vid:\n link=(f'<video controls class=\"vid\" src=\"{atmnt.url}\"></video>')\n else:\n link=(f'<a class=\"attachment\" href=\"{atmnt.url}\" download><img src=\"./file.png\"><span class=\"attachmentText\">{atmnt.filename}</span></a>')\n return link\n\ndef handleEmbeds(message):\n thisFields=\"\"\n index=1\n for i in message.embeds[0].fields:\n thisFields+=(f'''\n <details class=\"subDet\">\n <summary>\n Field {index}: {i.title}\n </summary>\n {i.text}\n </details>\n ''')\n index+=1\n\n return (f'''\n <details style=\"background-color: {message.embeds[0].color};\" class=\"detailWrap\">\n <summary>\n Title: {message.embeds[0].title}\n </summary>\n <details class=\"subDet\">\n <summary>\n Description\n </summary>\n {message.embeds[0].description}<br>\n </details> \n <details class=\"subDet\">\n <summary>\n footer\n </summary>\n {message.embeds[0].footer.text}<br>\n </details>\n <details style=\"padding: 0.5em;\" class=\"subDet\">\n <summary>\n Fields:\n </summary>\n {thisFields}\n </details> \n <details class=\"subDet\">\n <summary>\n Image url: <a href=\"{message.embeds[0].image.url}\">{message.embeds[0].image.url}</a><br>\n </summary>\n <img src=\"{message.embeds[0].image.url}\">\n </details>\n Color hex: {message.embeds[0].color}<br>\n Author: {message.embeds[0].author.name}<br>\n Url: <a href=\"{message.embeds[0].url}\">{message.embeds[0].url}</a><br>\n </details>\n ''')\n\n\n\ndef logThatShit(message,date,time):\n if not os.path.exists(f\"./logs/{message.guild.name}.html\"):\n f = open((f\"./logs/{message.guild.name}.html\"), \"w\")\n data=open(\"./logs/log.html\",\"r\").read()\n insertpoint=data.find('<div class=\"wrapper\">')+len('<div class=\"wrapper\">')+1\n inputdata=(f'\\n<a href=\"./{message.guild.name}.html\" download class=\"loglink\" ><img src=\"./file.png\"><span class=\"attachmentText\">{message.guild.name}</span></a>')\n writedata=data[:insertpoint]+inputdata+data[insertpoint:]\n print(writedata,file=open((f\"./logs/log.html\"), \"w\"))\n\n with open((f\"./logs/{message.guild.name}.html\"), \"r\") as userFile:\n data=userFile.read()\n msgattachmentstr=\"\"\n msgembed=\"\"\n if not data.startswith(\"<!DOCTYPE html>\"):\n data=htmlbase\n\n if len(message.attachments)>0:\n msgattachmentstr=handleAttachments(message)\n\n if len(message.embeds)>0:\n msgembed=handleEmbeds(message)\n\n insertpoint=data.find('<div class=\"wrapper\">')+len('<div class=\"wrapper\">')+1\n inputdata=(f'''\n <div class=\"message {message.channel}\">\n {msgattachmentstr}\n <a onclick=\"hide('{message.channel}')\">\n <span class=\"guild\">\n {message.guild.name} \n </span>\n <span class=\"channel\">\n [{message.channel}]:\n </span>\n </a>\n <span class=\"date\">\n {date} \n </span>\n <span class=\"time\">\n [{time}]: \n </span>\n <span class=\"author\">\n {message.author} \n </span>\n <span class=\"authorname\">\n ({message.author.name}): \n </span>\n <span class=\"content\">\n {message.clean_content}\n </span>\n {msgembed}\n </div>\n ''')\n writedata=data[:insertpoint]+inputdata+data[insertpoint:]\n print(writedata,file=open((f\"./logs/{message.guild.name}.html\"), \"w\"))\n # print(data[:insertpoint])\n # print(inputdata)\n # print(data[insertpoint:])\n\n# setup logging\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename=f'./botlogs/discord_{datetime.datetime.now().date()}.log', encoding='utf-8', mode='a')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\n# Read token, botversion and midf from a json \"data\" file\ndata=json.loads(open(\"data.json\",\"r\").read())\nbotversion = data[\"botversion\"]\ntoken = data[\"token\"]\nmidf = data[\"cmdMod\"]\n\nclass cmd(): # Use: evaluate command sent by bot admin.\n def __init__(self,midf,message,client):\n self.name=type(self).__name__\n self.message=message\n self.client=client\n self.midf=midf\n self.command=self.message.content[len(self.midf)+len(self.name):]\n self.args=self.command.split(' ')\n \n async def cmd(self):\n if self.message.author.id == 197327976621277184:\n await eval(self.command)\n else:\n await self.message.channel.send(\"Access denied.\")\n\n# starts the discord client.\nclient = discord.Client() \n\[email protected] # event decorator/wrapper. More on decorators here: https://pythonprogramming.net/decorators-intermediate-python-tutorial/\nasync def on_ready(): # method expected by client. This runs once when connected\n \n # notification of login.\n print(f'''\n Connected: logged in as {client.user}\n Running discord.py version: {discord.__version__}\n Running LogBot version: {botversion}\n ''') \n\[email protected]\nasync def on_message(message): # event that happens per any message.\n\n # get and format date and time and then output to log.\n dt=datetime.datetime.now() \n date=dt.date()\n time=dt.time().strftime(\"%H:%M:%S\")\n logThatShit(message,date,time)\n\n # check if a command was called then run it.\n if message.content[0:len(midf)]==midf:\n await cmd(midf,message,client).cmd()\n\n# Initiate loop. (placed att absolute bottom)\nclient.run(token,bot=False)\n" }, { "alpha_fraction": 0.7982456088066101, "alphanum_fraction": 0.7982456088066101, "avg_line_length": 114, "blob_id": "5b05a76d7fe1b3465007402921f1c8fea3b89b51", "content_id": "2db45b16844fd8cb7cc625755dd6f4893e2b19b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 114, "license_type": "no_license", "max_line_length": 114, "num_lines": 1, "path": "/README.md", "repo_name": "RandomDuck/logbot", "src_encoding": "UTF-8", "text": "This is my logbot for discord, i originaly made it in python but changed to javascript since it was esier to host." } ]
3
raonifduarte/Fundamentos_Projetos
https://github.com/raonifduarte/Fundamentos_Projetos
c16c1a8751cf349a25ab57ecb9bebc47567fc838
f73b21d3f50964988155cdb876b7a17adc39d24c
a5774f92b4e3fd28b990c62497cdd3c67b7f92a1
refs/heads/main
2023-05-30T10:01:26.517355
2021-06-16T15:58:29
2021-06-16T15:58:29
377,551,911
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6194690465927124, "alphanum_fraction": 0.6548672318458557, "avg_line_length": 20.600000381469727, "blob_id": "0c1e3b1fca04d893cf57b6eb58d59008881b28aa", "content_id": "c825383e1be211c6c78912b3c844584ce363c5e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 115, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/area_circunferencia_v4.py", "repo_name": "raonifduarte/Fundamentos_Projetos", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python3\r\nimport math\r\nprint(math.pi)\r\nraio = 15\r\nprint('Área do círculo', math.pi * raio ** 2)\r\n" }, { "alpha_fraction": 0.5720930099487305, "alphanum_fraction": 0.5860465168952942, "avg_line_length": 19.5, "blob_id": "2a261db43e123d777ef37d89df4efdb095039cf9", "content_id": "6c35cf7a4bb87f9fa135a2af0cbb76a76493ad89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "no_license", "max_line_length": 48, "num_lines": 10, "path": "/nota_aluno.py", "repo_name": "raonifduarte/Fundamentos_Projetos", "src_encoding": "UTF-8", "text": "nota = float(input('Insira a nota do aluno: '))\r\n\r\nif nota >= 9:\r\n print('Aprovado com honras')\r\nelif nota >= 7:\r\n print('Aprovado')\r\nelif nota >= 5:\r\n print('Recuperação')\r\nelse:\r\n print('Reprovado')\r\n" } ]
2
garvit74/Python-Tkinter
https://github.com/garvit74/Python-Tkinter
1be0f25133f5d70fdefa2ea01b404a050ebb1c20
1f283580fe1405ce7db912b88561751b76616d86
dc54d388a51b82ce0b7f99c412ab2a8b53a72339
refs/heads/main
2023-08-03T07:25:54.027659
2021-09-26T08:18:06
2021-09-26T08:18:06
409,453,029
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6178861856460571, "alphanum_fraction": 0.642276406288147, "avg_line_length": 16.571428298950195, "blob_id": "4c22a668a1506368cf0f9d69c5b0318940be08ed", "content_id": "8a69ba145015f67e68efb4879e7cd25cf38d1411", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 80, "num_lines": 14, "path": "/Buttons.py", "repo_name": "garvit74/Python-Tkinter", "src_encoding": "UTF-8", "text": "from tkinter import *\n\nroot = Tk()\n\n\ndef myClick():\n my_label = Label(root, text=\"I am clicked!\",fg='brown')\n my_label.pack()\n\n\nbutton = Button(root, text=\"Click Me\", command=myClick, fg='cyan', bg='#787777')\nbutton.pack()\n\nroot.mainloop()\n" }, { "alpha_fraction": 0.6242774724960327, "alphanum_fraction": 0.6329479813575745, "avg_line_length": 18.22222137451172, "blob_id": "9a518670433b62edaca067d8fbd4b7eedbf8d5f5", "content_id": "5f0f3dee17cd60315683c1b8a965efb494bd590a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 89, "num_lines": 18, "path": "/Entry.py", "repo_name": "garvit74/Python-Tkinter", "src_encoding": "UTF-8", "text": "from tkinter import *\n\nroot = Tk()\ne = Entry(root, width=50)\ne.pack()\ne.insert(0, \"Enter Your Name: \")\n\n\ndef myClick():\n hello = f\"Hello! {e.get()}\"\n my_label = Label(root, text=hello, fg='brown')\n my_label.pack()\n\n\nbutton = Button(root, text=\"Enter Your Name\", command=myClick, fg='white', bg='sky blue')\nbutton.pack()\n\nroot.mainloop()\n" }, { "alpha_fraction": 0.588691771030426, "alphanum_fraction": 0.637749433517456, "avg_line_length": 32.10091781616211, "blob_id": "91149753269eaf167cd075b33e4953f0d334f506", "content_id": "b0d4cd176acfedbec944a7cdcd925f335290b3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3608, "license_type": "no_license", "max_line_length": 111, "num_lines": 109, "path": "/Calculator_Simple.py", "repo_name": "garvit74/Python-Tkinter", "src_encoding": "UTF-8", "text": "from tkinter import *\n\nroot = Tk()\nroot.title(\"Simple Calculator\")\n\ne = Entry(root, width=35, borderwidth=5, fg='Dark Green', font=('caliber', 10, 'bold'))\ne.grid(row=0, column=0, columnspan=3, padx=10, pady=10)\n\nf_num = 0\nx = 0\n\n\ndef button_click(number):\n current = e.get()\n e.delete(0, END)\n e.insert(0, current + str(number))\n\n\ndef button_clear():\n e.delete(0, END)\n\n\ndef button_add():\n first_num = e.get()\n global f_num\n global x\n x = 1\n f_num = int(first_num)\n e.delete(0, END)\n\n\ndef button_sub():\n first_num = e.get()\n global f_num\n global x\n x = 2\n f_num = int(first_num)\n e.delete(0, END)\n\n\ndef button_multiply():\n first_num = e.get()\n global f_num\n global x\n x = 3\n f_num = int(first_num)\n e.delete(0, END)\n\n\ndef button_div():\n first_num = e.get()\n global f_num\n global x\n x = 4\n f_num = int(first_num)\n e.delete(0, END)\n\n\ndef button_Equal():\n sec_num = e.get()\n e.delete(0, END)\n if x == 1:\n e.insert(0, str(f_num + int(sec_num)))\n if x == 2:\n e.insert(0, str(f_num - int(sec_num)))\n if x == 3:\n e.insert(0, str(f_num * int(sec_num)))\n if x == 4:\n e.insert(0, str(f_num / int(sec_num)))\n\n\nbutton_0 = Button(root, text=\"0\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(0))\nbutton_1 = Button(root, text=\"1\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(1))\nbutton_2 = Button(root, text=\"2\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(2))\nbutton_3 = Button(root, text=\"3\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(3))\nbutton_4 = Button(root, text=\"4\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(4))\nbutton_5 = Button(root, text=\"5\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(5))\nbutton_6 = Button(root, text=\"6\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(6))\nbutton_7 = Button(root, text=\"7\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(7))\nbutton_8 = Button(root, text=\"8\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(8))\nbutton_9 = Button(root, text=\"9\", padx=40, pady=20, fg='black', bg='sky blue', command=lambda: button_click(9))\nbutton_add = Button(root, text=\"+\", padx=39, pady=20, fg='black', bg='sky blue', command=button_add)\nbutton_sub = Button(root, text=\"-\", padx=40, pady=20, fg='black', bg='sky blue', command=button_sub)\nbutton_multi = Button(root, text=\"*\", padx=41, pady=20, fg='black', bg='sky blue', command=button_multiply)\nbutton_div = Button(root, text=\"/\", padx=40, pady=20, fg='black', bg='sky blue', command=button_div)\nbutton_equal = Button(root, text=\"=\", padx=87, pady=20, fg='black', bg='sky blue', command=button_Equal)\nbutton_clear = Button(root, text=\"Clear\", padx=77, pady=20, fg='black', bg='sky blue', command=button_clear)\n\nbutton_0.grid(row=4, column=0, columnspan=1)\nbutton_add.grid(row=5, column=0, columnspan=1)\nbutton_equal.grid(row=5, column=1, columnspan=2)\nbutton_clear.grid(row=4, column=1, columnspan=2)\nbutton_sub.grid(row=6, column=0, columnspan=1)\nbutton_div.grid(row=6, column=1, columnspan=1)\nbutton_multi.grid(row=6, column=2, columnspan=1)\n\nbutton_1.grid(row=3, column=0)\nbutton_2.grid(row=3, column=1)\nbutton_3.grid(row=3, column=2)\n\nbutton_4.grid(row=2, column=0)\nbutton_5.grid(row=2, column=1)\nbutton_6.grid(row=2, column=2)\n\nbutton_7.grid(row=1, column=0)\nbutton_8.grid(row=1, column=1)\nbutton_9.grid(row=1, column=2)\n\nroot.mainloop()\n" }, { "alpha_fraction": 0.7986111044883728, "alphanum_fraction": 0.7986111044883728, "avg_line_length": 35, "blob_id": "6fcd4c45279a1b56042fd8ef18e61cbce4e62b9b", "content_id": "f00fdcb5f60ba2f76158b9409912ac082ac31024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 144, "license_type": "no_license", "max_line_length": 85, "num_lines": 4, "path": "/README.md", "repo_name": "garvit74/Python-Tkinter", "src_encoding": "UTF-8", "text": "# Python-Tkinter\n\nI have started learning Python-Tkinter \nIn this repository I will share the codes I created using this gui library of python.\n" }, { "alpha_fraction": 0.596875011920929, "alphanum_fraction": 0.6343749761581421, "avg_line_length": 17.764705657958984, "blob_id": "cdf5bb8391ae023cbde7c9bcff24b8b0e6c4defa", "content_id": "89d66c9ca152e21fe9dfd566bf0bda5de69adbf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 56, "num_lines": 17, "path": "/grid.py", "repo_name": "garvit74/Python-Tkinter", "src_encoding": "UTF-8", "text": "from tkinter import *\n\nroot = Tk()\n\n# Creating a label\n\nmyLabel1 = Label(root, text=\"Hello World!\")\n\nmyLabel2 = Label(root, text=\" \")\nmyLabel3 = Label(root, text=\"My name is Garvit Agrawal\")\n\nmyLabel1.grid(row=0, column=0)\n\nmyLabel2.grid(row=1, column=0)\nmyLabel3.grid(row=2, column=1)\n\nroot.mainloop()\n\n" } ]
5
krasheninnikov/gym-experiments
https://github.com/krasheninnikov/gym-experiments
06b428fe25fab4a34a26f616ea8db5f82c3e0cc7
41c1576f672dada65ff0de60038791c52e7eb26e
b300437dbb9700588a27012db2fe7c7a8cf6be20
refs/heads/master
2021-01-11T09:31:36.897571
2016-12-29T22:28:44
2016-12-29T22:28:44
77,451,886
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5622665286064148, "alphanum_fraction": 0.5841635465621948, "avg_line_length": 32, "blob_id": "efd0752f3797eeb21a32afa3e74409294b146775", "content_id": "a39e426c3d1d49764e25e5d9b8d398629b163caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9636, "license_type": "no_license", "max_line_length": 121, "num_lines": 292, "path": "/VideoPinballDQN.py", "repo_name": "krasheninnikov/gym-experiments", "src_encoding": "UTF-8", "text": "import gym\nimport tensorflow as tf\nimport itertools\nimport collections\nimport sys\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.constraints import maxnorm\nfrom keras.optimizers import Adam\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import load_model\n\nif \"../\" not in sys.path:\n sys.path.append(\"../\")\n\nclass ImgBuf:\n \"\"\"\n A ring buffer for holding multiple consecutive preprocessed frames.\n append(image) adds the frame to the buffer instead of the oldest one present.\n get() returns all frames from the buffer in the order they were added.\n empty() empties the ring buffer\n \"\"\"\n def __init__(self, shape):\n self.shape = shape\n self.frame_buf = np.zeros(self.shape)\n self.index = 0\n\n def append(self, image):\n self.frame_buf[self.index, :, :] = image\n self.index += 1\n self.index = self.index % self.shape[0]\n\n def get(self):\n idx = (self.index + np.arange(self.shape[0])) % self.shape[0]\n return self.frame_buf[idx, :, :].reshape(1, self.shape[0], self.shape[1], self.shape[2])\n\n def empty(self):\n self.frame_buf = np.zeros(self.shape)\n self.index = 0\n\n\nclass ReplayBuf:\n \"\"\"\n Synchronised ring buffers that hold (s_t, a_t, reward, s_t_plus_1).\n :param s_t and s_t_plus_1 have shape of (replay_size, n_ch, img_side, img_side)\n :param a_t is an int vector (one-hot encoding)\n :param reward is int\n \"\"\"\n def __init__(self, shape, n_actions):\n self.shape = shape\n self.index = 0\n\n self.s_t = np.zeros(shape)\n self.s_t_plus_1 = np.zeros(shape)\n self.n_actions = n_actions\n self.action = np.zeros((shape[0], n_actions))\n self.reward = np.zeros(shape[0])\n\n def append(self, s_t, a_t, reward, s_t_plus_1):\n self.s_t[self.index, :, :, :] = s_t\n self.s_t_plus_1[self.index, :, :, :] = s_t_plus_1\n\n act = np.zeros(self.n_actions)\n act[a_t] = 1\n self.action[self.index] = act\n self.reward[self.index] = reward\n\n self.index += 1\n self.index = self.index % self.shape[0]\n\n\ndef preprocess(img):\n \"\"\"\n :param img: a frame from the Atari simulator\n :return: the frame cropped and downsampled to 80x80 grayscale\n \"\"\"\n img = img[60:220] # crop\n img = img[::2, ::2, 1] # downsample by factor of 2\n return img.astype(np.float)\n\ndef clip_reward(reward):\n \"\"\"\n Clips the rewards to either -1, 0 or 1 for more stable training of the network\n :param reward: int\n :return: clipped reward, int\n \"\"\"\n\n if reward > 0:\n reward = 1\n elif reward < 0:\n reward = -1\n return reward\n\ndef make_init_replay(env, replay, eps):\n \"\"\"\n Makes the initial experience replay dataset by taking\n random actions and recording (s_t, a_t, reward, s_t_plus_1)\n :param env: OpenAI gym env\n :param replay: ReplayBuf object\n :param eps: probability that the tuple (s_t, a_t, reward, s_t_plus_1) will be added to replay\n\n :return: replay: a full replay buffer\n \"\"\"\n max_episode_len = 30000\n frame_buf = ImgBuf((3, 80, 80))\n i = 0\n\n while i < replay.shape[0]:\n\n s_t_plus_1 = None\n frame_buf.append(preprocess(env.reset()))\n s_t = frame_buf.get()\n a_t = env.action_space.sample()\n\n for t in range(max_episode_len):\n\n if s_t_plus_1 is not None:\n s_t = s_t_plus_1\n a_t = a_t_plus_1\n\n obs, reward, done, _ = env.step(a_t)\n frame_buf.append(preprocess(obs))\n s_t_plus_1 = frame_buf.get()\n\n if np.random.rand() < eps:\n replay.append(s_t, a_t, clip_reward(reward), s_t_plus_1)\n i += 1\n\n a_t_plus_1 = env.action_space.sample()\n\n if done or t == (max_episode_len-1):\n frame_buf.empty()\n replay.append(s_t_plus_1, a_t_plus_1, -1, s_t_plus_1)\n break\n\n\ndef make_model(n_actions=9):\n model = Sequential()\n model.add(Convolution2D(32, 3, 3, input_shape=(3, 80, 80), border_mode='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Flatten())\n model.add(Dense(256, activation='relu', W_constraint=maxnorm(3)))\n model.add(Dropout(0.2))\n\n model.add(Dense(n_actions, activation='linear'))\n # Compile model\n model.compile(loss='mse', optimizer=Adam())\n print(model.summary())\n\n return model\n\n\ndef train(model, replay, discount_factor=.999, epochs=10):\n batchsize = 128\n s_t, a_t, reward, s_t_plus_1 = (replay.s_t, replay.action, replay.reward, replay.s_t_plus_1)\n\n s_t_Q = model.predict(s_t)\n s_t_plus_1_Q = model.predict(s_t_plus_1)\n\n TD_error = a_t * (reward + discount_factor * np.amax(s_t_plus_1_Q, axis=1)).reshape(replay.shape[0], 1) - a_t * s_t_Q\n\n target = s_t_Q + TD_error\n model.fit(s_t, target, nb_epoch=epochs, batch_size=batchsize)\n\n return model\n\n\ndef make_epsilon_greedy_policy(estimator, epsilon, n_actions):\n \"\"\"\n Creates an epsilon-greedy policy based on a given Q-function approximator and epsilon.\n\n :param estimator: An estimator that returns q values for a given frame_buf\n :param epsilon: The probability to select a random action . float between 0 and 1.\n :param n_actions: Number of actions in the environment.\n\n :return a function that takes the observation as an argument and returns\n the probabilities for each action in the form of a numpy array of length n_actions.\n\n \"\"\"\n\n def policy_fn(observation):\n A = np.ones(n_actions, dtype=float) * epsilon / n_actions\n q_values = estimator.predict(observation, batch_size=1, verbose=0)\n best_action = np.argmax(q_values)\n A[best_action] += (1.0 - epsilon)\n return A\n\n return policy_fn\n\n\ndef main():\n\n resume = 0\n replay_size = 40000\n add_to_rep_prob = .1\n num_episodes = 100\n max_episode_len = 100000\n epsilon = .01\n epsilon_decay = .99\n frame_buf = ImgBuf((3, 80, 80))\n discount_factor = .999\n stats = np.zeros((3, num_episodes))\n\n env = gym.envs.make(\"VideoPinball-v0\")\n env.reset()\n\n replay = ReplayBuf(shape=(replay_size, 3, 80, 80), n_actions=env.action_space.n)\n print(\"making init replay ...\")\n make_init_replay(env=env, replay=replay, eps=0.05)\n print(\"init replay done\")\n print(replay.s_t.shape)\n\n tf.python.control_flow_ops = tf\n with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:\n with tf.device(\"/gpu:0\"):\n\n if resume == 0:\n Q1 = make_model(n_actions=env.action_space.n)\n else:\n print(\"loading model ...\")\n Q1 = load_model('Q1.h5')\n\n init = tf.global_variables_initializer()\n sess.run(init)\n\n Q1 = train(Q1, replay, discount_factor=discount_factor, epochs=10)\n Q1.save('Q1.h5')\n\n for i_episode in range(num_episodes):\n print(\"starting episode \", i_episode, \" ...\")\n\n # The policy we're following\n policy = make_epsilon_greedy_policy(\n Q1, epsilon * epsilon_decay ** i_episode, env.action_space.n)\n\n s_t_plus_1 = None\n\n frame_buf.append(preprocess(env.reset()))\n s_t = frame_buf.get()\n action_probs = policy(s_t)\n a_t = np.random.choice(np.arange(len(action_probs)), p=action_probs)\n\n for t in range(max_episode_len):\n\n if s_t_plus_1 is not None:\n s_t = s_t_plus_1\n a_t = a_t_plus_1\n\n obs, reward, done, _ = env.step(a_t)\n frame_buf.append(preprocess(obs))\n s_t_plus_1 = frame_buf.get()\n\n action_probs = policy(s_t_plus_1)\n a_t_plus_1 = np.random.choice(np.arange(len(action_probs)), p=action_probs)\n\n if np.random.rand() < add_to_rep_prob:\n replay.append(s_t, a_t, clip_reward(reward), s_t_plus_1)\n\n stats[0, i_episode] += reward\n stats[1, i_episode] += clip_reward(reward)\n if done or t == (max_episode_len-1):\n frame_buf.empty()\n Q1 = train(Q1, replay, discount_factor=discount_factor, epochs=3)\n Q1.save('Q1.h5')\n # sys.stdout.flush()\n print(\"episode \", i_episode, \" done in \", t, \" steps, reward is \", stats[0, i_episode])\n stats[2, i_episode] = t\n np.savetxt('stats-pinball.txt', stats)\n break\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
12thpass/blacklscheck
https://github.com/12thpass/blacklscheck
bafc5128c7391a2091e66a831d9ce156f50af956
32e158bdfb58881ebb6fe5bb9b20bc1183bf9a37
3561b334c2415f101a3637fe4d16240db07e8911
refs/heads/master
2020-09-02T17:22:13.178488
2019-11-05T04:34:04
2019-11-05T04:34:04
219,268,381
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5862661004066467, "alphanum_fraction": 0.6025751233100891, "avg_line_length": 37.83333206176758, "blob_id": "34605becb2b7ca5c0299e15ec941c42d56e77d54", "content_id": "0bb0f482bef2758976064c2de56be2ad54bdf04e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1165, "license_type": "no_license", "max_line_length": 169, "num_lines": 30, "path": "/teamtrees.py", "repo_name": "12thpass/blacklscheck", "src_encoding": "UTF-8", "text": "import socket\nfrom colorama import Fore, Back, Style \n# below line for get multiple ip input \nxip = [str(newx) for newx in input(\"Enter multiple value: \").split()] \nprint(xip)\n# you can add more blacklis here \nbl = [\"b.barracudacentral.org\",\n \"dnsbl.sorbs.net\",\n \"dnsbl-1.uceprotect.net\",\n \"dnsbl-2.uceprotect.net\",\n \"dnsbl-3.uceprotect.net\",\n \"pbl.spamhaus.org\",\n \"sbl.spamhaus.org\",\n \"xbl.spamhaus.org\",\n \"zen.spamhaus.org\"]\n\n# below for loop get our ip and run for all blacklist for more contact SkypeId: deepakmeena900\nfor ip in xip :\n print ( Fore.YELLOW + ip + \" checking\")\n for xbl in bl:\n querybad = '.'.join(reversed(str(ip).split(\".\"))) + \".\" + xbl\n try: \n addr1 = socket.gethostbyname(querybad)\n print( Fore.RED + str(ip) + \" listed in \" + str(xbl))\n if xbl == \"b.barracudacentral.org\" :\n print(\"http://www.barracudacentral.org/rbl/removal-request/\" + ip +\"&address=\" + ip +\"/&[email protected]&phone=1234567890&ir_code=&submit=submit%20request\")\n \n except :\n #print( Fore.GREEN + str(ip) + \" NO listed in \" + str(xbl))\n pass\n" } ]
1
Sainithin-bit/BarCode-Scanner
https://github.com/Sainithin-bit/BarCode-Scanner
5c22e036b2b8527f8fad139fed3846e20ca7cffd
cc3f89f7eea4195c92139394a25a0b16416d7d71
3573fe1d19e409183576c001f121438202490aca
refs/heads/master
2022-04-11T05:32:45.053370
2020-03-26T10:55:40
2020-03-26T10:55:40
250,228,560
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5637149214744568, "alphanum_fraction": 0.584233283996582, "avg_line_length": 22.972972869873047, "blob_id": "0cf6d5a714213d6eae142cf65006563a6e8e5844", "content_id": "63038c2b28876e713f1dea9eda5516cceedd12b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 926, "license_type": "no_license", "max_line_length": 87, "num_lines": 37, "path": "/Barcode scanner.py", "repo_name": "Sainithin-bit/BarCode-Scanner", "src_encoding": "UTF-8", "text": "from __future__ import print_function\r\nimport pyzbar.pyzbar as pyzbar\r\nimport numpy as np\r\nimport cv2\r\n\r\ndef decoede(im):\r\n decodedobjects=pyzbar.decode(im)\r\n\r\n for obj in decodedobjects:\r\n print('Type: ',obj.type)\r\n print('Data: ',obj.data,'\\n')\r\n\r\n return decodedobjects\r\n\r\ndef display(im,decodedobjects):\r\n for decodedobject in decodedobjects:\r\n points=decodedobject.polygon\r\n\r\n if len(points)>4:\r\n hull=cv2.convexHull(np.array([point for point in points],dtype=np.float32))\r\n hull=list(map(tuple,np.squeeze(hull)))\r\n else:\r\n hull=points;\r\n n=len(hull)\r\n\r\n for j in range(0,n):\r\n cv2.line(im,hull[j],hull[(j+1)%n],(255,0,0),3)\r\n\r\n cv2.imshow(\"Result\",im);\r\n cv2.waitKey(0);\r\n\r\nif __name__=='__main__':\r\n\r\n im=cv2.imread('Qr-3.png')\r\n\r\n decodedobjects=decoede(im)\r\n display(im,decodedobjects)\r\n\r\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 24, "blob_id": "bff3394ed69a809c427c1c91e752551975658358", "content_id": "29052d4fe1398884c69212e064bec1d71e135906", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 75, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/README.md", "repo_name": "Sainithin-bit/BarCode-Scanner", "src_encoding": "UTF-8", "text": "# BarCode-Scanner\n\nI have attached three sample images for testing pupose.\n" } ]
2
bmahaj2/SQL-Queries---Data-Science-Assignment
https://github.com/bmahaj2/SQL-Queries---Data-Science-Assignment
218076291ac625c1b085d31c2ad2ff713afd930f
58368a8bdc725fce63030d9eeb85848eda48558d
db0f81d0ae7347b941f0920ec774d98df9c18d4d
refs/heads/master
2021-01-11T22:26:56.088885
2017-01-14T20:16:38
2017-01-14T20:16:38
78,964,248
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5826228857040405, "alphanum_fraction": 0.6243424415588379, "avg_line_length": 54.13999938964844, "blob_id": "0f91b981792243fc5f7e029b493a5e2e0b0f8cd5", "content_id": "579260d1620b8fdd35523d19f81b72256853a6f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5513, "license_type": "no_license", "max_line_length": 966, "num_lines": 100, "path": "/bmahaj2.py", "repo_name": "bmahaj2/SQL-Queries---Data-Science-Assignment", "src_encoding": "UTF-8", "text": "import sqlite3\n\n####################################################\n# TODO assign [your netid].result to netid variable\n####################################################\nnetid = \"bmahaj2.result\" # suppose your netid is \"liu4\", the output file should be\n # liu4.result with extension .result\n\n###########################################\n# TODO put database file in the right path\n###########################################\nsocial_db = \"./data/social.db\"\nmatrix_db = \"./data/matrix.db\"\nuniversity_db = \"./data/university.db\"\n\n#################################\n# TODO write all your query here\n#################################\nquery_1 = \"\"\"select name from Student where grade=9 order by name;\"\"\"\nquery_2 =\"\"\"select grade, count(id) from student group by grade order by grade;\"\"\"\nquery_3 =\"\"\"select s.name, s.grade from student as s, friend as f where s.ID=f.ID1 group by ID having count(f.ID1)>2 order by name, grade;\"\"\"\nquery_4 =\"\"\"select s1.name, s1.grade from student as s1 where s1.id IN(Select l.id2 from likes as l, student as s2 where l.id1=s2.id and s2.grade>s1.grade) order by s1.name, s1.grade;\"\"\"\nquery_5=\"\"\"Select name, grade from student where id not in (Select lid1 from(select likes.id1 as lid1, likes.id2 as lid2 from likes except select friend.id1 as fid1, friend.id2 as fid2 from friend))order by name,grade;\"\"\"\nquery_6=\"\"\"select s1.id,s1.name,s2.id,s2.name from student as s1,student as s2,(select likes.ID1 as lid1,likes.ID2 as lid2 from likes except select friend.ID1 as fid1,friend.ID2 as fid2 from friend) where s1.id = lid1 and s2.id=lid2 order by s1.id ,s2.id ;\"\"\"\nquery_7=\"\"\"select s1.id,s1.name,s2.id,s2.name,s3.id,s3.name from student as s1,student as s2,student as s3, (select lid1,lid2,friend.ID2 as f3 from (select likes.ID1 as lid1,likes.ID2 as lid2 from likes except select friend.ID1 as fid1,friend.ID2 as fid2 from friend),friend where lid1=friend.id1 INTERSECT select lid1,lid2,friend.ID2 as f3 from (select likes.ID1 as lid1,likes.ID2 as lid2 from likes except select friend.ID1 as fid1,friend.ID2 as fid2 from friend),friend where lid2=friend.id1) where s1.id=lid1 and s2.id=lid2 and s3.id=f3 order by s1.id asc,s2.id,s3.id;\"\"\"\nquery_8=\"\"\"select distinct p.aid, p.aname, p.bid, p.bname, p.cid, p.cname from (select s1.id as aid, s1.name as aname, s2.id as bid, s2.name as bname, s3.id as cid, s3.name as cname from student as s1, student as s2, student as s3, friend as f1, friend as f2, friend as f3, friend as f4, student as s4 where s1.id=f1.id1 and s2.id=f1.id2 and s1.id=f2.id1 and s3.id=f2.id2 and s2.id=f3.id1 and s3.id=f3.id2 and s1.id=f4.id1 and s4.id<>f4.id2 and s1.id>s2.id and s2.id>s3.id) as p left join (select s1.id as did, s1.name as dname, s2.id as eid, s2.name as ename, s3.id as gid, s3.name as gname, s4.id as fid,s4.name as fname from student as s1, student as s2, student as s3, friend as f1, friend as f2, friend as f3, friend as f4, friend as f5, student as s4 where s1.id=f1.id1 and s2.id=f1.id2 and s1.id=f2.id1 and s3.id=f2.id2 and s2.id=f3.id1 and s3.id=f3.id2 and s2.id=f4.id1 and s4.id=f4.id2 and s3.id=f5.id1 and s4.id=f5.id2) as q order by p.aid,p.bid,p.cid; \"\"\"\nquery_9=\"\"\"Select d.tenured, avg(f.class_score) from Dim_Professor as d,Fact_Course_Evaluation as f where f.professor_id=d.id group by d.tenured;\"\"\"\nquery_10=\"\"\"Select avg(f.class_score), d.area,dt.year from Fact_Course_Evaluation as f, Dim_Type as d, Dim_Term as dt where f.type_id=d.id and f.term_id=dt.id group by d.area,dt.year order by dt.year,d.area;\"\"\"\nquery_11=\"\"\"select a.row_num, b.col_num,SUM(a.value * b.value) from a,b where a.col_num = b.row_num group by a.row_num,b.col_num;\"\"\"\n\n################################################################################\n\ndef get_query_list():\n \"\"\"\n Form a query list for all the queries above\n \"\"\"\n query_list = []\n ## TODO change query number here\n for index in range(1,12):\n eval(\"query_list.append(query_\" + str(index) + \")\")\n # end for\n return query_list\n pass\n\ndef output_result(index, result):\n \"\"\"\n Output the result of query to facilitate autograding.\n Caution!! Do not change this method\n \"\"\"\n with open(netid, 'a') as fout:\n fout.write(\"<\"+str(index)+\">\\n\")\n with open(netid, 'a') as fout:\n for item in result:\n fout.write(str(item))\n fout.write('\\n')\n #end for\n #end with\n with open(netid, 'a') as fout:\n fout.write(\"</\"+str(index) + \">\\n\")\n pass\ndef run():\n ## get all the query list\n query_list = get_query_list()\n\n ## problem 1\n conn = sqlite3.connect(social_db)\n cur = conn.cursor()\n for index in range(0, 8): # TODO query 1-8 for problem 1\n cur.execute(query_list[index])\n result = cur.fetchall()\n tag = \"q\" + str(index+1)\n output_result(tag, result)\n\n ## problem 2\n conn = sqlite3.connect(university_db)\n cur = conn.cursor()\n for index in range(8,10): # TODO query 9-10 for problem 2\n cur.execute(query_list[index])\n result = cur.fetchall()\n tag = \"q\" + str(index+1)\n output_result(tag, result)\n\n ## problem 3\n conn = sqlite3.connect(matrix_db)\n cur = conn.cursor()\n for index in range(10,11): # TODO query 11 for problem 3\n cur.execute(query_list[index])\n result = cur.fetchall()\n tag = \"q\" + str(index+1)\n output_result(tag, result)\n\n\n #end for\n ## TODO problem 2\n ## TODO problem 3\n #end run()\n\n\nif __name__ == '__main__':\n run()" } ]
1
NOAA-PSL/COARE-algorithm
https://github.com/NOAA-PSL/COARE-algorithm
a5ca7b26ff2cfd9c1bdc33dd4f9154df7604d6e6
5b144cf6376a98b42200196d57ae40d791494abe
ffa741ae668675e2b7a2b8e96a00429fc825e218
refs/heads/master
2023-04-17T05:30:14.654760
2022-10-11T19:39:50
2022-10-11T19:39:50
287,338,950
6
7
MIT
2020-08-13T17:18:55
2023-07-12T07:08:32
2023-08-18T11:07:48
Fortran
[ { "alpha_fraction": 0.6690544486045837, "alphanum_fraction": 0.7156160473823547, "avg_line_length": 22.644067764282227, "blob_id": "e9142b07fcdace30b85822798b5f10ed359bd98a", "content_id": "df97310bff4a2903f18ca2a39fe2fc770795d8b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1396, "license_type": "permissive", "max_line_length": 102, "num_lines": 59, "path": "/Fortran/COARE3.0/f90/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "Programs:\n*\tcor3_0af.F90: this version is set up to use the Fairall near-surface temperature sensor for Ts bulk.\n*\tcor3_0ah.F90: this version is setup to use the MSP 6m-depth temperature sensor for Ts bulk.\n\nInput data:\n*\ttest3_0.txt (Test data)\n\n1\tDate: YYYYMMDDHHmmss.ss, YYYY=year, MM=month, DD=day, HH=hour, mm=minute,ss.ss=sec\n\n2\tU: true wind speed at 15-m height m/s corrected for surface currents\n\n3\tTsea: sea surface temp (at about 0.05m depth) deg.C\n\n4\tTair: Vaisala air temperature (about 15 m) deg.C\n\n5\tqair: Vaisala air specific humidity (about 15 m) g/kg\n\n6\tRs: solar irradiance W/m2\n\n7\tRl: downwelling longwave irradiance W/m2\n\n8\tRain: precipitation mm/hr\n\n9\tLat: Latitude (N=+)\n\n10\tLon: Longitude (E=+)\n\n11\tMSP: MSP temperature at 6m depth deg.C\n\n\nOutput files:\n*\ttst3_0af_out.txt and tst3_0ah_out.txt\t\t\t\tMatlab output file from test data \n\n\n1\tindex:\tdata line number\n\n2\txtime:\tYYYYMMDDHHmmss, date and time as read in (without dec. sec.)\n\n3\thf:\tsensible heat flux W/m2\n\n4\tef:\tlatent heat flux W/m2\n\n5\tsst:\tsea skin temperature deg.C\n\n6\ttau:\tsurface stress N/m2\n\n7\tWbar:\tmean Webb vertical velocity m/s\n\n8\trf:\tsensible heat flux due to precipitation W/m2\n\n9\tdter:\tcool skin effect deg.C\n\n10\tdt_wrm: warming across entire warm layer deg.C\n\n11\ttk_pwp:warm layer thickness m\n\n12\ttkt*1000:tkt=cool skin thickness\n\n13\tWg:\tgustiness velocity m/s\n\n" }, { "alpha_fraction": 0.7323688864707947, "alphanum_fraction": 0.7739602327346802, "avg_line_length": 183, "blob_id": "ddf7b52be0963eb6c59ac4b8f102d7eccdb96efe", "content_id": "96a649994e902c6509fa7c351f2d41e3e5fb8a2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 553, "license_type": "permissive", "max_line_length": 483, "num_lines": 3, "path": "/Python/COARE3.5/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "Python implementation of COARE air/sea flux algorithm version 3.5.\n\nThe python code runs the same data set used to exercise the matlab code. Execute '%run coare35vn.py' from the iPython command line for test run with 'test_35_data.txt' input data file. Edit line 554 to indicate path to test data file. This will output a file of results that you can compare to the test_35_output_py_082020.txt provided. The file contains a time series of flux variables (usr\ttau\thsb\thlb\thlwebb\ttsr\tqsr\tzot\tzoq\tCd\tCh\tCe\tL\tzet\tdter\tdqer\ttkt\tRF\tCdn_10\tChn_10\tCen_10 ).\n\n" }, { "alpha_fraction": 0.6520270109176636, "alphanum_fraction": 0.7466216087341309, "avg_line_length": 41, "blob_id": "cbff79e5162c34e469ba273842c72414c1c7548d", "content_id": "f42586e16a5d033e9e4f5580205dab0fadf3a130", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 296, "license_type": "permissive", "max_line_length": 136, "num_lines": 7, "path": "/Fortran/COARE3.6/run_test.bash", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho \"Running test_coare_36, driven by test cases in test_35_data.txt\"\n\nrm -f *mod *.o test_coare_36\nifort -no-wrap-margin -o test_coare_36 machine.f90 physcons.F90 module_coare36_parameters.f90 module_coare36_model.f90 test_coare_36.f90\nnice ./test_coare_36 > log_coare_36_output\n\n\n" }, { "alpha_fraction": 0.7504302859306335, "alphanum_fraction": 0.7728055119514465, "avg_line_length": 95.83333587646484, "blob_id": "1d92192ebd8e62010bcff5688d30fd49303f7589", "content_id": "4e052a44f173ce6539a61b32101cafea54cccbbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 581, "license_type": "permissive", "max_line_length": 271, "num_lines": 6, "path": "/Matlab/COARE3.6/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "'coare36bvnWarm_et.m' is the main program. It calls the 'coare36bvn_zrf_et.m' function. \n'et' refers to Elizabeth Thompson contribution who has edited the code for some typos and \nadded more comment so it is more reader friendly.\n\nMeanwhile Chris made a new analytical cool skin function 'dcoolf2.m' and the version has \nevolved to 'coare36vn_zrf_et_cs.m'. 'cs' is for coolskin. The codes are present in the experimental coolskin folder for reference. Replace 'coare36bvn_zrf_et.m' by 'coare36bvn_zrf_et_cs.m' in 'coare36bvnWarm_et.m' if you want to use the new experimental coolskin scheme.\n" }, { "alpha_fraction": 0.5059176683425903, "alphanum_fraction": 0.5541110038757324, "avg_line_length": 11.95816421508789, "blob_id": "b302496bb9da0f340c57666319ac52b25778dabc", "content_id": "887b738ef182c8611c9d3f0c86580fc21aec1aaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22306, "license_type": "permissive", "max_line_length": 80, "num_lines": 1721, "path": "/Python/COARE3.5/coare35vn.py", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\r\r\rFunctions for COARE model bulk flux calculations.\r\r\r\r\r\rTranslated and vectorized from J Edson/ C Fairall MATLAB scripts.\r\r\r\r\r\rExecute '%run coare35vn.py' from the iPython command line for test run with\r\r\r'test_35_data.txt' input data file.\r\r\r\r\r\rByron Blomquist, CU/CIRES, NOAA/ESRL/PSD3\rLudovic Bariteau, CU/CIRES, NOAA/ESRL/PSD3\rv1: May 2015\rv2: July 2020. Fixed some typos and changed syntax for python 3.7 compatibility.\r\r\r\r\"\"\"\r\r\r\r\r\rdef coare35vn(u, t, rh, ts, P=1015, Rs=150, Rl=370, zu=18, zt=18, zq=18, lat=45,\r\r\r zi=600, rain=None, cp=None, sigH=None, jcool=1):\r\r\r \"\"\"\r\r\r usage: A = coare35vn(u, t, rh, ts) - include other kwargs as desired\r\r\r\r\r\r Vectorized version of COARE 3 code (Fairall et al, 2003) with modification\r\r\r based on the CLIMODE, MBL and CBLAST experiments (Edson et al., 2013).\r\r\r The cool skin option is retained but warm layer and surface wave options\r\r\r have been removed.\r\r\r\r\r\r This version includes parameterizations of wave height and wave slope using\r\r\r cp and sigH. Unless these are provided the wind speed dependent formulation\r\r\r is used.\r\r\r\r\r\r AN IMPORTANT COMPONENT OF THIS CODE IS WHETHER INPUT 'ts' REPRESENTS\r\r\r THE SKIN TEMPERATURE OR A NEAR SURFACE TEMPERATURE. How this variable is\r\r\r treated is determined by the jcool parameter: jcool=1 if Ts is bulk\r\r\r ocean temperature (default), jcool=0 if Ts is ocean skin temperature.\r\r\r\r\r\r The code assumes u, t, rh, and ts are vectors; rain, if given, is a vector;\r\r\r P, Rs, Rl, lat, zi, cp and sigH may be passed as vectors or constants;\r\r\r sensor heights (zu, zt, zq) are only constants. All vectors must be of\r\r\r equal length.\r\r\r\r\r\r Default values are assigned for all variables except u,t,rh,ts. Input\r\r\r arrays may contain NaNs to indicate missing values. Defaults should be set\r\r\r to representative regional values if possible.\r\r\r\r\r\r Input definitions:\r\r\r\r\r\r u = ocean surface relative wind speed (m/s) at height zu(m)\r\r\r t = bulk air temperature (degC) at height zt(m)\r\r\r rh = relative humidity (%) at height zq(m)\r\r\r ts = sea water temperature (degC) - see jcool below\r\r\r P = surface air pressure (mb) (default = 1015)\r\r\r Rs = downward shortwave radiation (W/m^2) (default = 150)\r\r\r Rl = downward longwave radiation (W/m^2) (default = 370)\r\r\r zu = wind sensor height (m) (default = 18m)\r\r\r zt = bulk temperature sensor height (m) (default = 18m)\r\r\r zq = RH sensor height (m) (default = 18m)\r\r\r lat = latitude (default = 45 N)\r\r\r zi = PBL height (m) (default = 600m)\r\r\r rain = rain rate (mm/hr)\r\r\r cp = phase speed of dominant waves (m/s)\r\r\r sigH = significant wave height (m)\r\r\r jcool = cool skin option (default = 1 for bulk SST)\r\r\r\r\r\r Output is a 2-D ndarray with the following variables as 37 columns.\r\r\r Other quantities may be added to output by editing lines 536/537.\r\r\r\r\r\r col var description\r\r\r -------------------------------------------------------------------------\r\r\r 0 usr friction velocity that includes gustiness (m/s)\r\r\r 1 tau wind stress (N/m^2)\r\r\r 2 hsb sensible heat flux into ocean (W/m^2)\r\r\r 3 hlb latent heat flux into ocean (W/m^2)\r\r\r 4 hbb buoyancy flux into ocean (W/m^2)\r\r\r 5 hsbb \"sonic\" buoyancy flux measured directly by sonic anemometer\r\r\r 6 hlwebb Webb correction for latent heat flux, add this to directly\r\r\r measured eddy covariance latent heat flux from water vapor\r\r\r mass concentration sensors (e.g. Licor 7500).\r\r\r 7 tsr temperature scaling parameter (K)\r\r\r 8 qsr specific humidity scaling parameter (g/Kg)\r\r\r 9 zot thermal roughness length (m)\r\r\r 10 zoq moisture roughness length (m)\r\r\r 11 Cd wind stress transfer (drag) coefficient at height zu\r\r\r 12 Ch sensible heat transfer coefficient (Stanton number) at ht zu\r\r\r 13 Ce latent heat transfer coefficient (Dalton number) at ht zq\r\r\r 14 L Obukhov length scale (m)\r\r\r 15 zet Monin-Obukhov stability parameter zu/L\r\r\r 16 dter cool-skin temperature depression (degC)\r\r\r 17 dqer cool-skin humidity depression (degC)\r\r\r 18 tkt cool-skin thickness (m)\r\r\r 19 Urf wind speed at reference height (user can select height below)\r\r\r 20 Trf temperature at reference height\r\r\r 21 Qrf specific humidity at reference height\r\r\r 22 RHrf relative humidity at reference height\r\r\r 23 UrfN neutral value of wind speed at reference height\r\r\r 24 Rnl Upwelling IR radiation computed by COARE\r\r\r 25 Le latent heat of vaporization\r\r\r 26 rhoa density of air\r\r\r 27 UN neutral value of wind speed at zu\r\r\r 28 U10 wind speed adjusted to 10 m\r\r\r 29 U10N neutral value of wind speed at 10m\r\r\r 30 Cdn_10 neutral value of drag coefficient at 10m\r\r\r 31 Chn_10 neutral value of Stanton number at 10m\r\r\r 32 Cen_10 neutral value of Dalton number at 10m\r\r\r 33 RF rain heat flux (W/m2)\r\r\r 34 Evap evaporation (mm/hr)\r\r\r 35 Qs sea surface specific humidity (g/kg)\r\r\r 36 Q10 specific humidity at 10m (g/kg)\r\r\r 37 RH10 RH at 10m (%)\r\r\r\r\r\r Notes:\r\r\r 1) u is the ocean-relative wind speed, i.e., the magnitude of the\r\r\r difference between the wind (at zu) and ocean surface current\r\r\r vectors.\r\r\r 2) Set jcool=0 if ts is true surface skin temperature,\r\r\r otherwise ts is assumed the bulk temperature and jcool=1.\r\r\r 3) The code to compute the heat flux caused by precipitation is\r\r\r included if rain data is available (default is no rain).\r\r\r 4) Code updates the cool-skin temperature depression dter and thickness\r\r\r tkt during iteration loop for consistency.\r\r\r 5) Number of iterations set to nits = 6.\r\r\r 6) The warm layer is not implemented in this version.\r\r\r\r\r\r Reference:\r\r\r\r\r\r Fairall, C.W., E.F. Bradley, J.E. Hare, A.A. Grachev, and J.B. Edson (2003),\r\r\r Bulk parameterization of air sea fluxes: updates and verification for the\r\r\r COARE algorithm, J. Climate, 16, 571-590.\r\r\r\r\r\r Code history:\r\r\r\r\r\r 1) 12/14/05 - created based on scalar version coare26sn.m with input\r\r\r on vectorization from C. Moffat.\r\r\r 2) 12/21/05 - sign error in psiu_26 corrected, and code added to use\r\r\r variable values from the first pass through the iteration loop for the\r\r\r stable case with very thin M-O length relative to zu (zetu>50) (as is\r\r\r done in the scalar coare26sn and COARE3 codes).\r\r\r 3) 7/26/11 - S = dt was corrected to read S = ut.\r\r\r 4) 7/28/11 - modification to roughness length parameterizations based\r\r\r on the CLIMODE, MBL, Gasex and CBLAST experiments are incorporated\r\r\r 5) Python translation by BWB, Oct 2014. Modified to allow user specified\r\r\r vectors for lat and zi. Defaults added for zu, zt, zq.\r\r\r \"\"\"\r\r\r\r\r\r import numpy as np\r\r\r import meteo\r\r\r import util\r\r\r\r\r\r # be sure array inputs are ndarray floats\r\r\r # if inputs are already ndarray float this does nothing\r\r\r # otherwise copies are created in the local namespace\r\r\r u = np.copy(np.asarray(u, dtype=float))\r\r\r t = np.copy(np.asarray(t, dtype=float))\r\r\r rh = np.copy(np.asarray(rh, dtype=float))\r\r\r ts = np.copy(np.asarray(ts, dtype=float))\r\r\r # these default to 1 element arrays\r\r\r P = np.copy(np.asarray(P, dtype=float))\r\r\r Rs = np.copy(np.asarray(Rs, dtype=float))\r\r\r Rl = np.copy(np.asarray(Rl, dtype=float))\r\r\r zi = np.copy(np.asarray(zi, dtype=float))\r\r\r lat = np.copy(np.asarray(lat, dtype=float))\r\r\r\r\r\r # check for mandatory input variable consistency\r\r\r len = u.size\r\r\r if not np.all([t.size==len, rh.size==len, ts.size==len]):\r\r\r raise ValueError ('coare35vn: u, t, rh, ts arrays of different length')\r\r\r\r\r\r # format optional array inputs\r\r\r if P.size != len and P.size != 1:\r\r\r raise ValueError ('coare35vn: P array of different length')\r\r\r elif P.size == 1:\r\r\r P = P * np.ones(len)\r\r\r\r\r\r if Rl.size != len and Rl.size != 1:\r\r\r raise ValueError ('coare35vn: Rl array of different length')\r\r\r elif Rl.size == 1:\r\r\r Rl = Rl * np.ones(len)\r\r\r\r\r\r if Rs.size != len and Rs.size != 1:\r\r\r raise ValueError ('coare35vn: Rs array of different length')\r\r\r elif Rs.size == 1:\r\r\r Rs = Rs * np.ones(len)\r\r\r\r\r\r if zi.size != len and zi.size != 1:\r\r\r raise ValueError ('coare35vn: zi array of different length')\r\r\r elif zi.size == 1:\r\r\r zi = zi * np.ones(len)\r\r\r\r\r\r if lat.size != len and lat.size != 1:\r\r\r raise ValueError ('coare35vn: lat array of different length')\r\r\r elif lat.size == 1:\r\r\r lat = lat * np.ones(len)\r\r\r\r\r\r if rain is not None:\r\r\r rain = np.asarray(rain, dtype=float)\r\r\r if rain.size != len:\r\r\r raise ValueError ('coare35vn: rain array of different length')\r\r\r\r\r\r if cp is not None:\r\r\r waveage_flag = True\r\r\r cp = np.copy(np.asarray(cp, dtype=float))\r\r\r if cp.size != len:\r\r\r raise ValueError ('coare35vn: cp array of different length')\r\r\r elif cp.size == 1:\r\r\r cp = cp * np.ones(len)\r\r\r else:\r\r\r waveage_flag = False\r\r\r cp = np.nan * np.ones(len)\r\r\r\r\r\r if sigH is not None:\r\r\r seastate_flag = True\r\r\r sigH = np.copy(np.asarray(sigH, dtype=float))\r\r\r if sigH.size != len:\r\r\r raise ValueError ('coare35vn: sigH array of different length')\r\r\r elif sigH.size == 1:\r\r\r sigH = sigH * np.ones(len)\r\r\r else:\r\r\r seastate_flag = False\r\r\r sigH = np.nan * np.ones(len)\r\r\r\r\r\r if waveage_flag and seastate_flag:\r\r\r print ('Using seastate dependent parameterization')\r\r\r\r\r\r if waveage_flag and not seastate_flag:\r\r\r print ('Using waveage dependent parameterization')\r\r\r\r\r\r # check jcool\r\r\r if jcool != 0:\r\r\r jcool = 1 # all input other than 0 defaults to jcool=1\r\r\r\r\r\r # check sensor heights\r\r\r test = [type(zu) is int or type(zu) is float]\r\r\r test.append(type(zt) is int or type(zt) is float)\r\r\r test.append(type(zq) is int or type(zq) is float)\r\r\r if not np.all(test):\r\r\r raise ValueError ('coare35vn: zu, zt, zq, should be constants')\r\r\r zu = zu * np.ones(len)\r\r\r zt = zt * np.ones(len)\r\r\r zq = zq * np.ones(len)\r\r\r\r\r\r # input variable u is surface relative wind speed (magnitude of difference\r\r\r # between wind and surface current vectors). To follow orginal Fairall\r\r\r # code, we set surface current speed us=0. If us data are available\r\r\r # construct u prior to using this code.\r\r\r us = np.zeros(len)\r\r\r\r\r\r # convert rh to specific humidity\r\r\r Qs = meteo.qsea(ts,P)/1000.0 # surface water specific humidity (kg/kg)\r\r\r Q, Pv = meteo.qair(t,P,rh) # specific hum. and partial Pv (mb)\r\r\r Q /= 1000.0 # Q (kg/kg)\r\r\r\r\r\r # set constants\r\r\r zref = 10. # ref height, m (edit as desired)\r\r\r Beta = 1.2\r\r\r von = 0.4 # von Karman const\r\r\r fdg = 1.00 # Turbulent Prandtl number\r\r\r tdk = 273.16\r\r\r grav = meteo.grv(lat)\r\r\r\r\r\r # air constants\r\r\r Rgas = 287.1\r\r\r Le = (2.501 - 0.00237*ts) * 1e6\r\r\r cpa = 1004.67\r\r\r cpv = cpa * (1 + 0.84*Q)\r\r\r rhoa = P*100. / (Rgas * (t + tdk) * (1 + 0.61*Q))\r\r\r rhodry = (P - Pv)*100. / (Rgas * (t + tdk))\r\r\r visa = 1.326e-5 * (1 + 6.542e-3*t + 8.301e-6*t**2 - 4.84e-9*t**3)\r\r\r\r\r\r # cool skin constants\r\r\r Al = 2.1e-5 * (ts + 3.2)**0.79\r\r\r be = 0.026\r\r\r cpw = 4000.\r\r\r rhow = 1022.\r\r\r visw = 1.e-6\r\r\r tcw = 0.6\r\r\r bigc = 16. * grav * cpw * (rhow * visw)**3 / (tcw**2 * rhoa**2)\r\r\r wetc = 0.622 * Le * Qs / (Rgas * (ts + tdk)**2)\r\r\r\r\r\r # net radiation fluxes\r\r\r Rns = 0.945 * Rs #albedo correction\r\r\r # IRup = eps * sigma*T**4 + (1 - eps)*IR\r\r\r # Rnl = IRup - IR\r\r\r # Rnl = eps * sigma*T**4 - eps*IR as below\r\r\r Rnl = 0.97 * (5.67e-8 * (ts - 0.3*jcool + tdk)**4 - Rl) # initial value\r\r\r # IRup = Rnl + IR\r\r\r\r\r\r ##### BEGIN BULK LOOP\r\r\r\r\r\r # first guess\r\r\r du = u - us\r\r\r dt = ts - t - 0.0098*zt\r\r\r dq = Qs - Q\r\r\r ta = t + tdk\r\r\r ug = 0.5\r\r\r dter = 0.3\r\r\r ut = np.sqrt(du**2 + ug**2)\r\r\r u10 = ut * np.log(10/1e-4) / np.log(zu/1e-4)\r\r\r usr = 0.035 * u10\r\r\r zo10 = 0.011 * usr**2 / grav + 0.11*visa / usr\r\r\r Cd10 = (von / np.log(10/zo10))**2\r\r\r Ch10 = 0.00115\r\r\r Ct10 = Ch10 / np.sqrt(Cd10)\r\r\r zot10 = 10 / np.exp(von/Ct10)\r\r\r Cd = (von / np.log(zu/zo10))**2\r\r\r Ct = von / np.log(zt/zot10)\r\r\r CC = von * Ct/Cd\r\r\r Ribcu = -zu / zi / 0.004 / Beta**3\r\r\r Ribu = -grav * zu/ta * ((dt - dter*jcool) + 0.61*ta*dq) / ut**2\r\r\r zetu = CC * Ribu * (1 + 27/9 * Ribu/CC)\r\r\r\r\r\r k50 = util.find(zetu > 50) # stable with thin M-O length relative to zu\r\r\r\r\r\r k = util.find(Ribu < 0)\r\r\r if Ribcu.size == 1:\r\r\r zetu[k] = CC[k] * Ribu[k] / (1 + Ribu[k] / Ribcu)\r\r\r else:\r\r\r zetu[k] = CC[k] * Ribu[k] / (1 + Ribu[k] / Ribcu[k])\r\r\r\r\r\r L10 = zu / zetu\r\r\r gf = ut / du\r\r\r usr = ut * von / (np.log(zu/zo10) - meteo.psiu_40(zu/L10))\r\r\r tsr = -(dt - dter*jcool)*von*fdg / (np.log(zt/zot10) -\r\r\r meteo.psit_26(zt/L10))\r\r\r qsr = -(dq - wetc*dter*jcool)*von*fdg / (np.log(zq/zot10) -\r\r\r meteo.psit_26(zq/L10))\r\r\r tkt = 0.001 * np.ones(len)\r\r\r\r\r\r # The following gives the new formulation for the Charnock variable\r\r\r\r\r\r charnC = 0.011 * np.ones(len)\r\r\r umax = 19\r\r\r a1 = 0.0017\r\r\r a2 = -0.0050\r\r\r\r\r\r charnC = a1 * u10 + a2\r\r\r j = util.find(u10 > umax)\r\r\r charnC[j] = a1 * umax + a2\r\r\r\r\r\r A = 0.114 # wave-age dependent coefficients\r\r\r B = 0.622\r\r\r\r\r\r Ad = 0.091 # Sea-state/wave-age dependent coefficients\r\r\r Bd = 2.0\r\r\r\r\r\r charnW = A * (usr/cp)**B\r\r\r zoS = sigH * Ad * (usr/cp)**Bd\r\r\r charnS = zoS * grav / usr / usr\r\r\r\r\r\r charn = 0.011 * np.ones(len)\r\r\r k = util.find(ut > 10)\r\r\r charn[k] = 0.011 + (ut[k] - 10) / (18 - 10)*(0.018 - 0.011)\r\r\r k = util.find(ut > 18)\r\r\r charn[k] = 0.018\r\r\r\r\r\r # begin bulk loop\r\r\r nits = 10 # number of iterations\r\r\r for i in range(nits):\r\r\r zet = von*grav*zu / ta*(tsr + 0.61*ta*qsr) / (usr**2)\r\r\r if waveage_flag:\r\r\r if seastate_flag:\r\r\r charn = charnS\r\r\r else:\r\r\r charn = charnW\r\r\r else:\r\r\r charn = charnC\r\r\r\r\r\r L = zu / zet\r\r\r zo = charn*usr**2/grav + 0.11*visa/usr # surface roughness\r\r\r rr = zo*usr/visa\r\r\r # thermal roughness lengths give Stanton and Dalton numbers that\r\r\r # closely approximate COARE 3.0\r\r\r zoq = np.minimum(1.6e-4, 5.8e-5/rr**0.72)\r\r\r zot = zoq\r\r\r cdhf = von / (np.log(zu/zo) - meteo.psiu_26(zu/L))\r\r\r cqhf = von*fdg / (np.log(zq/zoq) - meteo.psit_26(zq/L))\r\r\r cthf = von*fdg / (np.log(zt/zot) - meteo.psit_26(zt/L))\r\r\r usr = ut*cdhf\r\r\r qsr = -(dq - wetc*dter*jcool)*cqhf\r\r\r tsr = -(dt - dter*jcool)*cthf\r\r\r tvsr = tsr + 0.61*ta*qsr\r\r\r tssr = tsr + 0.51*ta*qsr\r\r\r Bf = -grav / ta*usr*tvsr\r\r\r ug = 0.2 * np.ones(len)\r\r\r\r\r\r k = util.find(Bf > 0)\r\r\r if zi.size == 1:\r\r\r ug[k] = Beta*(Bf[k]*zi)**0.333\r\r\r else:\r\r\r ug[k] = Beta*(Bf[k]*zi[k])**0.333\r\r\r\r\r\r ut = np.sqrt(du**2 + ug**2)\r\r\r gf = ut/du\r\r\r hsb = -rhoa*cpa*usr*tsr\r\r\r hlb = -rhoa*Le*usr*qsr\r\r\r qout = Rnl + hsb + hlb\r\r\r dels = Rns * (0.065 + 11*tkt - 6.6e-5/tkt*(1 - np.exp(-tkt/8.0e-4)))\r\r\r qcol = qout - dels\r\r\r alq = Al*qcol + be*hlb*cpw/Le\r\r\r xlamx = 6.0 * np.ones(len)\r\r\r tkt = np.minimum(0.01, xlamx*visw/(np.sqrt(rhoa/rhow)*usr))\r\r\r k = util.find(alq > 0)\r\r\r xlamx[k] = 6/(1 + (bigc[k]*alq[k]/usr[k]**4)**0.75)**0.333\r\r\r tkt[k] = xlamx[k]*visw / (np.sqrt(rhoa[k]/rhow)*usr[k])\r\r\r dter = qcol*tkt/tcw\r\r\r dqer = wetc*dter\r\r\r Rnl = 0.97*(5.67e-8*(ts - dter*jcool + tdk)**4 - Rl) # update dter\r\r\r\r\r\r # save first iteration solution for case of zetu>50\r\r\r if i == 0:\r\r\r usr50 = usr[k50]\r\r\r tsr50 = tsr[k50]\r\r\r qsr50 = qsr[k50]\r\r\r L50 = L[k50]\r\r\r zet50 = zet[k50]\r\r\r dter50 = dter[k50]\r\r\r dqer50 = dqer[k50]\r\r\r tkt50 = tkt[k50]\r\r\r\r\r\r u10N = usr/von/gf*np.log(10/zo)\r\r\r charnC = a1*u10N + a2\r\r\r k = util.find(u10N > umax)\r\r\r charnC[k] = a1*umax + a2\r\r\r charnW = A*(usr/cp)**B\r\r\r zoS = sigH*Ad*(usr/cp)**Bd - 0.11*visa/usr\r\r\r charnS = zoS*grav/usr/usr\r\r\r\r\r\r # end bulk loop\r\r\r\r\r\r # insert first iteration solution for case with zetu > 50\r\r\r usr[k50] = usr50\r\r\r tsr[k50] = tsr50\r\r\r qsr[k50] = qsr50\r\r\r L[k50] = L50\r\r\r zet[k50] = zet50\r\r\r dter[k50] = dter50\r\r\r dqer[k50] = dqer50\r\r\r tkt[k50] = tkt50\r\r\r\r\r\r # compute fluxes\r\r\r tau = rhoa*usr*usr/gf # wind stress\r\r\r hsb = -rhoa*cpa*usr*tsr # sensible heat flux\r\r\r hlb = -rhoa*Le*usr*qsr # latent heat flux\r\r\r hbb = -rhoa*cpa*usr*tvsr # buoyancy flux\r\r\r hsbb = -rhoa*cpa*usr*tssr # sonic buoyancy flux\r\r\r wbar = 1.61*hlb/Le/(1+1.61*Q)/rhoa + hsb/rhoa/cpa/ta\r\r\r hlwebb = rhoa*wbar*Q*Le\r\r\r Evap = 1000*hlb/Le/1000*3600 # mm/hour\r\r\r\r\r\r # compute transfer coeffs relative to ut @ meas. ht\r\r\r Cd = tau/rhoa/ut/np.maximum(0.1,du)\r\r\r Ch = -usr*tsr/ut/(dt - dter*jcool)\r\r\r Ce = -usr*qsr/(dq - dqer*jcool)/ut\r\r\r\r\r\r # compute 10-m neutral coeff relative to ut\r\r\r Cdn_10 = 1000*von**2 / np.log(10/zo)**2\r\r\r Chn_10 = 1000*von**2 * fdg/np.log(10/zo) / np.log(10/zot)\r\r\r Cen_10 = 1000*von**2 * fdg/np.log(10/zo) / np.log(10/zoq)\r\r\r\r\r\r # compute the stability functions\r\r\r zrf_u = 10 # User defined reference heights\r\r\r zrf_t = 10\r\r\r zrf_q = 10\r\r\r psi = meteo.psiu_26(zu/L)\r\r\r psi10 = meteo.psiu_26(10/L)\r\r\r psirf = meteo.psiu_26(zrf_u/L)\r\r\r psiT = meteo.psit_26(zt/L)\r\r\r psi10T = meteo.psit_26(10/L)\r\r\r psirfT = meteo.psit_26(zrf_t/L)\r\r\r psirfQ = meteo.psit_26(zrf_q/L)\r\r\r gf = ut/du\r\r\r\r\r\r # Determine the wind speeds relative to ocean surface\r\r\r # Note that usr is the friction velocity that includes\r\r\r # gustiness usr = sqrt(Cd) S, which is equation (18) in\r\r\r # Fairall et al. (1996)\r\r\r S = ut\r\r\r U = du\r\r\r S10 = S + usr/von*(np.log(10/zu) - psi10 + psi)\r\r\r U10 = S10/gf\r\r\r # or U10 = U + usr/von/gf*(np.log(10/zu) - psi10 + psi)\r\r\r Urf = U + usr/von/gf*(np.log(zrf_u/zu) - psirf + psi)\r\r\r UN = U + psi*usr/von/gf\r\r\r U10N = U10 + psi10*usr/von/gf\r\r\r UrfN = Urf + psirf*usr/von/gf\r\r\r\r\r\r UN2 = usr/von/gf * np.log(zu/zo)\r\r\r U10N2 = usr/von/gf * np.log(10/zo)\r\r\r UrfN2 = usr/von/gf * np.log(zrf_u/zo)\r\r\r\r\r\r # rain heat flux after Gosnell et al., JGR, 1995\r\r\r if rain is None:\r\r\r RF = np.zeros(usr.size)\r\r\r else:\r\r\r # water vapour diffusivity\r\r\r dwat = 2.11e-5*((t + tdk)/tdk)**1.94\r\r\r # heat diffusivity\r\r\r dtmp = (1 + 3.309e-3*t - 1.44e-6*t**2) * 0.02411/(rhoa*cpa)\r\r\r # Clausius-Clapeyron\r\r\r dqs_dt = Q*Le / (Rgas*(t + tdk)**2)\r\r\r # wet bulb factor\r\r\r alfac = 1/(1 + 0.622*(dqs_dt*Le*dwat)/(cpa*dtmp))\r\r\r RF = rain*alfac*cpw*((ts-t-dter*jcool)+(Qs-Q-dqer*jcool)*Le/cpa)/3600\r\r\r\r\r\r lapse = grav/cpa\r\r\r SST = ts - dter*jcool\r\r\r\r\r\r T = t\r\r\r T10 = T + tsr/von*(np.log(10/zt) - psi10T + psiT) + lapse*(zt - 10)\r\r\r Trf = T + tsr/von*(np.log(zrf_t/zt) - psirfT + psiT) + lapse*(zt - zrf_t)\r\r\r TN = T + psiT*tsr/von\r\r\r T10N = T10 + psi10T*tsr/von\r\r\r TrfN = Trf + psirfT*tsr/von\r\r\r\r\r\r TN2 = SST + tsr/von * np.log(zt/zot) - lapse*zt\r\r\r T10N2 = SST + tsr/von * np.log(10/zot) - lapse*10;\r\r\r TrfN2 = SST + tsr/von * np.log(zrf_t/zot) - lapse*zrf_t\r\r\r\r\r\r dqer = wetc*dter*jcool\r\r\r SSQ = Qs - dqer\r\r\r SSQ = SSQ*1000\r\r\r Q = Q*1000\r\r\r qsr = qsr*1000\r\r\r Q10 = Q + qsr/von*(np.log(10/zq) - psi10T + psiT)\r\r\r Qrf = Q + qsr/von*(np.log(zrf_q/zq) - psirfQ + psiT)\r\r\r QN = Q + psiT*qsr/von/np.sqrt(gf)\r\r\r Q10N = Q10 + psi10T*qsr/von\r\r\r QrfN = Qrf + psirfQ*qsr/von\r\r\r\r\r\r QN2 = SSQ + qsr/von * np.log(zq/zoq)\r\r\r Q10N2 = SSQ + qsr/von * np.log(10/zoq)\r\r\r QrfN2 = SSQ + qsr/von * np.log(zrf_q/zoq)\r\r\r RHrf = meteo.rhcalc(Trf, P, Qrf/1000)\r\r\r RH10 = meteo.rhcalc(T10, P, Q10/1000)\r\r\r\r\r\r # output: edit these lists to add other values as desired\r\r\r# list1 = [usr,tau,hsb,hlb,hbb,hsbb,hlwebb,tsr,qsr,zot,zoq,Cd,Ch,Ce,L,zet]\r\r\r# list2 = [dter,dqer,tkt,Urf,Trf,Qrf,RHrf,UrfN,Rnl,Le,rhoa,UN,U10,U10N]\r\r\r# list3 = [Cdn_10,Chn_10,Cen_10,RF,Evap,Qs,Q10,RH10]\r\r\r# out = tuple(list1 + list2 + list3)\r\r\r # basic default output...\r\r\r list1 = [usr,tau,hsb,hlb,hlwebb,tsr,qsr,zot,zoq,Cd,Ch,Ce,L,zet]\r\r\r list2 = [dter,dqer,tkt,RF,Cdn_10,Chn_10,Cen_10]\r\r\r out = tuple(list1 + list2)\r\r\r A = np.column_stack(out)\r\r\r return A\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r# This code executes if 'run coare35vn.py' is executed from iPython cmd line\r\r\r# Edit line 533 to indicate path to test data file\r\r\rif __name__ == '__main__':\r\r\r import numpy as np\r\r\r import os\r\r\r import util\r\r\r import matplotlib.pyplot as plt\r\r\r\r\r\r path = '/Volumes/MyPassport/pyCOARE_NOAA'\r\r\r fil = 'test_35_data.txt'\r\r\r cols = 15\r\r\r data, varNames = util.load_txt_file(path,fil,cols)\r\r\r u = data[:,0]\r\r\r ta = data[:,2]\r\r\r rh = data[:,4]\r\r\r Pa = data[:,6]\r\r\r ts = data[:,7]\r\r\r rs = data[:,8]\r\r\r rl = data[:,9]\r\r\r Lat = data[:,10]\r\r\r ZI = data[:,11]\r\r\r Rain = data[:,12]\r\r\r\r\r\r A = coare35vn(u, ta, rh, ts, P=Pa, Rs=rs, Rl=rl, zu=16, zt=16, zq=16,\r\r\r lat=Lat, zi=ZI, rain=Rain, jcool=1)\r\r\r fnameA = os.path.join(path,'test_35_output_py_082020.txt')\r\r\r A_hdr = 'usr\\ttau\\thsb\\thlb\\thlwebb\\ttsr\\tqsr\\tzot\\tzoq\\tCd\\t'\r\r\r A_hdr += 'Ch\\tCe\\tL\\tzet\\tdter\\tdqer\\ttkt\\tRF\\tCdn_10\\tChn_10\\tCen_10'\r\r\r np.savetxt(fnameA,A,fmt='%.18e',delimiter='\\t',header=A_hdr)\r\r\r\r\r\r" }, { "alpha_fraction": 0.6835047602653503, "alphanum_fraction": 0.7037104964256287, "avg_line_length": 72.56756591796875, "blob_id": "fc74d992acb2db8a9bb46a9ae26174f34aed30c8", "content_id": "0d64f724e5c6776df505e546610efc990b2ae628", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5444, "license_type": "permissive", "max_line_length": 748, "num_lines": 74, "path": "/Python/COARE3.6/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "# Python implementation of COARE air/sea flux algorithm version 3.6.\n\nThis includes functions for bulk flux calculations:\n- Without warm layer computations [coare36vn\\_zrf\\_et.py](https://github.com/noaa-psd/COARE-algorithm/blob/feature/sanAkel/decorated_doc/Python/COARE3.6/coare36vn_zrf_et.py).\n- With warm layer computations [coare36vnWarm\\_et.py](https://github.com/noaa-psd/COARE-algorithm/blob/feature/sanAkel/decorated_doc/Python/COARE3.6/coare36vnWarm_et.py).\n\nThe python codes were translated from the MATLAB scripts. They can be run over the same input data set [test\\_36\\_data.txt](https://github.com/noaa-psd/COARE-algorithm/blob/feature/sanAkel/decorated_doc/Python/COARE3.6/test_36_data.txt) that is used to exercise the MATLAB code. Output with and without wave effects is included in [test\\_36\\_output\\_withwavesinput\\_withwarmlayer.txt](https://github.com/noaa-psd/COARE-algorithm/blob/feature/sanAkel/decorated_doc/Python/COARE3.6/test_36_output_withwavesinput_withwarmlayer.txt) and [test\\_36\\_output\\_withnowavesinput\\_withwarmlayer.txt](https://github.com/noaa-psd/COARE-algorithm/blob/feature/sanAkel/decorated_doc/Python/COARE3.6/test_36_output_withnowavesinput_withwarmlayer.txt) respectively.\n\n## Instructions\n- For the bulk flux calculations without warm layer computations, run: `coare36vn_zrf_et.py` from the iPython command line. Edit line `959` to set path to test data file: `test_36_data.txt`. \n- With warm layer computations, run: `coare36vnWarm_et.py`. Edit line 403 to set path to test data file: `test_36_data.txt`. \n\nDepending if the waves parameters: `cp` and `sigH` are used as input to COARE3.6, this will output a file of results that you can compare to the ones provided (`test_36_output_withnowavesinput_withwarmlayer.txt`, `test_36_output_withwavesinput_withwarmlayer.txt`). \n\n## Sample output\nThis file contains a time series of following variables.\n\n\n| Variable Name | Description | Notes |\n| :------------ | :---------: | ----: |\n| usr | friction velocity that includes gustiness (m/s) | Denoted by u* |\n| tau | wind stress that includes gustiness (N/m^2)| |\n| hsb | sensible heat flux (W/m^2) | positive for $T_{air}$ < $T_{skin}$ |\n| hlb | latent heat flux (W/m^2) | positive for $q_{air} < q_s$\n| hbb | atmospheric buoyany flux (W/m^2) | positive when `hlb` and `hsb` heat the atmosphere |\n| hsbb | atmospheric buoyancy flux from sonic | as above, computed with sonic anemometer `T` |\n| hlwebb | Webb factor to be added to `hl` | covariance and ID latent heat fluxes |\n| tsr | temperature scaling parameter (K) | Denoted by t* | \n| qsr | specific humidity scaling parameter (kg/kg) | Denoted by q* |\n| zo | momentum roughness length (m)| |\n| zot | thermal roughness length (m)| |\n| zoq | moisture roughness length (m)| |\n| Cd | wind stress transfer (drag) coefficient at height zu (unitless)| |\n| Ch |sensible heat transfer coefficient (Stanton number) at height zu (unitless)| |\n| Ce | latent heat transfer coefficient (Dalton number) at height zu (unitless)| |\n| L | Monin-Obukhov length scale (m)\n| zeta | Monin-Obukhov stability parameter zu/L (dimensionless)| |\n| dT_skin | cool-skin temperature depression (degC)| positive value means skin is cooler than subskin|\n| dq_skin | cool-skin humidity depression (g/kg)| |\n| dz_skin | cool-skin thickness (m)| |\n| Urf | wind speed at reference height |user can select height at input |\n| Trf | air temperature at reference height| |\n| Qrf |air specific humidity at reference height| |\n| RHrf | air relative humidity at reference height| |\n| UrfN | neutral value of wind speed at reference height| |\n| TrfN | neutral value of air temp at reference height | |\n| qarfN | neutral value of air specific humidity at reference height | |\n| lw_net | Net IR radiation computed by COARE (W/m2) | positive heating ocean |\n| sw_net | Net solar radiation computed by COARE (W/m2) | positive heating ocean | \n| Le | latent heat of vaporization (J/K)| |\n| rhoa | density of air at input parameter height zt (kg/m3)|typically same as zq |\n| UN | neutral value of wind speed at zu (m/s)| |\n| U10 | wind speed adjusted to 10 m (m/s)| |\n| UN10 | neutral value of wind speed at 10m (m/s)| |\n| Cdn_10 | neutral value of drag coefficient at 10m (unitless)| |\n| Chn_10 | neutral value of Stanton number at 10m (unitless)| |\n| Cen_10 | neutral value of Dalton number at 10m (unitless)| |\n| hrain | rain heat flux (W/m^2) | positive cooling ocean |\n| Qs | sea surface specific humidity, assuming saturation (g/kg)| |\n| Evap | evaporation rate (mm/h)| |\n| T10 | air temperature at 10m (deg C)| |\n| T10N | neutral air temperature at 10m (deg C) | |\n| Q10 | air specific humidity at 10m (g/kg) | |\n| Q10N | neutral air specific humidity at 10m (g/kg) | |\n| RH10 | air relative humidity at 10m (unitless) | |\n| P10 | air pressure at 10m (mb) | |\n| rhoa10 | air density at 10m (kg/m3) | |\n| gust | gustiness velocity (m/s) | |\n| wc_frac | whitecap fraction (ratio) | |\n| Edis | energy dissipated by wave breaking (W/m^2) | |\n| dT_warm | dT from base of warm layer to skin, i.e. warming across entire warm layer depth (deg C) | |\n| dz_warm | warm layer thickness (m) | |\n| dT\\_warm\\_to\\_skin | dT from measurement depth to skin due to warm layer, such that $T_{skin} = T_{sea} + dT_{warm_to_skin} - dT_{skin}$ | |\n| du_warm | total current accumulation in warm layer (m/s) | |\n" }, { "alpha_fraction": 0.777222752571106, "alphanum_fraction": 0.807692289352417, "avg_line_length": 181, "blob_id": "f46461370b80aa8ba8bcabde0ef1049b47322747", "content_id": "0b6bafef29b9be3e78a83f381a80c0af1a2d66b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2002, "license_type": "permissive", "max_line_length": 832, "num_lines": 11, "path": "/Fortran/COARE3.6/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "This repository provides a fortran implementation of the COARE3.6 algorithm for the computation of surface fluxes of momentum, heat and moisture over oceans. Within the file module_coare36_model.f90, the algorithm is implemented in two subroutines:\n - coare36flux_coolskin, which assumes that an ocean bulk temperature is input in ts. This subroutine will compute a skin temperature that accounts for the heating/cooling of the surface by radiative, sensible and latent heat fluxes.\n - coare36flux, assumes that a skin temperature is input in ts and only computes the surface energy fluxes.\n\nThis repository includes several files that have been extracted from a preliminary implementation in NOAA's Unified Forecast System (UFS), and the two model_coare36*f90 files are intended for use in that model.\n\nThe current versions of these files have been verified against a matlab implementation of COARE3.6 in coare36vn_zrf.m. Sample output from the matlab code is provided in test_36_output_matlab_072821.txt. Do note that acceleration due to gravity was fixed at 9.81 m/s2 in that test. The default algorithm allows this to change with latitude.\n\nThe fortran program test_coare_36.f90 is a driver for the test suite in the data file test_35_data.txt. This program may be compiled and run (using the intel compiler) with the script run_test.bash. This program will produce an output file test_36_output_f90coolskin.txt, which may be compared against test_36_output_matlab_072821.txt. An additional matlab script PlotCOARE36Errors.m produces plots of absolute and relative error for many quantities output by the scheme and, optionally, writes them to files in the Figures/ directory. The default version of the algorithm agrees to the matlab version within 1% for most variables. Better agreement can be achieved by decreasing dT_skin_min in module_coare36_parameters.f90 to 1.e-8, which tightens the tolerance for stopping iterations within the (iterative) flux computation.\n\nPeter Blossey, July 2021\n" }, { "alpha_fraction": 0.43128010630607605, "alphanum_fraction": 0.5361279249191284, "avg_line_length": 26.866863250732422, "blob_id": "864af747b53e1f3b02ac2343757b0e920b694495", "content_id": "b73b6aa82743db25cdb662c02ef688d671c3fb7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9757, "license_type": "permissive", "max_line_length": 114, "num_lines": 338, "path": "/Python/COARE3.5/meteo.py", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\r\nFunctions for meteorological variable conversions and functions.\r\n\r\nTranslated and vectorized from NOAA bulk model and flux processing MATLAB scripts.\r\n\r\nUncomment code at the end of this file and execute '%run flux.py' from the iPython command line to test functions.\r\n\r\nByron Blomquist, CU/CIRES, NOAA/ESRL/PSD3\r\nv1: Oct 2014\r\n\"\"\"\r\n\r\ndef qsat(t,p):\r\n \"\"\"\r\n usage: es = qsat(t,p)\r\n Returns saturation vapor pressure es (mb) given t(C) and p(mb).\r\n\r\n After Buck, 1981: J.Appl.Meteor., 20, 1527-1532\r\n\r\n Returns ndarray float for any numeric object input.\r\n \"\"\"\r\n from numpy import copy, asarray, exp\r\n\r\n t2 = copy(asarray(t, dtype=float)) # convert to ndarray float\r\n p2 = copy(asarray(p, dtype=float))\r\n es = 6.1121 * exp(17.502 * t2 / (240.97 + t2))\r\n es = es * (1.0007 + p2 * 3.46e-6)\r\n return es\r\n\r\n\r\ndef qsea(sst,p):\r\n \"\"\"\r\n usage: qs = qsea(sst,p)\r\n Returns saturation specific humidity (g/kg) at sea surface\r\n given sst(C) and p(mb) input of any numeric type.\r\n\r\n Returns ndarray float for any numeric object input.\r\n \"\"\"\r\n ex = qsat(sst,p) # returns ex as ndarray float\r\n es = 0.98 * ex\r\n qs = 622 * es /(p - 0.378 * es)\r\n return qs\r\n\r\n\r\ndef qair(t,p,rh):\r\n \"\"\"\r\n usage: qa, em = qair(t,p,rh)\r\n Returns specific humidity (g/kg) and partial pressure (mb)\r\n given t(C), p(mb) and rh(%).\r\n\r\n Returns ndarray float for any numeric object input.\r\n \"\"\"\r\n from numpy import copy, asarray\r\n\r\n rh2 = copy(asarray(rh,dtype=float)) # conversion to ndarray float\r\n rh2 /= 100.0 # frational rh\r\n p2 = copy(asarray(p, dtype=float))\r\n t2 = copy(asarray(t, dtype=float))\r\n em = rh2 * qsat(t2,p2)\r\n qa = 621.97 * em / (p2 - 0.378 * em)\r\n return (qa, em)\r\n\r\n\r\ndef rhcalc(t,p,q):\r\n \"\"\"\r\n usage: rh = rhcalc(t,p,q)\r\n Returns RH(%) for given t(C), p(mb) and specific humidity, q(kg/kg)\r\n\r\n Returns ndarray float for any numeric object input.\r\n \"\"\"\r\n from numpy import copy, asarray\r\n\r\n q2 = copy(asarray(q, dtype=float)) # conversion to ndarray float\r\n p2 = copy(asarray(p, dtype=float))\r\n t2 = copy(asarray(t, dtype=float))\r\n es = qsat(t2,p2)\r\n em = p2 * q2 / (0.622 + 0.378 * q2)\r\n rh = 100.0 * em / es\r\n return rh\r\n\r\n\r\ndef rhoa(t,p,rh):\r\n \"\"\"\r\n computes moist air density from temperature, pressure and RH\r\n\r\n usage: Ra = rhoa(t,p,rh)\r\n\r\n inputs: t (deg C), p (mb or hPa) and rh\r\n\r\n output: Ra = moist air density in kg/m3\r\n\r\n \"\"\"\r\n Md = 0.028964 # mol wt dry air, kg/mole\r\n Mv = 0.018016 # mol wt water, kg/mole\r\n Tk = t + 273.15 # deg Kelvin\r\n Pa = p*100.0 # Pascals\r\n Rgas = 8.314 # in m3 Pa/mol K\r\n Pv = (rh/100.0)*qsat(t,p)*100.0 # H2O vapor pressure in Pa\r\n Pd = Pa - Pv # pressure dry air\r\n Ra = (Pd*Md + Pv*Mv)/(Rgas*Tk) # moist air density\r\n return Ra\r\n\r\n\r\ndef rhod(t,p):\r\n \"\"\"\r\n computes dry air density from temperature and pressure\r\n\r\n usage: Rd = rhod(t,p)\r\n\r\n inputs: t (deg C), and p (mb or hPa)\r\n\r\n output: Rd = dry air density in kg/m3\r\n\r\n \"\"\"\r\n Rd = 287.058 # gas const for dry air in J/kg K\r\n tk = t+273.15 # deg Kelvin\r\n Pa = p*100 # Pascals\r\n Rdry = Pa/(Rd*Tk) # dry air density, kg/m3\r\n return Rd\r\n\r\n\r\ndef grv(latitude):\r\n \"\"\"\r\n usage: g = grv(latitude)\r\n Computes gravity, g [m/sec^2] given latitude in deg.\r\n\r\n Ref??\r\n\r\n Returns ndarray float for any numeric object input.\r\n \"\"\"\r\n from numpy import copy, pi, sin, asarray\r\n\r\n lat = copy(asarray(latitude, dtype=float)) # conversion to ndarray float\r\n gamma = 9.7803267715\r\n c1 = 0.0052790414\r\n c2 = 0.0000232718\r\n c3 = 0.0000001262\r\n c4 = 0.0000000007\r\n phi = lat * pi/180;\r\n x = sin(phi);\r\n g = gamma * (1 + c1*x**2 + c2*x**4 + c3*x**6 + c4*x**8)\r\n return g\r\n\r\n\r\ndef psit_26(z_L):\r\n \"\"\"\r\n usage psi = psit_26(z_L)\r\n\r\n Computes the temperature structure function given z/L.\r\n \"\"\"\r\n from numpy import exp, log, sqrt, arctan, asarray, copy\r\n from util import find\r\n\r\n zet = copy(asarray(z_L, dtype=float)) # conversion to ndarray float\r\n dzet = 0.35*zet\r\n dzet[dzet>50] = 50. # stable\r\n psi = -((1 + 0.6667*zet)**1.5 + 0.6667*(zet - 14.28)*exp(-dzet) + 8.525)\r\n k = find(zet < 0) # unstable\r\n x = (1 - 15*zet[k])**0.5\r\n psik = 2*log((1 + x)/2.)\r\n x = (1 - 34.15*zet[k])**0.3333\r\n psic = 1.5*log((1.+x+x**2)/3.) - sqrt(3)*arctan((1 + 2*x)/sqrt(3))\r\n psic += 4*arctan(1.)/sqrt(3.)\r\n f = zet[k]**2 / (1. + zet[k]**2.)\r\n psi[k] = (1-f)*psik + f*psic\r\n return psi\r\n\r\n\r\ndef psiu_26(z_L):\r\n \"\"\"\r\n usage: psi = psiu_26(z_L)\r\n\r\n Computes velocity structure function given z/L\r\n \"\"\"\r\n from numpy import exp, log, sqrt, arctan, min, asarray, copy\r\n from util import find\r\n\r\n zet = copy(asarray(z_L, dtype=float)) # conversion to ndarray float\r\n dzet = 0.35*zet\r\n dzet[dzet>50] = 50. # stable\r\n a = 0.7\r\n b = 3./4.\r\n c = 5.\r\n d = 0.35\r\n psi = -(a*zet + b*(zet - c/d)*exp(-dzet) + b*c/d)\r\n k = find(zet < 0) # unstable\r\n x = (1 - 15*zet[k])**0.25\r\n psik = 2.*log((1.+x)/2.) + log((1.+x*x)/2.) - 2.*arctan(x) + 2.*arctan(1.)\r\n x = (1 - 10.15*zet[k])**0.3333\r\n psic = 1.5*log((1.+x+x**2)/3.) - sqrt(3.)*arctan((1.+2.*x)/sqrt(3.))\r\n psic += 4*arctan(1.)/sqrt(3.)\r\n f = zet[k]**2 / (1.+zet[k]**2)\r\n psi[k] = (1-f)*psik + f*psic\r\n return psi\r\n\r\n\r\ndef psiu_40(z_L):\r\n \"\"\"\r\n usage: psi = psiu_40(z_L)\r\n\r\n Computes velocity structure function given z/L\r\n \"\"\"\r\n from numpy import exp, log, sqrt, arctan, min, asarray, copy\r\n from util import find\r\n\r\n zet = copy(asarray(z_L, dtype=float)) # conversion to ndarray float\r\n dzet = 0.35*zet\r\n dzet[dzet>50] = 50. # stable\r\n a = 1.\r\n b = 3./4.\r\n c = 5.\r\n d = 0.35\r\n psi = -(a*zet + b*(zet - c/d)*exp(-dzet) + b*c/d)\r\n k = find(zet < 0) # unstable\r\n x = (1. - 18.*zet[k])**0.25\r\n psik = 2.*log((1.+x)/2.) + log((1.+x*x)/2.) - 2.*arctan(x) + 2.*arctan(1.)\r\n x = (1. - 10.*zet[k])**0.3333\r\n psic = 1.5*log((1.+x+x**2)/3.) - sqrt(3.)*arctan((1.+2.*x)/sqrt(3.))\r\n psic += 4.*arctan(1.)/sqrt(3.)\r\n f = zet[k]**2 / (1.+zet[k]**2)\r\n psi[k] = (1-f)*psik + f*psic\r\n return psi\r\n\r\n\r\n\r\ndef Le_water(t, sal):\r\n \"\"\"\r\n computes latent heat of vaporization for pure water and seawater\r\n reference: M. H. Sharqawy, J. H. Lienhard V, and S. M. Zubair, Desalination\r\n and Water Treatment, 16, 354-380, 2010. (http://web.mit.edu/seawater/)\r\n validity: 0 < t < 200 C; 0 <sal <240 g/kg\r\n\r\n usage: Le_w, Le_sw = Le_water(t, sal)\r\n\r\n inputs: T in deg C\r\n sal in ppt\r\n\r\n output: Le_w, Le_sw in J/g (kJ/kg)\r\n\r\n \"\"\"\r\n\r\n # polynomial constants\r\n a = [2.5008991412E+06, -2.3691806479E+03, 2.6776439436E-01,\r\n -8.1027544602E-03, -2.0799346624E-05]\r\n\r\n Le_w = a[0] + a[1]*t + a[2]*t**2 + a[3]*t**3 + a[4]*t**4\r\n Le_sw = Le_w*(1 - 0.001*sal)\r\n return (Le_w/1000.0, Le_sw/1000.0)\r\n\r\n\r\ndef uv2spd_dir(u,v):\r\n \"\"\"\r\n converts u, v meteorological wind components to speed/direction\r\n where u is velocity from N and v is velocity from E (90 deg)\r\n\r\n usage spd, dir = uv2spd_dir(u, v)\r\n\r\n \"\"\"\r\n import numpy as np\r\n\r\n spd = np.zeros_like(u)\r\n dir = np.zeros_like(u)\r\n\r\n spd = np.sqrt(u**2 + v**2)\r\n dir = np.arctan2(v, u)*180.0/np.pi\r\n\r\n return (spd, dir)\r\n\r\n\r\ndef spd_dir2uv(spd,dir):\r\n \"\"\"\r\n converts wind speed / direction to u, v meteorological wind components\r\n where u is velocity from N and v is velocity from E (90 deg)\r\n\r\n usage u, v = uv2spd_dir(spd, dir)\r\n\r\n \"\"\"\r\n import numpy as np\r\n\r\n dir2 = (np.copy(dir) + 180.0)*np.pi/180.0\r\n s = np.sin(dir2)\r\n c = np.cos(dir2)\r\n v = -spd*s\r\n u = -spd*c\r\n\r\n return (u, v)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# This code executes if 'run flux.py' is executed from iPython cmd line\r\n# Uncomment lines below to test particular functions\r\nif __name__ == '__main__':\r\n import numpy as np\r\n import matplotlib.pyplot as plt\r\n\r\n # TEST MET FUNCTIONS\r\n# print 'testing qsat(25,1015) = 31.8037'\r\n# print qsat(25,1015)\r\n\r\n# print 'testing qsea(18,1013) = 12.5615'\r\n# print qsea(18,1013)\r\n\r\n# print 'testing qair(10,1010,77) = 5.8665'\r\n# print qair(10,1010,77)\r\n\r\n# print 'testing rhcalc(14,1013,9.7121) = 98'\r\n# print rhcalc(14,1013,9.7121)\r\n\r\n# print 'testing grv(45) = 9.8062'\r\n# print grv(45)\r\n\r\n # TEST PSI FUNCTIONS\r\n# zet = np.arange(1,501,25)\r\n# psi = psit_26(zet)\r\n# print 'psit_26: MATLAB result *10^3'\r\n# print '-0.0044 -0.0870 -0.2156 -0.3799'\r\n# print '-0.5734 -0.7922 -1.0337 -1.2959'\r\n# print '-1.5772 -1.8765 -2.1927 -2.5250'\r\n# print '-2.8726 -3.2349 -3.6113 -4.0013'\r\n# print '-4.4044 -4.8202 -5.2484 -5.6886'\r\n# print psi\r\n# psi = psiu_26(zet)\r\n# print 'psiu_26: MATLAB result'\r\n# print ' -4.3926 -28.9153 -46.4143 -63.9143 -81.4143'\r\n# print ' -98.9143 -116.4143 -133.9143 -151.4143 -168.9143'\r\n# print '-186.4143 -203.9143 -221.4143 -238.9143 -256.4143'\r\n# print '-273.9143 -291.4143 -308.9143 -326.4143 -343.9143'\r\n# print psi\r\n# psi = psiu_40(zet)\r\n# print 'psiu_40: MATLAB result'\r\n# print ' -4.6926 -36.7153 -61.7143 -86.7143 -111.7143'\r\n# print '-136.7143 -161.7143 -186.7143 -211.7143 -236.7143'\r\n# print '-261.7143 -286.7143 -311.7143 -336.7143 -361.7143'\r\n# print '-386.7143 -411.7143 -436.7143 -461.7143 -486.7143'\r\n# print psi\r\n" }, { "alpha_fraction": 0.7558484077453613, "alphanum_fraction": 0.7742998600006104, "avg_line_length": 73.93827056884766, "blob_id": "d59d21bab44acfa66bedc38c299d1c64deda8f2c", "content_id": "65df9eeb3dc0837d132a6569f4b31a6eb0b8e3dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6096, "license_type": "permissive", "max_line_length": 605, "num_lines": 81, "path": "/Fortran/COARE3.0/f77/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "Brief notes about the algorithm and the test data set appears at the head of the fortran file. Here we provide some comments on the structure of the code:\n\n1. The input \"read\" statement is set up for the test data file test3_0.txt . This consists of four days of Moana Wave COARE data, 26-29 Nov 1992, prepared from Chris Fairall's hourly data file wavhr2_5.asc dated 31/10/96. A full description of the Moana Wave operations, instruments and data set is given at http://www.ncdc.noaa.gov/coare/catalog/data/air_sea_fluxes/moana_flux.html\n\n2. A list of input variables is given, with units etc.. Only the first 11, the critical environmental and position variables, appear in the test data. If time series of p and/or zi are available to the user, they may be added to the “700 read…” input string, and the default values disabled. The remaining input parameters relate to the instrument set-up and are expected to remain fixed for the duration of the observations. They are therefore set in the main program, as are the switches for cool skin, warm layer and wave state options.\n\n3. Properly, wind speed should be relative to the water surface. “u” should be the vector sum of measured wind speed and surface current if available, calculated by the user outside the program.\n\n4. Two sea temperature measurements are given in the test data, one at only 0.05m depth, the other at 6m from Mike Gregg's Advanced Microstructure Profiler which operated from the Moana Wave during leg 1. The data was kindly provided in suitable form by Hemantha Wijesekera (COAS, OSU). It allows a better demonstration of the calculation of skin temperature from the bulk via the warm layer option. “ts_depth” should be set to correspond with whichever of “ts” or “hwt” is selected.\n\n5. If skin temperature (sst) is measured directly with an infra-red radiometer, the warm layer and cool skin codes should be bypassed by setting jwarm and jcool to zero\n\n6. jwave selects the method of calculating zo at the beginning of the main iteration loop in subroutine(ASL), i.e. Smith (1988) or one of the two wind/wave parameterizations. The latter require values for the significant wave height (hwave) and dominant wave period (twave), which are calculated in the code from formulas given by Taylor and Yelland (2001) for fully developed seas. If measurements of hwave and twave are available, they should be added to the input data string and the default values disabled.\n\n7. Structure of the fortran code.\nThe main program (fluxes) opens the input and output files, reads the data and sets fixed values, defaults and options. It adds a data line number (index) and calls subroutine bulk_flux, passing input data in COMMON.\nBulk_flux defines most physical constants and coefficients and, after determining the proper conditions, calculates and integrates the diurnal warming of the ocean surface, using fluxes and net longwave radiation from the previous time-step and the solar absorption profile. The fraction of warming above the temperature sensor is added to the measurement, and subroutine ASL is called for the flux and boundary layer calculations.\nASL is a descendant of the original LKB code, but almost all operations and parameterizations are changed. After a series of first guesses and operations to characterize the atmospheric surface layer within the framework of Monin-Obhukov similarity theory, the core of the subroutine is an iteration loop. This iterates three times over the fluxes (in the form u*, t*, q*), the roughness parameters (zo, zot, zoq), the M-O stability parameter and profile phi functions, and also calculates gustiness and the cool skin within the loop. Final values are returned to bulk_flux in COMMON.\nFinally, bulk_flux calculates the surface fluxes (Wm-2), skin temperature (sst), heat and momentum fluxes due to rainfall, neutral transfer coefficients, values of state variables at standard height, etc., and saves the fluxes for the next timestep warm layer integrals. Output files are written before returning to the main program for the next line of input data.\n\n8. Outputs available from bulk_flux are listed at the head of the program. The outputs in tst3_0bf.out are given below. To illustrate the warm layer and cool skin, we output the respective delta-temperatures and layer thicknesses. Note that dt_warm is the temperature across the entire warm layer. Only if tk_pwp is less than the sensor depth (ts_depth = 6m in the test case) will tsw=ts +dt_warm. Otherwise, a linear profile is assumed, and the warming above the bulk sensor calculated. The measurement of “ts” at 0.05m depth will generally include most of the warm layer but not the cool skin effect.\n\nPrograms:\n*\tcor3_0bf.for: this version is set up to use the Fairall near-surface temperature sensor for Ts bulk.\n*\tcor3_0bh.for: this version is setup to use the MSP 6m-depth temperature sensor for Ts bulk.\n \nInput data:\n*\ttest3_0.txt (Test data)\n\n1\tDate: YYYYMMDDHHmmss.ss, YYYY=year, MM=month, DD=day, HH=hour, mm=minute,ss.ss=sec\n\n2\tU: true wind speed at 15-m height m/s corrected for surface currents\n\n3\tTsea: sea surface temp (at about 0.05m depth) deg.C\n\n4\tTair: Vaisala air temperature (about 15 m) deg.C\n\n5\tqair: Vaisala air specific humidity (about 15 m) g/kg\n\n6\tRs: solar irradiance W/m2\n\n7\tRl: downwelling longwave irradiance W/m2\n\n8\tRain: precipitation mm/hr\n\n9\tLat: Latitude (N=+)\n\n10\tLon: Longitude (E=+)\n\n11\tMSP: MSP temperature at 6m depth deg.C\n\n\n\nOutput files:\n*\ttst3_0bf.out and tst3_0bh.out \tFortran output files from test data\n\n1\tindex:\tdata line number\n\n2\txtime:\tYYYYMMDDHHmmss, date and time as read in (without dec. sec.)\n\n3\thf:\tsensible heat flux W/m2\n\n4\tef:\tlatent heat flux W/m2\n\n5\tsst:\tsea skin temperature deg.C\n\n6\ttau:\tsurface stress N/m2\n\n7\tWbar:\tmean Webb vertical velocity m/s\n\n8\trf:\tsensible heat flux due to precipitation W/m2\n\n9\tdter:\tcool skin effect deg.C\n\n10\tdt_wrm: warming across entire warm layer deg.C\n\n11\ttk_pwp:warm layer thickness m\n\n12\ttkt*1000:tkt=cool skin thickness\n\n13\tWg:\tgustiness velocity m/s\n" }, { "alpha_fraction": 0.6601690649986267, "alphanum_fraction": 0.7475340366363525, "avg_line_length": 145.8275909423828, "blob_id": "4906599e0aa9bfcb86bc0a2c9ea2870366b0dd6f", "content_id": "9874073d18bf18f355ba4d4205f71892847b1971", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4266, "license_type": "permissive", "max_line_length": 1198, "num_lines": 29, "path": "/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "# COARE-algorithm\nRepository of the TOGA-COARE bulk air-sea flux algorithm in:\n- Python\n- MATLAB\n- FORTRAN\n\n## Origins\nThe international TOGA-COARE field program which took place in the western Pacific warm pool over 4 months from November 1992 to February 1993 ([Fairall et al. 1996a](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Fairall%20et%20al.%201996a%20-%20cool%20skin%20warm%20layer.pdf), [1996b](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Fairall%20et%20al.%201996b%20-%20bulk%20fluxes%20of%20variables.pdf) and [1997](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Fairall%20et%20al.%201997%20-%20ship%20measurements%20MABL.pdf)) spurred the development of the COARE model. The algorithm is intended to provide estimates of `momentum, sensible heat`, and `latent heat fluxes` using inputs of bulk atmospheric variables (`wind speed, SST, air temperature, air humidity`). The algorithm contains subroutines/functions to handle near-surface gradients of temperature in the ocean.\n\n## Versions\n- **Version 2.5** was published in 1996. \n- **Version 3.0** was published in 2003; it was a major update from Version 2.5. This update was based on new observations at higher wind speeds (10 to 20 m/s). Available in MATLAB and FORTRAN only.\n- **Version 3.5** was released in 2013 following the publication of [Edson et al. 2013](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Edson%20et%20al.%202013%20-%20momentum%20flux.pdf), which made adjustments to the wind speed dependence of the Charnock parameter based on a large database of direct covariance stress observations (principally from a buoy). This led to an increase in stress for wind speeds greater than about 18 m/s. The roughness Reynolds number formulation of the scalar roughness length was tuned slightly to give the same values of `Ch` and `Ce` as Version 3.0. The diurnal warm layer model was structured as a separate routine instead of embedded in a driver program. COARE 3.5 was based on Edson’s buoy data ([Edson et al. 2013](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Edson%20et%20al.%202013%20-%20momentum%20flux.pdf)) and was compared to a large database (a total of 16,000 hours of observations) combining observations from NOAA, WHOI, and U. Miami ([Fairall et al. 2011](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/Fairall%20et%20al.%202011%20-%20COAREG.pdf)). It is available in Python and MATLAB.\n- **Version 3.6** is slightly restructured and built around improvements in the representation of the effects of waves on fluxes. This includes improved relationships of `surface roughness`, $z_o$, and `whitecap fraction`, $W_f$, on wave parameters. More details can be found in [coare3.6\\_readme\\_1.pdf](https://github.com/noaa-psd/COARE-algorithm/blob/master/References/coare36_readme_1.pdf). This version is available in Python, MATLAB and FORTRAN.\n\n\n# References:\n\n* Edson, J.B., J. V. S. Raju, R.A. Weller, S. Bigorre, A. Plueddemann, C.W. Fairall, S. Miller, L. Mahrt, Dean Vickers, and Hans Hersbach, 2013: On the Exchange of momentum over the open ocean. J. Phys. Oceanogr., 43, 1589–1610. doi: http://dx.doi.org/10.1175/JPO-D-12-0173.1\n\n* Fairall, C.W., E.F. Bradley, J.S. Godfrey, G.A. Wick, J.B. Edson, and G.S. Young, 1996a: The cool skin and the warm layer in bulk flux calculations. J. Geophys. Res. 101, 1295-1308. https://doi.org/10.1029/95JC03190\n\n* Fairall, C.W., E.F. Bradley, D.P. Rogers, J.B. Edson, G.S. Young, 1996b: Bulk parameterization of air-sea fluxes for TOGA COARE. J. Geophys. Res. 101, 3747-3764. https://doi.org/10.1029/95JC03205\n\n* Fairall, C. W., White, A. B., Edson, J. B., and Hare, J. E.: Integrated Shipboard Measurements of the Marine Boundary Layer, J. Atmos. Ocean. Tech., 14, 338–359, 1997. https://doi.org/10.1175/1520-0426(1997)014<0338:ISMOTM>2.0.CO;2\n\n* Fairall, C.W., E.F. Bradley, J.E. Hare, A.A. Grachev, and J.B. Edson, 2003: Bulk parameterization of air-sea fluxes: Updates and verification for the COARE algorithm. J. Climate 16, 571-591. https://doi.org/10.1175/1520-0442(2003)016<0571:BPOASF>2.0.CO;2\n\n* Fairall, C.W., Mingxi Yang, Ludovic Bariteau, J.B. Edson, D. Helmig, W. McGillis, S. Pezoa, J.E. Hare, B. Huebert, and B. Blomquist, 2011: Implementation of the COARE flux algorithm with CO2, DMS, and O3. J. Geophys. Res., 116, C00F09, https://doi.org/10.1029/2010JC006884\n" }, { "alpha_fraction": 0.51951003074646, "alphanum_fraction": 0.5435029864311218, "avg_line_length": 12.709156036376953, "blob_id": "50b00dfbff0f0620cf2032b34ff7a8c0364981ed", "content_id": "7fd667e36fd2c6809f4194e48aaa0155e705dbcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7919, "license_type": "permissive", "max_line_length": 80, "num_lines": 557, "path": "/Python/COARE3.5/util.py", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "\"\"\"\r\r\nUtility functions gathered from various sources or custom.\r\r\n\r\r\nV.1 Oct 2014, BWB\r\r\n\"\"\"\r\r\n\r\r\ndef load_txt_file(path,fil,cols,sep='\\t',hdr=True):\r\r\n \"\"\"\r\r\n loads delimited text file of column variables\r\r\n header, if present, is assumed to be one line of var names only\r\r\n\r\r\n usage: data, varNames = load_txt_file(path,fil,cols)\r\r\n\r\r\n inputs: path: string variable for path to file\r\r\n fil: string variable of file name\r\r\n cols: number of data columns in file\r\r\n sep: delimiter character, tab is default\r\r\n hdr: boolean, True if file has header (default)\r\r\n\r\r\n output: data: 2-D array of data as column variables\r\r\n varNames: list of variable names\r\r\n \"\"\"\r\r\n import os\r\r\n import numpy as np\r\r\n\r\r\n fpath = os.path.join(path,fil)\r\r\n fin = open(fpath)\r\r\n first = True\r\r\n data = np.zeros((0,cols))\r\r\n temp = np.zeros((1,cols))\r\r\n for line in fin:\r\r\n if first and hdr:\r\r\n cleanLine = line.strip()\r\r\n varNames = cleanLine.split(sep)\r\r\n first = False\r\r\n continue\r\r\n elif first and not hdr:\r\r\n varNames = []\r\r\n for jj in range(cols): # default var names\r\r\n varNames.append('var'+str(jj))\r\r\n first = False\r\r\n cleanLine = line.strip()\r\r\n fields = cleanLine.split(sep)\r\r\n for jj in range(cols):\r\r\n temp[0,jj] = np.float(fields[jj])\r\r\n data = np.row_stack((data,temp))\r\r\n fin.close()\r\r\n return (data, varNames)\r\r\n\r\r\n\r\r\ndef noaa_tcode(ddd, hh, code_str):\r\r\n \"\"\"\r\r\n Converts NOAA serial data acquisition system time code to decimal\r\r\n julian date.\r\r\n\r\r\n Usage: jd = noaa_tcode(ddd, hh, code_str)\r\r\n\r\r\n Input strings: ddd = julian date, hh = hour string, and code_str = time code\r\r\n (e.g.1230423), where first two chr are minutes, next two are sec, and\r\r\n last three are msec\r\r\n\r\r\n Output is decimal julian date/time for given year\r\r\n\r\r\n \"\"\"\r\r\n\r\r\n import numpy as np\r\r\n\r\r\n day = np.float(ddd)\r\r\n hr = np.float(hh)\r\r\n min = np.float(code_str[0:2])\r\r\n sec = np.float(code_str[2:4])\r\r\n msec = np.float(code_str[4:])/1000\r\r\n jd = day + (hr + (min + (sec + msec)/60)/60)/24;\r\r\n return jd\r\r\n\r\r\n\r\r\ndef find(b):\r\r\n \"\"\"\r\r\n Usage: idx = find(b) - Returns sorted array of indices where boolean\r\r\n input array b is true. Similar to MATLAB find function.\r\r\n\r\r\n Input may be a 1-D boolean array or any expression that evaluates to\r\r\n a 1-D boolean: e.g. ii = find(x < 3), where x is a 1-D ndarray.\r\r\n This syntax is similar to MATLAB usage.\r\r\n\r\r\n 2-D or higher arrays could be flattened prior to calling find() and\r\r\n then reconstituted with reshape. This modification could be added to\r\r\n this function as well to support N-D arrays.\r\r\n\r\r\n Returns 1-D ndarray of int64.\r\r\n \"\"\"\r\r\n from numpy import sum, argsort, sort, ndarray\r\r\n\r\r\n if type(b) != ndarray:\r\r\n raise ValueError ('find: Input should be ndarray')\r\r\n if b.dtype != 'bool':\r\r\n raise ValueError ('find: Input should be boolean array')\r\r\n if b.ndim > 1:\r\r\n raise ValueError ('find: Input should be 1-D')\r\r\n\r\r\n F = b.size - sum(b) # number of False in b\r\r\n idx = argsort(b)[F:] # argsort puts True at the end, so select [F:]\r\r\n idx = sort(idx) # be sure values in idx are ordered low to high\r\r\n return idx\r\r\n\r\r\n\r\r\ndef md2jd(YYYY, MM, DD):\r\r\n \"\"\"\r\r\n Converts Month and Day into day-of-year (julian date)\r\r\n\r\r\n Usage: yday = md2jd(YYYY, MM, DD)\r\r\n\r\r\n Inputs YYYY, MM & DD may be strings or numbers.\r\r\n\r\r\n Returns integer day of year\r\r\n\r\r\n \"\"\"\r\r\n import numpy as np\r\r\n\r\r\n day_tab = [[31,28,31,30,31,30,31,31,30,31,30,31],\r\r\n [31,29,31,30,31,30,31,31,30,31,30,31]]\r\r\n days = np.array(day_tab)\r\r\n yr = np.int(YYYY)\r\r\n mo = np.int(MM)\r\r\n day = np.int(DD)\r\r\n\r\r\n leap = np.logical_and((np.remainder(yr,4) == 0),\r\r\n (np.remainder(yr,100) != 0))\r\r\n leap = np.logical_or(leap, (np.remainder(yr,400) == 0))\r\r\n\r\r\n yday = day\r\r\n for ii in np.arange(1,mo):\r\r\n yday += days[leap,ii-1]\r\r\n\r\r\n return np.int(yday)\r\r\n\r\r\n\r\r\ndef jd2md(YYYY, DOY):\r\r\n \"\"\"\r\r\n Converts day-of-year (julian date) to Month and Day of given Year\r\r\n\r\r\n Usage: mo, da = jd2md(YYYY, JD)\r\r\n\r\r\n Inputs YYYY, & DOY may be strings or numbers.\r\r\n\r\r\n Returns tuple of integers, month and day\r\r\n\r\r\n \"\"\"\r\r\n import numpy as np\r\r\n\r\r\n day_tab = [[31,28,31,30,31,30,31,31,30,31,30,31],\r\r\n [31,29,31,30,31,30,31,31,30,31,30,31]]\r\r\n days = np.array(day_tab)\r\r\n yr = np.int(YYYY)\r\r\n jd = np.int(DOY)\r\r\n\r\r\n leap = np.logical_and((np.remainder(yr,4) == 0),\r\r\n (np.remainder(yr,100) != 0))\r\r\n leap = np.logical_or(leap, (np.remainder(yr,400) == 0))\r\r\n\r\r\n ii = 1\r\r\n while jd > days[leap,ii-1]:\r\r\n jd -= days[leap,ii-1]\r\r\n ii += 1\r\r\n\r\r\n mo = np.int(ii)\r\r\n day = np.int(jd)\r\r\n return (mo, day)\r\r\n\r\r\n\r\r\ndef replace_nan(x):\r\r\n \"\"\"\r\r\n Replaces NaNs in 1D array with nearest finite value.\r\r\n\r\r\n Usage: y = replace_nan(x)\r\r\n\r\r\n Returns filled array y without altering input array x.\r\r\n Assumes input is numpy array.\r\r\n\r\r\n 3/2015 BWB\r\r\n \"\"\"\r\r\n import numpy as np\r\r\n#\r\r\n x2 = np.zeros(len(x))\r\r\n np.copyto(x2,x)\r\r\n#\r\r\n bads = find(np.isnan(x)) # indices of NaNs\r\r\n if bads.size == 0:\r\r\n return x2\r\r\n else:\r\r\n fins = find(np.isfinite(x)) # indices for all finites\r\r\n for ii in np.arange(0,bads.size): # for all NaNs\r\r\n # locate index of nearest finite\r\r\n diffs = np.abs(fins-bads[ii])\r\r\n idx = diffs.argmin()\r\r\n # replace NaN with nearest finite\r\r\n x2[bads[ii]] = x[fins[idx]]\r\r\n return x2\r\r\n\r\r\n\r\r\ndef invert_dict(d):\r\r\n \"\"\"Inverts a dictionary, returning a map from val to a list of keys.\r\r\n\r\r\n If the mapping key->val appears in d, then in the new dictionary\r\r\n val maps to a list that includes key.\r\r\n\r\r\n d: dict\r\r\n\r\r\n Returns: dict\r\r\n\r\r\n Copyright 2012 Allen B. Downey\r\r\n License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\r\r\n \"\"\"\r\r\n inverse = {}\r\r\n for key, val in d.iteritems():\r\r\n inverse.setdefault(val, []).append(key)\r\r\n return inverse\r\r\n\r\r\n\r\r\ndef find_module(module):\r\r\n \"\"\"\r\r\n Searches the PYTHONPATH for a module\r\r\n \"\"\"\r\r\n import sys\r\r\n import os\r\r\n import glob\r\r\n\r\r\n result = []\r\r\n # Loop over the list of paths in sys.path\r\r\n for subdir in sys.path:\r\r\n # Join the subdir path with the module we're searching for\r\r\n pth = os.path.join(subdir, module)\r\r\n # Use glob to test if the pth is exists\r\r\n res = glob.glob(pth)\r\r\n # glob returns a list, if it is not empty, the pth exists\r\r\n if len(res) > 0:\r\r\n result.append(res)\r\r\n return result\r\r\n\r\r\n\r\r\ndef print_attributes(obj):\r\r\n \"\"\"\r\r\n Prints attributes for given object\r\r\n \"\"\"\r\r\n for attr in obj.__dict__:\r\r\n print(attr), getattr(obj,attr)\r\r\n\r\r\n\r\r\ndef walk(dirname):\r\r\n \"\"\"\r\r\n Recursively traverse all files in given directory, printing\r\r\n file names.\r\r\n \"\"\"\r\r\n import os\r\r\n\r\r\n for name in os.listdir(dirname):\r\r\n path = os.path.join(dirname,name)\r\r\n\r\r\n if os.path.isfile(path):\r\r\n print(path)\r\r\n else:\r\r\n walk(path)\r\r\n\r\r\n# Test code\r\r\nif __name__ == '__main__':\r\r\n print('test')\r\r\n# print 'testing invert_dict'\r\r\n# d = dict(a=1, b=2, c=3, z=1)\r\r\n# print d\r\r\n# inverse = invert_dict(d)\r\r\n# for val, keys in inverse.iteritems():\r\r\n# print val, keys\r\r\n#\r\r\n# print \"testing find_module('site.py')\"\r\r\n# result = find_module('site.py')\r\r\n# print result\r\r\n#\r\r\n# print 'testing walk(os.getcwd())'\r\r\n# walk(os.getcwd())\r\r\n\r\r\n" }, { "alpha_fraction": 0.7213114500045776, "alphanum_fraction": 0.7431694269180298, "avg_line_length": 181, "blob_id": "b986dece86820e128a8b7d04c81820d0fe9c16da", "content_id": "98d5bff6afa85ddf1172a34b5deef08acf2e480b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 183, "license_type": "permissive", "max_line_length": 181, "num_lines": 1, "path": "/Matlab/COARE3.0/README.md", "repo_name": "NOAA-PSL/COARE-algorithm", "src_encoding": "UTF-8", "text": "'red_VP_bulk.m' is the main testing program. It loads the input data 'VP_test_data_1.txt', calls the 'coare30vn_ref.m' function, and compares to output files 'VP_test_results_1.txt'\n\n" } ]
12
tazjel/Accent
https://github.com/tazjel/Accent
4233a787bda0d5cb68d09c23f5a63f1fa4bc76aa
72730fc38a4007464704e1b722f6faafb86866d6
e1b711bb3d8ecdded2ab39a3aedea7021cf7847c
refs/heads/master
2021-01-22T09:55:34.807007
2016-12-02T18:24:12
2016-12-02T18:24:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5493574738502502, "alphanum_fraction": 0.5566588640213013, "avg_line_length": 33.92856979370117, "blob_id": "8cdbb411b900e8debd9e8758400773f78cfd62d7", "content_id": "9f675b0ca83f079debc66a1eaa9db98db7dfa0cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3425, "license_type": "no_license", "max_line_length": 124, "num_lines": 98, "path": "/Accent-iOS/Accent/Accent/LandingViewController.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// LandingViewController.swift\n// Accent\n//\n// Created by Aidan Gadberry on 10/26/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport UIKit\nimport TextFieldEffects\nimport Alamofire\nimport SCLAlertView\nimport SwiftyJSON\n\nclass LandingViewController: UIViewController {\n\n @IBOutlet var loginView: UIView!\n @IBOutlet var loginButton: UIButton!\n @IBOutlet var loginUsername: IsaoTextField!\n @IBOutlet var loginPassword: IsaoTextField!\n\n @IBOutlet var registerViewButton: UIButton!\n \n override func viewDidLoad() {\n super.viewDidLoad()\n \n // Do any additional setup after loading the view, typically from a nib.\n }\n \n override func viewWillAppear(_ animated: Bool) {\n UIApplication.shared.statusBarStyle = .lightContent\n self.navigationController?.isNavigationBarHidden = true\n }\n \n override var preferredStatusBarStyle : UIStatusBarStyle {\n return .lightContent\n }\n \n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n\n @IBAction func loginPressed(_ sender: AnyObject) {\n \n self.processLogin()\n }\n \n @IBAction func displayRegisterView(_ sender: AnyObject) {\n let registerVC = self.storyboard?.instantiateViewController(withIdentifier: \"RegisterVC\") as! RegisterViewController\n self.navigationController?.pushViewController(registerVC, animated: true)\n }\n \n func processLogin() {\n let parameters : [String : String] = [\n \"email\" : loginUsername.text!,\n \"password\" : loginPassword.text!\n ]\n \n print(parameters)\n \n var url = \"http://159.203.233.58/accent/default/api/login/\"\n url += parameters[\"email\"]! + \"/\" + parameters[\"password\"]!\n \n print(url)\n \n Alamofire.request(url, method: .get, encoding: URLEncoding.default)\n .responseJSON { response in\n let description = response.description\n print(response)\n if (description.substring(to: description.index(description.startIndex, offsetBy: 7)) == \"FAILURE\") {\n SCLAlertView().showError(\"Whoops!\", subTitle: \"Error connecting to server\")\n } else {\n let json = JSON(data: response.data!)\n \n if (json[\"error\"].stringValue != \"\") {\n SCLAlertView().showError(\"Whoops!\", subTitle: json[\"error\"].stringValue)\n\n } else {\n var myUser = [User]()\n let user = User(\n firstname: json[\"content\"][0][\"firstname\"].stringValue,\n lastname: json[\"content\"][0][\"lastname\"].stringValue,\n id: json[\"content\"][0][\"id\"].stringValue,\n password: json[\"content\"][0][\"password\"].stringValue,\n email: json[\"content\"][0][\"email\"].stringValue\n )\n myUser.append(user)\n \n \n let myDelegate = UIApplication.shared.delegate as! AppDelegate\n myDelegate.switchToTabBar(user: myUser)\n }\n }\n }\n }\n \n}\n\n" }, { "alpha_fraction": 0.5700483322143555, "alphanum_fraction": 0.6183574795722961, "avg_line_length": 12.800000190734863, "blob_id": "5cf4deab4fbd88a2f7a0dcc7344858b16d0ba75d", "content_id": "c4b45b0f0b7e90412a25066f23b2de2da88ae89d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 208, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/Accent-iOS/Accent/Accent/Query.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// Query.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/30/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport Foundation\n\nstruct Query {\n \n let original, corrected : String\n \n}\n" }, { "alpha_fraction": 0.5823817253112793, "alphanum_fraction": 0.5861104726791382, "avg_line_length": 34.1721305847168, "blob_id": "a6e8d6f2644116106aa5ef4c29e21947d077595f", "content_id": "5ad49dd6926e8fef8cc6bf43ef27d3dce20673ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4291, "license_type": "no_license", "max_line_length": 118, "num_lines": 122, "path": "/NLP/ngram.py", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "import http.client, urllib.request, urllib.parse\nimport urllib.error, base64, json, nltk\nfrom nltk import word_tokenize\nfrom nltk.util import ngrams\nimport string, re\n\n# Queries the Microsoft LM API for joint probabilities of trigrams.\nclass ngrammer:\n def __init__(self):\n self.tkns = dict()\n\n # Returns the index the token was received for reordering.\n def getIndex(self, token):\n return self.tkns[token]\n\n # Tags the part of speech \n def pos_tag(self, list_of_ngrams):\n pos_list = []\n for ngram in list_of_ngrams:\n pos_list.append(nltk.pos_tag(word_tokenize(ngram[0])))\n return pos_list\n\n # Queries Microsoft LM api\n def queryAPI(self, body_dict):\n headers = {\n # Request headers\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': '9292de8c83df4531861ef48c725f9256',\n }\n\n params = urllib.parse.urlencode({\n # Request parameters\n 'model': 'query',\n })\n\n try:\n conn = http.client.HTTPSConnection('api.projectoxford.ai')\n \n body = json.dumps(body_dict)\n conn.request(\"POST\", \"/text/weblm/v1.0/calculateJointProbability?%s\" % params, body, headers)\n response = conn.getresponse()\n data = response.read()\n #print(data)\n conn.close()\n except Exception as e:\n print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n return data\n\n def extractProbabilities(self, unserialized_data):\n data = json.loads(unserialized_data.decode('utf-8'))\n trigram_probabilities = []\n for trigram_result in data['results']:\n remake = []\n #print(trigram_result['words'])\n for word in word_tokenize(trigram_result['words']):\n remake.append(self.capitalize(word))\n #print(remake)\n rebuilt = ' '.join(remake)\n trigram_result['words'] = rebuilt\n print('4-Gram: ' + trigram_result['words'] + ' | ' + 'Probability: ' + str(trigram_result['probability']))\n trigram_probabilities.append((trigram_result['words'], trigram_result['probability']))\n return trigram_probabilities\n\n # Extract and returns the trigrams given a sanitized input string.\n def extractTrigrams(self, input_string):\n #print('Raw: ' + input_string)\n tokens = word_tokenize(input_string)\n for i in range(len(tokens)):\n self.tkns[tokens[i]] = i\n #print(self.tkns[tokens[i]])\n #print('Tokens: ', end = '')\n #print(tokens)\n numOfTokens = len(tokens)\n if numOfTokens == 1:\n print('1')\n elif numOfTokens == 2:\n trigramGenerator = ngrams(tokens,2)\n elif numOfTokens == 3:\n trigramGenerator = ngrams(tokens, 3)\n else:\n trigramGenerator = ngrams(tokens, 4)\n trigrams = set()\n [trigrams.add(gram) for gram in trigramGenerator]\n print(trigrams)\n return trigrams\n \n\n # Constructs and returns a dictionary obj that makes up the body of the API Query.\n def constructBody(self, trigrams):\n #print(trigrams)\n body = dict()\n body['queries'] = []\n for gram in trigrams:\n body['queries'].append(' '.join(list(gram)))\n\n #print(body)\n return body\n\n # Sanitizes the input by removing punctuation other than apostrophes and hyphens.\n def sanitize(self, raw):\n remove_regex = string.punctuation\n remove_regex = remove_regex.replace(\"'\",\"\")\n remove_regex = remove_regex.replace(\"-\",\"\")\n pattern = r\"[{}]\".format(remove_regex)\n sanitized = re.sub(pattern,'',raw)\n #print('sanitized ' + sanitized)\n return sanitized\n\n def capitalize(self, word):\n for tkn in self.tkns:\n if word == tkn.lower():\n word = tkn\n return word\n\n\n def probabilities(self, raw):\n sanitized_input = self.sanitize(raw)\n trigram_list = self.extractTrigrams(sanitized_input)\n body = self.constructBody(trigram_list)\n raw_output = self.queryAPI(body)\n trigram_probabilities = self.extractProbabilities(raw_output)\n return(trigram_probabilities)\n" }, { "alpha_fraction": 0.701996922492981, "alphanum_fraction": 0.7071172595024109, "avg_line_length": 34.490909576416016, "blob_id": "3ec3ef70cfef2c565e66ae8ddb120361b2d6b9ab", "content_id": "e55757be711879b47ea621eabedcc83b1b3976bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 109, "num_lines": 55, "path": "/NLP/grammar_corrections.py", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "from ngram import ngrammer\nimport nltk\nfrom nltk import word_tokenize\nclass corrector:\n\tdef __init__(self):\n\t\tself.CORRECTNESS_THRESHOLD = 13\n\t\tself.PRONOUN_TOLERANCE = 4.5\n\t\tself.ngrams_with_pos = dict()\n\n\t# Scrolls through and makes initial flags of incorrectness.\n\tdef initial_flagging(self, ngram_prob):\n\t\tif abs(ngram_prob) >= self.CORRECTNESS_THRESHOLD:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t# Recheck the correctness of an ngram after applying tolerance.\n\tdef check_tolerance(self):\n\t\tfor i in range(len(self.ngrams_with_pos)):\n\t\t\tfor word in self.ngrams_with_pos[i]['tuple']:\n\t\t\t\tif word[1] == 'NNP':\n\t\t\t\t\t#print('Pronoun - Singular')\n\t\t\t\t\tself.ngrams_with_pos[i]['probability'] = self.ngrams_with_pos[i]['probability'] + self.PRONOUN_TOLERANCE\n\t\t\tif abs(self.ngrams_with_pos[i]['probability']) < self.CORRECTNESS_THRESHOLD:\n\t\t\t\tself.ngrams_with_pos.pop(i,None)\n\n\n\t# Performs the actual grammar checking.\n\tdef check(self, input_string):\n\t\tng = ngrammer()\n\t\tsanitized_input = ng.sanitize(input_string)\n\t\ttrigram_list = ng.extractTrigrams(sanitized_input)\n\t\tprobabilities = ng.probabilities(input_string)\n\t\twrong_ngrams = []\n\t\tfor ngram_prob in probabilities:\n\t\t\tif self.initial_flagging(float(ngram_prob[1])):\n\t\t\t\twrong_ngrams.append(ngram_prob)\n\t\tpos_tagged_list = ng.pos_tag(wrong_ngrams)\n\n\t\tfor ngram_index in range(len(pos_tagged_list)):\n\t\t\tngram_tuple = []\n\t\t\tfor word_pos_pair in pos_tagged_list[ngram_index]:\n\t\t\t\tngram_tuple.append((word_pos_pair[0], word_pos_pair[1], ng.getIndex(word_pos_pair[0])))\n\t\t\tself.ngrams_with_pos[ngram_index] = dict()\n\t\t\tself.ngrams_with_pos[ngram_index]['tuple'] = ngram_tuple\n\t\t\tself.ngrams_with_pos[ngram_index]['probability'] = wrong_ngrams[ngram_index][1]\n\n\n\t\t#print(wrong_ngrams)\n\t\t#for i in self.ngrams_with_pos:\n\t\t\t#print(self.ngrams_with_pos[i]['tuple'])\n\t\t\t#print(self.ngrams_with_pos[i]['probability'])\n\t\tself.check_tolerance()\n\t\tfor i in self.ngrams_with_pos:\n\t\t\tprint(self.ngrams_with_pos[i])\n\n" }, { "alpha_fraction": 0.5768667459487915, "alphanum_fraction": 0.5876036882400513, "avg_line_length": 27.068492889404297, "blob_id": "2d82cce2167a9afba9de9e8a814d90b537a3ed07", "content_id": "1f74f9c7283e4b4eac4c58e5b280bea56b040ae7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 2050, "license_type": "no_license", "max_line_length": 148, "num_lines": 73, "path": "/Accent-iOS/Accent/Accent/CorrectionViewController.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// CorrectionViewController.swift\n// Accent\n//\n// Created by Aidan Gadberry on 10/26/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport UIKit\nimport Speech\nimport AVFoundation\nimport Alamofire\nimport SwiftyJSON\nimport SCLAlertView\n\nclass CorrectionViewController: UIViewController {\n\n var user = [User]()\n \n @IBOutlet var correctedSentence: UILabel!\n @IBOutlet var sentenceTextField: UITextView!\n @IBOutlet var submitQueryButton: UIButton!\n override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view.\n }\n\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n override func viewWillAppear(_ animated: Bool) {\n UIApplication.shared.statusBarStyle = .lightContent\n }\n \n override var preferredStatusBarStyle : UIStatusBarStyle {\n return .lightContent\n }\n//\n// func requestSpeechAuthentication() {\n// \n// }\n @IBAction func submitButtonPressed(_ sender: AnyObject) {\n self.correctSpeech()\n }\n \n func correctSpeech() {\n print(user)\n let parameters : [String : String] = [\n \"speech\" : sentenceTextField.text!.lowercased(),\n \"email\" : user[0].email\n ]\n \n print(parameters)\n \n Alamofire.request(\"http://159.203.233.58/accent/default/api/sentence\", method: .post, parameters: parameters, encoding: URLEncoding.default)\n .responseJSON { response in\n print(response)\n \n let json = JSON(data: response.data!)\n print(json)\n if (json[\"error\"].stringValue != \"\") {\n SCLAlertView().showError(\"Whoops!\", subTitle: json[\"error\"].stringValue)\n \n } else {\n self.correctedSentence.text = json[\"corrected\"].stringValue\n }\n \n }\n \n }\n}\n" }, { "alpha_fraction": 0.5739418864250183, "alphanum_fraction": 0.581591010093689, "avg_line_length": 28.93893051147461, "blob_id": "bfb8b0589e723707e084e7742f8410103eb34773", "content_id": "a188ff75efecf42234c894629a187ff5a75be20e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 3923, "license_type": "no_license", "max_line_length": 120, "num_lines": 131, "path": "/Accent-iOS/Accent/Accent/PastQueriesViewController.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// PastQueriesViewController.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/29/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport UIKit\nimport Alamofire\nimport SwiftyJSON\nimport SCLAlertView\nimport AVFoundation\n\nclass PastQueriesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {\n\n var user = [User]()\n var queries = [Query]()\n \n @IBOutlet var getQueriesButton: UIButton!\n @IBOutlet var queriesTableView: UITableView!\n \n let speechSynthesizer = AVSpeechSynthesizer()\n \n override func viewDidLoad() {\n super.viewDidLoad()\n\n // Do any additional setup after loading the view.\n }\n\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n override func viewWillAppear(_ animated: Bool) {\n UIApplication.shared.statusBarStyle = .lightContent\n }\n \n override func viewDidAppear(_ animated: Bool) {\n print(\"view appeared\")\n self.queriesTableView?.reloadData()\n }\n \n override var preferredStatusBarStyle : UIStatusBarStyle {\n return .lightContent\n }\n\n @IBAction func getQueriesButtonPressed(_ sender: AnyObject) {\n self.getPastQueries()\n }\n \n \n func getPastQueries() {\n var url = \"http://159.203.233.58/accent/default/api/\"\n url += user[0].email + \"/get\"\n \n Alamofire.request(url, method: .get, encoding: URLEncoding.default)\n .responseJSON { response in\n print(response)\n \n \n let json = JSON(data: response.data!)\n print(json)\n \n if (json[\"error\"].stringValue != \"\") {\n SCLAlertView().showError(\"Whoops!\", subTitle: json[\"error\"].stringValue)\n \n } else {\n self.queries.removeAll()\n for (_, jsonQuery) in json[\"content\"] {\n self.queries.insert(\n Query (\n original: jsonQuery[\"speech\"].stringValue,\n corrected: jsonQuery[\"corrected\"].stringValue\n ),\n at: 0\n )\n print(jsonQuery)\n }\n }\n }\n \n self.queriesTableView?.reloadData()\n \n }\n \n func speak(sentence: String) {\n let speech = AVSpeechUtterance(string: sentence)\n \n speech.pitchMultiplier = 0.75\n \n speechSynthesizer.speak(speech)\n }\n \n \n // Table View Protocol\n \n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = queriesTableView.dequeueReusableCell(withIdentifier: \"QueriesTableViewCell\") as! QueriesTableViewCell\n \n cell.originalText.text = queries[indexPath.row].original\n cell.correctedText.text = queries[indexPath.row].corrected\n return cell\n }\n \n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return queries.count\n }\n \n func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n return 100.0\n }\n \n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n speak(sentence: queries[indexPath.row].corrected)\n }\n\n \n \n /*\n // MARK: - Navigation\n\n // In a storyboard-based application, you will often want to do a little preparation before navigation\n override func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n // Get the new view controller using segue.destinationViewController.\n // Pass the selected object to the new view controller.\n }\n */\n\n}\n" }, { "alpha_fraction": 0.6486956477165222, "alphanum_fraction": 0.6660869717597961, "avg_line_length": 20.296297073364258, "blob_id": "e74cec1ce166e22aaf8c187a4f5880a8fea285d0", "content_id": "0cf392e0474699ccd81c2a0376a68f3fd2e3b184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 576, "license_type": "no_license", "max_line_length": 65, "num_lines": 27, "path": "/Accent-iOS/Accent/Accent/QueriesTableViewCell.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// QueriesTableViewCell.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/30/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport UIKit\n\nclass QueriesTableViewCell: UITableViewCell {\n\n @IBOutlet var originalText: UILabel!\n @IBOutlet var correctedText: UILabel!\n \n override func awakeFromNib() {\n super.awakeFromNib()\n // Initialization code\n }\n\n override func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n\n // Configure the view for the selected state\n }\n\n}\n" }, { "alpha_fraction": 0.5835654735565186, "alphanum_fraction": 0.5905292630195618, "avg_line_length": 29.553192138671875, "blob_id": "6c2b27af1c05c2a94de391f446542bd98ef6fced", "content_id": "2abc7680b9b8abf27f7a4de7d93ecb68970bead0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 2873, "license_type": "no_license", "max_line_length": 143, "num_lines": 94, "path": "/Accent-iOS/Accent/Accent/RegisterViewController.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// RegisterViewController.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/2/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport UIKit\nimport TextFieldEffects\nimport Alamofire\nimport SwiftyJSON\nimport SCLAlertView\n\nclass RegisterViewController: UIViewController {\n \n @IBOutlet var registerFirstName: IsaoTextField!\n @IBOutlet var registerLastName: IsaoTextField!\n @IBOutlet var registerEmail: IsaoTextField!\n @IBOutlet var registerPassword: IsaoTextField!\n \n \n @IBOutlet var registerButton: UIButton!\n \n \n override func viewDidLoad() {\n super.viewDidLoad()\n self.title = \"Register\"\n // Do any additional setup after loading the view.\n }\n\n override func viewWillAppear(_ animated: Bool) {\n self.navigationController?.isNavigationBarHidden = false\n }\n \n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n @IBAction func submitRegisterForm(_ sender: AnyObject) {\n \n// let account = Account (\n// firstname: registerUsername.text!,\n// lastname: registerUsername.text!,\n// password: registerPassword.text!,\n// email: registerEmail.text!\n// )\n \n let parameters : [String : String] = [\n \"firstname\" : registerFirstName.text!,\n \"lastname\" : registerLastName.text!,\n \"password\" : registerPassword.text!,\n \"email\" : registerEmail.text!\n ]\n \n print(parameters)\n \n Alamofire.request(\"http://159.203.233.58/accent/default/api/acc\", method: .post, parameters: parameters, encoding: URLEncoding.default)\n .responseJSON { response in\n \n print(response)\n \n let json = JSON(data: response.data!)\n \n if (json[\"error\"].stringValue != \"\") {\n SCLAlertView().showError(\"Whoops!\", subTitle: json[\"error\"].stringValue)\n \n } else {\n let landingVC = self.storyboard?.instantiateViewController(withIdentifier: \"LandingVC\") as! LandingViewController\n self.navigationController?.pushViewController(landingVC, animated: true)\n }\n \n \n }\n \n }\n\n func finishRegister(first_token : String, second_token : String) {\n \n }\n \n \n /*\n // MARK: - Navigation\n\n // In a storyboard-based application, you will often want to do a little preparation before navigation\n override func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n // Get the new view controller using segue.destinationViewController.\n // Pass the selected object to the new view controller.\n }\n */\n\n}\n" }, { "alpha_fraction": 0.5796459913253784, "alphanum_fraction": 0.6238937973976135, "avg_line_length": 14.066666603088379, "blob_id": "f4100864b4c427c1f42c5b17a14601045dfdf5bb", "content_id": "5a23f83e823bf1a350894da91bbf793bf5fcf5ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 227, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/Accent-iOS/Accent/Accent/User.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// User.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/23/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport Foundation\n\nstruct User {\n \n let firstname, lastname, id, password, email : String\n \n}\n" }, { "alpha_fraction": 0.614814817905426, "alphanum_fraction": 0.6518518328666687, "avg_line_length": 15.875, "blob_id": "a65d584224f4c27c1cfc20567f18767bfd546274", "content_id": "3e0a829911604601b9d138a29a421cdee0cf9f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 271, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/Accent-iOS/Accent/Accent/UserAccount.swift", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "//\n// UserAccount.swift\n// Accent\n//\n// Created by Aidan Gadberry on 11/14/16.\n// Copyright © 2016 agadberr. All rights reserved.\n//\n\nimport Foundation\n\nstruct Account {\n let firstname : String\n let lastname : String\n let password : String\n let email : String\n}\n" }, { "alpha_fraction": 0.6810673475265503, "alphanum_fraction": 0.7242693901062012, "avg_line_length": 48.25, "blob_id": "1643f4f05cf7d53f78491f60bc75deb252f183d3", "content_id": "460004d80ec9379055ad0fcf3f40e0f10ef413dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 787, "license_type": "no_license", "max_line_length": 82, "num_lines": 16, "path": "/Sprint1/README.md", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "# Sprint 1 Plan\n* Product Name: Accent\n* Team Name: Accent Team\n* Sprint Completion Date: Wednesday, Oct 19th, 2016\n* Revision Number: 1\n* Revision Date: Tuesday Oct 4th, 2016\n\n## iOS Front End and Voice Recognition and Voice Synthesis API integration.\n* US1: As a user, I want the app to be able to recognize what I'm saying.\n\t- Task 1: Button that Activates Voice Recognition API. (1-2 hours)\n\t- Task 2: Taking output from API and displaying on screen. (1 hour)\n* US2: As a user, I want the app to be able to synthesize my speech.\n\t- Task 1: Initialize Voice Synthesis iOS 10 API. (2-3 hours)\n\t- Task 2: Reading out string from US1. (2-3 hours)\n* US3: As a user, I want to be able to create an account.\n\t- Task 1: Leverate Laravel (or just PHP/MySQL) for account db setup. (5-10 hours)" }, { "alpha_fraction": 0.7124999761581421, "alphanum_fraction": 0.7124999761581421, "avg_line_length": 26, "blob_id": "c6de8e8b94c14f72f3d44e8c96e848fd494c351b", "content_id": "a33dbcafe98abf50fc8b5419472e215aada4ad69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/test_script.py", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "# Parameters: string\ndef demoCall(query):\n\treturn 'Your query is ' + str(query);" }, { "alpha_fraction": 0.6412884593009949, "alphanum_fraction": 0.6412884593009949, "avg_line_length": 28.7391300201416, "blob_id": "990e5b6c817b3789540467cd806507a1a7fc2a9a", "content_id": "8830c1914d9db3073d33d57dafee08223cc035c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 128, "num_lines": 23, "path": "/NLP/test.py", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "from grammar_corrections import corrector\nfrom ngram import ngrammer\nimport unittest\n\n\n\nclass NgramTest(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.ng = ngrammer()\n\n\tdef testSanitize(self):\n\t\tself.assertEqual(self.ng.sanitize(\"Is that you're cup?\"), \"Is that you're cup\")\n\n\tdef testTrigramExtraction(self):\n\t\tself.assertEqual(self.ng.extractTrigrams(\"Is that you're cup\"), {('Is', 'that', 'you', \"'re\"), ('that', 'you', \"'re\", 'cup')})\n\n\tdef testConstructBody(self):\n\t\tself.assertEqual(self.ng.constructBody({('I', 'think', 'its', 'a'), ('think', 'its', 'a', 'cup')}), \\\n\t\t\t\t\t\t\t\t\t\t\t{'queries': ['I think its a', 'think its a cup']})\n\nif __name__ == \"__main__\": \n unittest.main()" }, { "alpha_fraction": 0.6732283234596252, "alphanum_fraction": 0.6929134130477905, "avg_line_length": 19.31999969482422, "blob_id": "350e9729cd8e429bb44ff8a6ef640a7a9701b17b", "content_id": "b131cfcd3b7d99d1b079286291697560414f253a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 508, "license_type": "no_license", "max_line_length": 66, "num_lines": 25, "path": "/Accent-iOS/Accent/Podfile", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "source 'https://github.com/CocoaPods/Specs.git'\n\n# Uncomment this line to define a global platform for your project\nplatform :ios, '10.0'\n\ntarget 'Accent' do\n use_frameworks!\n\n # Pods for Accent\n pod 'TextFieldEffects', '~> 1.3.0'\n\n pod 'Alamofire', '~> 4.0'\n\n pod 'SCLAlertView'\n\n pod 'SwiftyJSON'\nend\n\npost_install do |installer|\n installer.pods_project.targets.each do |target|\n target.build_configurations.each do |config|\n config.build_settings['SWIFT_VERSION'] = '3.0'\n end\n end\nend\n" }, { "alpha_fraction": 0.6600000262260437, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 24.125, "blob_id": "e26f79fdd318b22aad6e6002487cf835ec4dcf9d", "content_id": "60898ba3fcd6e0b1cc1b5dd7690a24c7df432c63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/NLP/demo.py", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "from grammar_corrections import corrector\nimport sys\n\ncc = corrector()\nif int(sys.argv[1]) == 1:\n\tcc.check(\"Is that you're cup?\")\nelif int(sys.argv[1]) == 2:\n\tcc.check(\"Whos is that, is it Albert's?\")" }, { "alpha_fraction": 0.7313432693481445, "alphanum_fraction": 0.7416045069694519, "avg_line_length": 37.32143020629883, "blob_id": "cd3291856fe4065e4f70e443ae998c4b85578a31", "content_id": "82b7d8f7f9ec8a5513821fb049db625624f1cc7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1072, "license_type": "no_license", "max_line_length": 76, "num_lines": 28, "path": "/README.md", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "## Release Plan\n* Product Name: Accent\n* Team Name: Accent Team\n* Release Name: Grammar Correction with Voice Recognition & Synthesis\n* Revision Number: 1\n* Revision Date: October 3rd, 2016\n\n---\n\n## High Level Goals\n* Detect grammatical errors, and then correct them.\n* Convert speech audio to text using Voice Recognition Software\n* Synthesize the corrected text into speech using Speech Synthesis software\n* User Accounts and backend to store past queries.\n\n---\n\n## User Stories for Release\n* Sprint 1 - Leverage iOS 10 API\n\t* As a user, I want the app to be able to recognize what I'm saying.\n\t* As a user, I want the app to be able to synthesize my speech.\n\t* As a user, I want to be able to create an account.\n* Sprint 2 - Attempt Grammar Corrections\n\t* As a user, I want to be able to do basic grammar corrections.\n\t* As a user, I want to be able to hear the app say the grammar corrections.\n* Spring 3 - Better Grammar Corrections\n\t* As a user, I want to be able to do more complex grammar corrections.\n\t* As a user, I want to be able to see my past speech queries." }, { "alpha_fraction": 0.6834532618522644, "alphanum_fraction": 0.7140287756919861, "avg_line_length": 33.75, "blob_id": "63d2ba331ad2fb04115ca4560229a1fe7c729225", "content_id": "a34b56f117db8a58dceed6da7f5147662fb987ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 556, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/Sprint2/README.md", "repo_name": "tazjel/Accent", "src_encoding": "UTF-8", "text": "# Sprint 2 Plan\n* Product Name: Accent\n* Team Name: Accent Team\n* Sprint Completion Date: Friday, Nov 4th, 2016\n* Revision Number: 1\n* Revision Date: Friday, Oct 28th, 2016\n\n## iOS Voice Synthesis & POST Requests\n* US1: As a user, I want to be able to hear the string.\n* US2: As a developer, I want to be able to query a python script via a POST Request.\n\n## Backend\n* US1: As a developer, I want the db to stay unlocked (R/W enable).\n\n## Grammar Checker using N-gram corpus (NLTK corpus)\n* US1: As a developer, I want to be able to train my n-gram model.\n" } ]
17
Coldlapse/SadangBot
https://github.com/Coldlapse/SadangBot
aa94d2404fd1bb38aa6268204a743c92b2c58ec7
178c38866881acf119ec0a34ddb85ce5450277e4
ad1495b89ab8c994fccfcc92a800ee15e87b79ae
refs/heads/main
2023-03-28T04:49:53.498886
2021-03-27T11:16:40
2021-03-27T11:16:40
352,053,526
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5537596344947815, "alphanum_fraction": 0.5843288898468018, "avg_line_length": 40.260868072509766, "blob_id": "df4923459c1ccefcf05b7b6f607f88cb5073a155", "content_id": "c5f80851d9cdec41c10f289a7139db122dbd1fb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2900, "license_type": "no_license", "max_line_length": 153, "num_lines": 69, "path": "/SadangBot.py", "repo_name": "Coldlapse/SadangBot", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nimport time\nimport random\n\nrandomwaittime = random.randrange(1, 300)\nprint(\"Random Wait Time : \" + str(randomwaittime), flush=True)\ntime.sleep(randomwaittime)\nprint(\"Starting Job\", flush=True)\n\nwith Display():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\")\n driver = webdriver.Chrome(options=chrome_options)\n try:\n driver.implicitly_wait(3)\n\n login=1\n\n id='' # 자신의 디씨 ID 입력\n pw='' # 자신의 디씨 PW 입력\n\n if login==1 :\n\n # 로그인\n driver.get('https://gall.dcinside.com/')\n time.sleep(1)\n\n driver.find_element_by_xpath(\"//a[contains(text(),'로그인')]\").click()\n time.sleep(1)\n\n driver.find_element_by_id('id').send_keys(id)\n time.sleep(1)\n\n driver.find_element_by_id('pw').send_keys(pw)\n time.sleep(1)\n\n driver.find_element_by_xpath(\"//button[@class='btn_blue small btn_wfull']\").click()\n time.sleep(1)\n\n print(\"Log-in Successful\", flush=True)\n\n # 관리 페이지 이동\n driver.get(f'https://gall.dcinside.com/mgallery/management?id=electronicmoney')\n time.sleep(1)\n nonmember = driver.find_elements_by_xpath(\"//button[@class='font_lightblue set_modify']\")\n time.sleep(1)\n nonmember[5].click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[2]/div/div\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[2]/div/ul/li[4]\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[1]/div/div\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[1]/div/ul/li[4]\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[1]/button\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[1]/div[1]/div[2]/button\").click()\n time.sleep(1)\n driver.find_element_by_xpath(\"//*[@id='right_cont_wrap']/div/fieldset/div[9]/div/div[3]/div[2]/button[1]\").click()\n time.sleep(1)\n\n print(\"Job Finished\", flush=True)\n\n finally:\n driver.quit()" }, { "alpha_fraction": 0.6979166865348816, "alphanum_fraction": 0.6979166865348816, "avg_line_length": 31, "blob_id": "fd144c16fd65533584dde6028612f8f551914696", "content_id": "b30da769df93648b56c5d6623b9da641f5e28e9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 204, "license_type": "no_license", "max_line_length": 46, "num_lines": 3, "path": "/README.md", "repo_name": "Coldlapse/SadangBot", "src_encoding": "UHC", "text": "# SadangBot\n 디시인사이드 마이너 갤러리 매니저, 부매니저를 위한 통피차단 갱신 프로그램입니다.\n 코드의 'id', 'pw'를 적절히 수정후 사용해주시면 됩니다.\n" } ]
2
vladharl/example
https://github.com/vladharl/example
781bc5c00e2715ad3ad0b7dc8131b984df17f982
4f85834af3590fdfe9550f7548fa46a5ffa3badb
7a4d887d8c7c252884582e5da02c628682c51341
refs/heads/master
2020-05-17T15:05:56.356457
2019-04-27T14:42:14
2019-04-27T14:42:14
183,781,192
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6229507923126221, "alphanum_fraction": 0.6475409865379333, "avg_line_length": 11.300000190734863, "blob_id": "b9b95e715b007ecbcf7e2ee15ca4c8fe80961884", "content_id": "2f9305e0525966424388bc84cca26f9ce60e8662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 18, "num_lines": 10, "path": "/main.py", "repo_name": "vladharl/example", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nprint(\"test\")\n\ndef main(msg):\n print(msg)\n\t//diff comment\nmain(\"hello2\")\n\n\t//Print stuff\n\t//comment3" }, { "alpha_fraction": 0.8399999737739563, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 12, "blob_id": "379ef2e45e130826bf49d4eb9cb2e6c48bb3813f", "content_id": "8ebc6f3cd9dc99ca979ba8b97c911af9b6e25cea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "vladharl/example", "src_encoding": "UTF-8", "text": "# example\ntesting project" } ]
2
PaulEmmanuelSotir/TPs_3IF
https://github.com/PaulEmmanuelSotir/TPs_3IF
87116bcf91d7f871f77bef26e35684f02c5ece87
51e1b82837bd2e9e01fe84721f127c469f1f24a7
7c82ece01341a445b10f5cccd1ff7c8614e1c5a2
refs/heads/master
2021-06-01T15:55:23.452046
2016-05-24T13:54:53
2016-05-24T13:54:53
43,512,483
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5919055938720703, "alphanum_fraction": 0.6121416687965393, "avg_line_length": 16.441177368164062, "blob_id": "af0b4dd0c29dd97d3b8dafbb57db02cd55759603", "content_id": "805964f3f215177acc3fb004a20de1adf0409197", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 593, "license_type": "permissive", "max_line_length": 110, "num_lines": 34, "path": "/TP4_cpp/tests/mktest.sh", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "echo \"Test ID;Return code validation;Out result;StdErr result;File creation result;Global result\" >results.csv\nnOk=0\nnKo=0\nnTotal=0\nnMis=0\n\nif [ \"$1\" = \"\" ]\nthen\n\tDirectory=\".\"\nelse\n\tDirectory=\"$1\"\nfi\n\nfor i in $Directory/Test*\ndo\n\t$Directory/test.sh $i results.csv\n\tresult=$?\n\tif [ $result -eq 0 ]\n\tthen\n\t\tlet \"nKo=$nKo+1\"\n\telif [ $result -eq 1 ]\n\tthen\n\t\tlet \"nOk=$nOk+1\"\n\telse\n\t\tlet \"nMis=$nMis+1\"\n\tfi\n\tlet \"nTotal=$nTotal+1\"\ndone\n\necho \"Passed tests : $nOk\"\necho \"Failed tests : $nKo\"\necho \"Misformed tests : $nMis\"\necho \"-----------------------\"\necho \"Total : $nTotal\"\n" }, { "alpha_fraction": 0.665217399597168, "alphanum_fraction": 0.6695652008056641, "avg_line_length": 27.75, "blob_id": "da0ca7d42c6d6881fe0698e4e97895b0b5d84476", "content_id": "e8799532edcdffa3394f106e512124e05da552f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 230, "license_type": "permissive", "max_line_length": 47, "num_lines": 8, "path": "/TD4_ALG/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "C_FLAGS = -Wall -O3\n\nEXE: hash_table.o main.o\n\tgcc hash_table.o main.o -o EXE\nmain.o: main.c hash_table.h\n\tgcc $(C_FLAGS) -c main.c -o main.o\nhash_table.o: hash_table.c hash_table.h\n\tgcc $(C_FLAGS) -c hash_table.c -o hash_table.o\n" }, { "alpha_fraction": 0.5058436989784241, "alphanum_fraction": 0.5149744153022766, "avg_line_length": 27.226804733276367, "blob_id": "3bb0707eef47733a4becd1d894c40d762d253a0b", "content_id": "d64d63c70dc530668f51496adcbb78251a6140a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2740, "license_type": "permissive", "max_line_length": 118, "num_lines": 97, "path": "/TP1_Concurrency/source/process_utils.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tProcess utils - aide a la manipulation de processus\n\t\t\t---------------------------------------------------\n\tdebut \t\t\t : 20/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//-------------------------------------------------------- Include systeme\n#include <string>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include <mqueue.h>\n#include <sys/ipc.h>\n#include <sys/shm.h>\n#include <sys/sem.h>\n#include <sys/stat.h>\n#include <functional>\n#include <sys/types.h>\n\n//------------------------------------------------------ Include personnel\n#include \"process_utils.h\"\n#include \"Outils.h\"\n\n/////////////////////////////////////////////////////////////////// PRIVE\n//------------------------------------------------------ Fonctions privees\nnamespace\n{\n\tbool create_or_open_message_queue(ipc_id_t& msqid, int id, int perm, std::string path, int flags)\n\t{\n\t\tkey_t key = ftok(path.data(), id);\n\t\tif (key == -1)\n\t\t\treturn false;\n\t\tmsqid = msgget(key, perm | flags);\n\t\treturn msqid >= 0;\n\t}\n}\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//----------------------------------------------------- Fonctions publique\npid_t fork(const std::function<void(void)>& code_fils, const std::function<void(pid_t)>& code_pere)\n{\n\tpid_t fils_pid;\n\n\tif ((fils_pid = fork()) == 0)\n\t\tcode_fils();\n\telse\n\t\tcode_pere(fils_pid);\n\n\treturn fils_pid;\n}\n\nbool open_message_queue(ipc_id_t& msqid, int id, int permission, std::string path)\n{\n\treturn create_or_open_message_queue(msqid, id, permission, path, 0);\n}\n\nbool create_message_queue(ipc_id_t& msqid, int id, int permission, std::string path, bool fail_if_exist)\n{\n\treturn create_or_open_message_queue(msqid, id, permission, path, fail_if_exist ? (IPC_CREAT | IPC_EXCL) : IPC_CREAT);\n}\n\nbool delete_message_queue(ipc_id_t msqid)\n{\n\treturn msgctl(msqid, IPC_RMID, nullptr) != -1;\n}\n\nbool delete_shared_memory(ipc_id_t id)\n{\n\treturn (shmctl(id, IPC_RMID, nullptr) != -1);\n}\n\nbool sem_pv(ipc_id_t sems_id, short unsigned int sem_num, short num_to_add)\n{\n\tsembuf sem_buf{ sem_num, num_to_add, 0 };\n\tint rslt = 0;\n\n\tdo { rslt = semop(sems_id, &sem_buf, 1); } while (rslt == -1 && errno == EINTR);\n\n\treturn rslt >= 0;\n}\n\nbool lock(ipc_id_t sems_id, short unsigned int sem_num, const std::function<void(void)>& func)\n{\n\t// Decremente la semaphore\n\tif (!sem_pv(sems_id, sem_num, -1))\n\t\treturn false;\n\n\t// Execute le code protégé par la semaphore\n\tfunc();\n\n\t// Incremente la semaphore\n\treturn sem_pv(sems_id, sem_num, 1);\n}\n" }, { "alpha_fraction": 0.5842105150222778, "alphanum_fraction": 0.5931174159049988, "avg_line_length": 36.42424392700195, "blob_id": "dfd302a7b206029eaaa7f5077c52357d1b35434b", "content_id": "bb3e0bcead59428101dc6cd16aaf7f0741f50dae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2477, "license_type": "permissive", "max_line_length": 112, "num_lines": 66, "path": "/TP1_Concurrency/include/gestionEntree.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tGestion entree - tache gerant les barrieres d'entree\n\t\t\t----------------------------------------------------\n\tdebut \t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//--- Interface du module <GESTION_ENTREE> (fichier gestionEntree.h) -----\n#ifndef GESTION_ENTREE_H\n#define GESTION_ENTREE_H\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//--------------------------------------------------- Interfaces utilisées\n#include <array>\n#include \"Outils.h\"\n#include \"process_utils.h\"\n\n//------------------------------------------------------------------ Types\n//! Type contenant les information nescessaires sur une voiture\n//! Ce type est utilise sur de la memoire partagee.\nstruct car_info\n{\n\t// Les constructeurs ne sont plus nescessaires en C++14 pour avoir des initilizer list + des valeurs par defaut\n\tcar_info() = default;\n\tcar_info(unsigned int num, TypeUsager type, time_t t)\n\t\t: car_number(num), user_type(type), heure_arrivee(t) { };\n\tvolatile unsigned int car_number = 0U;\n\tvolatile int user_type = AUCUN;\n\tvolatile time_t heure_arrivee = 0;\n};\n\n//! Represente une requete d'un voiture voulant entrer dans le parking plein\n//! Ce type est utilise sur de la memoire partagee.\nstruct request\n{\n\t// Les constructeurs ne sont plus nescessaires en C++14 pour avoir des initilizer list + des valeurs par defaut\n\trequest() = default;\n\trequest(TypeUsager t, time_t h) : type(t), heure_requete(h) { };\n\tvolatile TypeUsager type = AUCUN;\n\tvolatile time_t heure_requete = 0;\n};\n\n//! Struture contenant le prochain id donne a une voiture et le nombre de\n//! voitures dans le parking.\n//! Ce type est utilise sur de la memoire partagee.\nstruct parking\n{\n\tvolatile unsigned int next_car_id = 1U;\n\tvolatile unsigned int car_count = 0U;\n\tbool is_full() const { return car_count >= NB_PLACES; }\n};\n\n//! Ce type est utilise sur de la memoire partagee.\nstruct places\n{ car_info places[NB_PLACES]; };\n\n//! Ce type est utilisé sur de la memoire partagée.\nstruct waiting_cars\n{ request waiting_fences[NB_BARRIERES_ENTREE]; };\n\n//---------------------------------------------------- Fonctions publiques\n//! Démare la tache gèrant la barrière identifiée par sont type (TypeBarriere)\n//! Retourne le PID du processus fils ou -1 en cas d'echec.\npid_t ActiverPorte(TypeBarriere t);\n\n#endif // GESTION_ENTREE_H\n" }, { "alpha_fraction": 0.6523236036300659, "alphanum_fraction": 0.6632243394851685, "avg_line_length": 22.876712799072266, "blob_id": "29d5b1e8f59a175ec7ff699a4572fa38a95c18a6", "content_id": "dbe7900dfc4ba7494dd13be6cb274aee4b906f0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1743, "license_type": "permissive", "max_line_length": 88, "num_lines": 73, "path": "/TP4_cpp/src/Serializable_shape_history.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"Serializable_shape_history.h\"\n\nnamespace TP4\n{\n\tconst History_state& Shape_history::current() const\n\t{\n\t\treturn *m_current_state;\n\t}\n\n\tHistory_state& Shape_history::current()\n\t{\n\t\treturn *m_current_state;\n\t}\n\n\tvoid Shape_history::commit()\n\t{\n\t\tif(m_history.size() > 0)\n\t\t{\n\t\t\tif(std::distance(m_current_state, std::end(m_history)) > 1)\n\t\t\t\tm_history.erase(m_current_state + 1, std::end(m_history));\n\t\t\tm_history.push_back(m_history.back());\n\n\t\t\t// Delete old history state (user can undo from 20 to 40 actions)\n\t\t\t// We delete old history state by groups of 20 for perfomance reasons\n\t\t\tif (m_history.size() > 40U)\n\t\t\t\tm_history.erase(std::begin(m_history), std::begin(m_history) + 20U);\n\n\t\t\tm_current_state = std::end(m_history)-1;\n\t\t}\n\t}\n\n\tvoid Shape_history::undo()\n\t{\n\t\tif (m_history.size() > 0 && std::distance(std::begin(m_history), m_current_state) > 0)\n\t\t\t--m_current_state;\n\t\telse\n\t\t\tthrow std::logic_error(\"Cannot undo anymore.\");\n\t}\n\n\tvoid Shape_history::redo()\n\t{\n\t\tif (m_history.size() > 0 && std::distance(m_current_state, std::end(m_history)) > 1)\n\t\t\t++m_current_state;\n\t\telse\n\t\t\tthrow std::logic_error(\"Cannot redo anymore.\");\n\t}\n\n\tvoid Shape_history::clear()\n\t{\n\t\tm_history = { History_state() };\n\t\tm_current_state = std::begin(m_history);\n\t}\n\n\tHistory_shape History_shape::clone() const\n\t{\n\t\treturn m_self->polymorphic_clone();\n\t}\n\n\tbool Is_contained(const History_shape& history_obj, Point point)\n\t{\n\t\treturn history_obj.m_self->polymorphic_is_contained(std::move(point));\n\t}\n\n\tHistory_shape Move(const History_shape& history_obj, coord_t dx, coord_t dy)\n\t{\n\t\treturn history_obj.m_self->polymorphic_move(dx, dy);\n\t}\n\n\tvoid Print(const History_shape& history_obj)\n\t{\n\t\thistory_obj.m_self->polymorphic_print();\n\t}\n}\n" }, { "alpha_fraction": 0.49129703640937805, "alphanum_fraction": 0.5120718479156494, "avg_line_length": 19.941177368164062, "blob_id": "770f5b9982f30ba313ff283772f7501d38096e62", "content_id": "af0c84cedbca18c705368541e3696d675e1c413c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1781, "license_type": "permissive", "max_line_length": 56, "num_lines": 85, "path": "/TD4_ALG/main.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#include \"hash_table.h\"\n\n#define HASH_TABLE_REPETITION 1\n//#define DEFAULT_HASH_TABLE_SIZE 100\n\nvoid error(void);\n\nint main(void) \n{\n int size;\n char lecture[100];\n \n char * key;\n char * val;\n hash_table table;\n\n if (fscanf(stdin,\"%99s\", lecture)!=1)\n error();\n while (strcmp(lecture,\"bye\")!=0)\n {\n if (strcmp(lecture,\"init\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n size = atoi(lecture);\n\t\t \n // code d'initialisation\n\t\t init_hash_table(&table, HASH_TABLE_REPETITION, size);\n }\n else if (strcmp(lecture,\"insert\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n val = strdup(lecture);\n\t\t \n // insertion\n\t\t insert_to_table(&table, key, val);\n }\n else if (strcmp(lecture,\"delete\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n\t\t \n // suppression\n\t\t remove_from_table(&table, key); \n }\n else if (strcmp(lecture,\"query\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n\t\t\t\n // recherche et affiche le resultat\n\t\t find_in_table(&table, key);\t\t \n }\n else if (strcmp(lecture,\"destroy\")==0)\n {\n // destruction\n\t\t destr_hash_table(&table);\n }\n else if (strcmp(lecture,\"stats\")==0)\n {\n // statistiques\n\t\t show_stats(&table);\n }\n\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n }\n return 0;\n}\n\nvoid error(void)\n{\n printf(\"input error\\r\\n\");\n exit(0);\n}\n\n" }, { "alpha_fraction": 0.6550060510635376, "alphanum_fraction": 0.6568154692649841, "avg_line_length": 19.962024688720703, "blob_id": "53947689905121c61f02a5be999e793d0b6f9d46", "content_id": "8f2bf86b3395489a296f2bee4c4ace406f241787", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1658, "license_type": "permissive", "max_line_length": 77, "num_lines": 79, "path": "/GenericCppMakefile/Makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "\n# Debug mode (comment this line to build project in release mode)\nDEBUG = true\n\n# Compiler\nCC = g++\n# Command used to remove files\nRM = rm -f\n# Compiler and pre-processor options\nCPPFLAGS = -Wall -std=c++14 -O3 \n# Resulting program file name\nEXE_NAME = a.out\n# The source file extentions\nSRC_EXT = cpp\n# The header file types\n# TODO allow .hpp header files\nHDR_EXT = h\n\n# Source directory\nSRCDIR = source\n# Headers directory\nINCDIR = includes\n# Main output directory\nOUTPUT_DIR = bin\n# Dependencies path\nDEP_PATH = ./$(OUTPUT_DIR)/.d\n# Release output directory\nRELEASEDIR = release\n# Debug output directory\nDEBUGDIR = debug\n# Libraries paths\nLIBS = \n# Additional include paths\nINCLUDES = \n\nifdef DEBUG\nCPPFLAGS = $(CPPFLAGS) -g\nBUILD_PATH = ./$(OUTPUT_DIR)/$(DEBUGDIR)\nelse\nBUILD_PATH = ./$(OUTPUT_DIR)/$(RELEASEDIR)\nendif\n\n# List of include paths\nINCLUDES = ./$(INCDIR) $(INCLUDES)\n# List of source files\nSOURCES = $(wildcard *.$(SRC_EXT))\n# List of object files\nOBJS = $(SOURCES:%.$(SRC_EXT)=$(BUILD_PATH)/%.o)\n# List of dependency files\nDEP = $(SOURCES:%.$(SRC_EXT)=$(DEP_PATH)/%.d)\n# Source directory path\nSRC_PATH = ./$(SRCDIR)\n\n\n.PHONY: all clean rebuild help\n\nall: $(EXE_NAME)\n\nclean:\n\t$(RM) $(BUILD_PATH)/*.o\n\t$(RM) $(BUILD_PATH)/$(EXE_NAME)\n\t\nrebuild: clean all\n\nhelp:\n\techo '\t\t\t\t### MAKEFILE HELP ###'\n\techo 'TARGETS:'\n\techo '\tall \t...'\n\techo '\tclean \t...'\n\techo '\trebuild ...'\n\techo '\thelp\t...'\n\n# Build object files\n# TODO: generate dependency files\n$(BUILD_PATH)/%.o: $(SRC_PATH)/%.$(SRC_EXT)\n\t$(CC) $(CPPFLAGS) -I $(INCLUDES) $(SRC_PATH) -l $(LIBS) -MMD -MP -c $< -o $@\n\n# Build main target\n$(EXE_NAME): $(OBJS)\n\t$(CC) $(OBJS) -o $(EXE_NAME)\n\n" }, { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 9.333333015441895, "blob_id": "a9a879d458a0adffefca04c3b76acb981d5e468b", "content_id": "950be09c955987c602d9de49d57318ddef68adb1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 31, "license_type": "permissive", "max_line_length": 13, "num_lines": 3, "path": "/TD_Archi_cache/N.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef N\n#define N 400\n#endif\n" }, { "alpha_fraction": 0.5824877023696899, "alphanum_fraction": 0.5998363494873047, "avg_line_length": 17.400602340698242, "blob_id": "869f6ef58ecc6df1d9a723dbb8b9d7e3013c32e1", "content_id": "32274e422f76ff90e4d03b287553ccd30b64952c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6110, "license_type": "permissive", "max_line_length": 83, "num_lines": 332, "path": "/TP2_Concurrency/question10.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <limits.h>\n\n#define MAX_FACTORS 20\n\ntypedef enum { empty, used, deleted } status;\n\ntypedef struct\n{\n\tsize_t size;\n\tuint64_t* factors;\n} value_t;\n\ntypedef struct\n{\n\tstatus state;\n\tuint64_t key;\n\tvalue_t value;\n} cell;\n\ntypedef struct\n{\n\tunsigned int m;\n\tcell* array;\n\tunsigned int array_step;\n\tunsigned int array_size;\n\tunsigned int deleted_count;\n\tunsigned int used_count;\n} hash_table;\n\nstatic unsigned int hash(uint64_t value, uint64_t m);\nstatic unsigned int find_index_of(hash_table* table, uint64_t val, unsigned int h);\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, uint64_t m);\nvoid destr_hash_table(hash_table* table);\nvoid insert_to_table(hash_table* table, uint64_t key, value_t value);\nvoid remove_from_table(hash_table* table, uint64_t key);\nvalue_t find_in_table(hash_table* table, uint64_t key);\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, uint64_t m)\n{\n\tif (table != NULL)\n\t{\n\t\ttable->m = m;\n\t\ttable->array_size = repetition*m;\n\t\ttable->array_step = repetition;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\n\t\ttable->array = (cell*)malloc(table->array_size*sizeof(cell));\n\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tc->state = empty;\n\t\t\tc->key = NULL;\n\t\t\tc->value = NULL;\n\t\t}\n\t}\n}\n\nvoid destr_hash_table(hash_table* table)\n{\n\tif (table != NULL)\n\t{\n\t\t// Free all allocated strings\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tif (c != NULL)\n\t\t\t{\n\t\t\t\tif (c->value != NULL)\n\t\t\t\t\tfree(c->value);\n\t\t\t}\n\t\t}\n\n\t\t// Free table of cells\n\t\tfree(table->array);\n\t\ttable->array = NULL;\n\n\t\ttable->array_size = 0;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\t}\n}\n\nvoid insert_to_table(hash_table* table, uint64_t key, value_t value)\n{\n\tif (table != NULL && key != NULL && value != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\t// update cell value\n\t\t\tcell* c = &table->array[idx];\n\t\t\tfree(c->value);\n\t\t\tc->value = value;\n\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tunsigned int i;\n\t\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t\t{\n\t\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\t\tif (c->state == deleted)\n\t\t\t\t{\n\t\t\t\t\tif (c->key == key)\n\t\t\t\t\t{\n\t\t\t\t\t\tc->state = used;\n\t\t\t\t\t\ttable->used_count++;\n\t\t\t\t\t\tc->value = value;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (c->state == empty)\n\t\t\t\t{\n\t\t\t\t\tc->state = used;\n\t\t\t\t\ttable->used_count++;\n\t\t\t\t\tc->key = key;\n\t\t\t\t\tfree(c->value);\n\t\t\t\t\tc->value = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfree(value);\n}\n\nvoid remove_from_table(hash_table* table, uint64_t key)\n{\n\tif (table != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\tcell* c = &table->array[idx];\n\t\t\tif (c->state == used) // TODO: useless if ?\n\t\t\t{\n\t\t\t\ttable->used_count--;\n\t\t\t\tc->state = deleted;\n\t\t\t\ttable->deleted_count++;\n\n\t\t\t\tfree(c->value);\n\t\t\t\tc->value = NULL;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvalue_t find_in_table(hash_table* table, uint64_t key)\n{\n\tif (table != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\t\t\n\t\tif (idx < table->array_size)\n\t\t\treturn table->array[idx].value;\n\t}\n\treturn NULL;\n}\n\nstatic unsigned int find_index_of(hash_table* table, uint64_t key, unsigned int h)\n{\n\tif (table != NULL)\n\t{\n\t\tunsigned int i;\n\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\tif (c->state == used)\n\t\t\t{\n\t\t\t\tif (c->key == key)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn UINT_MAX;\n}\n\n/* fonction de hachage d'une valeur sur 64 bits */\nstatic unsigned int hash(uint64_t key, uint64_t m)\n{\n\treturn key*2654435761 % m;\n}\n\nstatic pthread_mutex_t mutexRead;\nstatic pthread_mutex_t mutexWrite;\nstatic pthread_mutex_t hash_mutex;\n\n/*int get_prime_factors(uint64_t n, uint64_t* dest)\n{\n uint64_t i = 0;\n int cpt = 0;\n uint64_t nPrime = n;\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime % i == 0)\n\t\t{\n\t\t\tif(cpt < MAX_FACTORS)\n\t\t\t{\n\t\t\t\tdest[cpt++] = i;\n\t\t\t}\n\t\t\tnPrime = nPrime/i;\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn cpt;\n}*/\n\nint get_prime_factors(uint64_t n, uint64_t* dest)\n{\n uint64_t i = 0;\n int cpt = 0;\n uint64_t nPrime = n;\n \n for( i = 2 ; i <= nPrime;)\n {\n\t\tif(nPrime % i == 0)\n\t\t{\n\t\t\tif(cpt < MAX_FACTORS)\n\t\t\t{\n\t\t\t\tdest[cpt++] = i;\n\t\t\t}\n\t\t\t\n\t\t\tvalue_t result = find_in_table(&table, nPrime);\n\t\t\tif(result != NULL)\n\t\t\t{\n\t\t\t\tmemcpy(*dest[cpt], result.factors, sizeof(uint64_t*result.size));\n\t\t\t\tinsert_to_table(&table, nPrime, result);\n\t\t\t\treturn cpt;\n\t\t\t}\n\t\t\t\n\t\t\tnPrime = nPrime/i;\n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\ti++;\n\t}\n\treturn cpt;\n}\n\nstatic hash_table table;\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t factors[MAX_FACTORS];\n\tint j,k;\n\tk=get_prime_factors(n,factors);\n\tpthread_mutex_lock(&mutexWrite);\n\tprintf(\"%ju: \",n);\n\tfor(j=0; j<k; j++)\n\t{\n\t\tprintf(\"%ju \",factors[j]);\n\t}\n\tprintf(\"\\n\");\n\tpthread_mutex_unlock(&mutexWrite);\n}\n\nvoid decompo_task(FILE* file)\n{\n\tchar line[60];\n\t\n\twhile(1)\n\t{\n\t\tpthread_mutex_lock(&mutexRead);\n\t\tif(fgets(line, 60, file) == NULL)\n\t\t{\n\t\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\tbreak;\n\t\t}\n\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\n\t\tprint_prime_factors(atoll(line));\n\t\n\t}\n}\n\nvoid* print_prime_factors_thread(void* n)\n{\n\tFILE* x = ((FILE*)n);\n\tdecompo_task(x);\n\treturn NULL;\n}\n\nint main(void)\n{\n\tinit_hash_table(&table, 5, 4294967296);\n\n\tFILE* primeList;\n\tprimeList = fopen(\"primes2.txt\", \"r\");\n\t\n\tpthread_t ta;\n\tpthread_t tb;\n\t\n\tif(primeList == NULL)\n\t{\n\t\tperror(\"erreur ouverture fichier\");\n\t\texit(-1);\n\t}\n\t\n\tpthread_mutex_init(&mutexRead, NULL);\n\tpthread_mutex_init(&hash_mutex, NULL);\n\tpthread_mutex_init(&mutexWrite, NULL);\n\tpthread_create (&ta, NULL, &print_prime_factors_thread, primeList);\n\tpthread_create (&tb, NULL, &print_prime_factors_thread, primeList);\n\tpthread_join (ta, NULL);\n\tpthread_join (tb, NULL);\n\t\n return 0;\n}\n\n" }, { "alpha_fraction": 0.7318840622901917, "alphanum_fraction": 0.75, "avg_line_length": 26.600000381469727, "blob_id": "979fc139f6a7fd196f3e43a3ecdf544c3a971855", "content_id": "88de2b86343a67b8b3778da64639119c450e465e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 280, "license_type": "permissive", "max_line_length": 87, "num_lines": 10, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/Utils/Callable.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.Utils;\n\n/**\n * Interface représentant une fonction ne prenant pas de paramètres et retournant void.\n * Cette interface permet de créer un mécaniqme similaire aux pointeurs de fonctions.\n * @author B3330\n */\npublic interface Callable {\n public void call();\n}\n" }, { "alpha_fraction": 0.4780619144439697, "alphanum_fraction": 0.4847913980484009, "avg_line_length": 47.24675369262695, "blob_id": "67a27ae32d7f7886a284a6cd2df70d33fa2657d0", "content_id": "8a5cb0b87631115b8684ecfd0381292df398cdaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3726, "license_type": "permissive", "max_line_length": 79, "num_lines": 77, "path": "/TP1_Concurrency/include/Menu.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\t\t\t\t Menu.h - description\n\t\t\t\t\t\t\t -------------------\n\tdebut : Mercredi 03 fevrier 2016\n\tcopyright : (C) 2016 par Mathieu Maranzana\n\te-mail : [email protected]\n*************************************************************************/\n\n//---------- Interface du module <Menu> (fichier Menu.h) -----------------\n#ifndef MENU_H\n#define MENU_H\n\n//------------------------------------------------------------------------\n// Rôle du module <Menu>\n// Ce module est en charge de la gestion du menu (interface homme - machine)\n// de l'application multitâche gerant le parking.\n// Les commandes autorisees sont :\n// 1. e|E : declenche la fin de l'application multitâche\n// 2. p|P : declenche l'arrivee d'un usager prof\n// 3. a|A : declenche l'arrivee d'un usager autre\n// 4. s|S : declenche la sortie d'un vehicule du parking\n// Ce module se charge aussi de la mise a jour de l'ecran du TP\n// (zone <Commande> et <Message>).\n//------------------------------------------------------------------------\n\n////////////////////////////////////////////////////////////////// INCLUDE\n//--------------------------------------------------- Interfaces utilisees\n\n//------------------------------------------------------------- Constantes\n\n//------------------------------------------------------------------ Types\n\n/////////////////////////////////////////////////////////////////// PUBLIC\n//---------------------------------------------------- Fonctions publiques\nvoid Menu(void);\n// Mode d'emploi :\n// - les commandes autorisees sont :\n// 1. e|E : declenche la fin de l'application multitâche\n// 2. p|P : saisie de l'arrivee d'un usager prof\n// un usager prof peut se presenter a la porte Blaise Pascal\n// (file PROFS) ou a la porte Gaston Berger (pas de file\n// particulière)\n// le choix de cette porte suit immediatement le declenchement\n// de l'arrivee d'un usager prof\n// en cas d'erreur de saisie du numero de la porte, on reitère\n// la demande\n// 3. a|A : saisie de l'arrivee d'un usager autre\n// un usager autre peut se presenter a la porte Blaise Pascal\n// (file AUTRES) ou a la porte Gaston Berger (pas de file\n// particulière)\n// le choix de cette porte suit immediatement le declenchement\n// de l'arrivee d'un usager autre\n// en cas d'erreur de saisie du numero de la porte, on reitère\n// la demande\n// 4. s|S : declenchement de la sortie d'un vehicule du parking\n// ce declenchement est suivi de la saisie du numero de la place\n// de parking ([1,8], limite graphique) (choix de la voiture qui\n// quittera le parking)\n// bien evidemment, il est conseille de choisir une place\n// actuellement occupee par un vehicule\n// toutes les autres commandes genèrent une erreur et declenchent une\n// nouvelle saisie\n// pour les quatre commandes licites, le menu appelle la procedure\n// <Commande> en respectant la convention suivante pour les paramètres\n// (=> interfaçage possible avec le menu)\n// 1. e|E : code = 'E' et valeur = 0\n// 2. p|P : code = 'P' et valeur = numero de la porte\n// 3. a|A : code = 'A' et valeur = numero de la porte\n// 4. s|S : code = 'S' et valeur = numero de la place\n// => le prototype impose de <Commande> est donc le suivant :\n// void Commande ( char code, unsigned int valeur );\n//\n// Contrat : aucun\n//\n\n\n#endif // MENU_H\n" }, { "alpha_fraction": 0.6087504029273987, "alphanum_fraction": 0.6194522976875305, "avg_line_length": 35.8030891418457, "blob_id": "10bcbd536f82a6c6beb513fb09267e8b4f381bf6", "content_id": "9943c1367f0dd69bec1e14c18ff092d23f56c9bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9534, "license_type": "permissive", "max_line_length": 229, "num_lines": 259, "path": "/TP2_cpp/sources/ville.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/********************************************************************************************\n\t\t\t\t\t\t\t\t\t\tville.cpp\n\t\t\t\t\t\t\t\t\t\t---------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n********************************************************************************************/\n\n//--------------------------------------------------------------------------- Include systeme\n#include <iostream>\n\n//------------------------------------------------------------------------- Include personnel\n#include \"ville.h\"\n#include \"capteur_stat.h\"\n#include \"capteur_event.h\"\n\nnamespace TP2\n{\n\t//------------------------------------------------------------------------- Constructeurs\n\t\n\tville::ville()\n\t\t: m_sensor_stats(32, MAX_IDS_COUNT,\n\t\t\t[](const capteur_stat_with_events& a, const capteur_stat_with_events& b) { return a.first.get_id() == b.first.get_id(); },\n\t\t\t[](const capteur_stat_with_events& a, const capteur_stat_with_events& b) { return a.first.get_id() < b.first.get_id(); })\n\t{\n\t\tfor (size_t i = 0; i < DAYS_COUNT; i++)\n\t\t\tfor (size_t j = 0; j < HOUR_COUNT; j++)\n\t\t\t\tm_week_jam_distribution_by_hour[i][j] = pair<unsigned int, unsigned int>(0, 0);\n\t}\n\n\t//-------------------------------------------------------------------- Méthodes publiques\n\n\tvoid ville::add_sensor(capteur_event new_event)\n\t{\n\t\t// Find if this sensor (id) have already been added\n\t\tauto sensor_stats_to_find = capteur_stat_with_events(capteur_stat(new_event), vec<capteur_event>(2, MAX_EVENT_COUNT, \n\t\t\t[](const capteur_event& a, const capteur_event& b) { return a == b; },\n\t\t\t[](const capteur_event& a, const capteur_event& b) { return a < b; } )); // sensor stats with empty (capacity = 2) event vector\n\t\tauto id_idx = m_sensor_stats.find(sensor_stats_to_find);\n\n\t\tif (LIKELY(id_idx <= m_sensor_stats.MAX_ALLOCATION_SIZE))\n\t\t\t// We already know this sensor, we update its statistics...\n\t\t{\n\t\t\tauto& sens_stat_with_events = m_sensor_stats[id_idx];\n\n\t\t\t// Update sensor's global statistics\n\t\t\tsens_stat_with_events.first.update(new_event);\n\n\t\t\t// Add event to sensor's event vector\n\t\t\tsens_stat_with_events.second.add(new_event);\n\t\t}\n\t\telse\n\t\t\t// We have a new sensor ID\n\t\t{\n\t\t\t// Add new/first event to sensor's event vector\n\t\t\tsensor_stats_to_find.second.add(new_event);\n\n\t\t\tm_sensor_stats.add(sensor_stats_to_find);\n\t\t\tm_sensor_stats.sort(); // sort m_sensor_stats vector using ids\n\t\t}\n\n\t\t// Update town's global statistics\n\t\tupdate_global_week_stats(new_event);\n\t}\n\n\tvoid ville::show_day_traffic_by_hour(capteur_stat::sensor_t d7) const\n\t{\n\t\tfor (size_t i = 0; i < HOUR_COUNT; i++)\n\t\t{\n\t\t\tconst auto& stat = m_week_jam_distribution_by_hour[d7][i];\n\t\t\tstd::cout\n\t\t\t\t<< d7 << \" \"\n\t\t\t\t<< i << \" \"\n\t\t\t\t<< (stat.second == 0 ? 0 : static_cast<unsigned int>((100.0 * stat.first) / stat.second + 0.5)) << \"%\" << std::endl;\n\t\t}\n\t}\n\n\tvoid ville::show_day_traffic(capteur_stat::sensor_t d7) const\n\t{\n\t\tconst auto& stat = m_week_traffic_distribution_by_day[d7];\n\n\t\tif (stat.total_count != 0)\n\t\t\tstd::cout\n\t\t\t<< traffic::vert << \" \" << static_cast<int>((100.0 * stat.green_count) / stat.total_count + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::rouge << \" \" << static_cast<int>((100.0 * stat.red_count) / stat.total_count + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::orange << \" \" << static_cast<int>((100.0 * stat.orange_count) / stat.total_count + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::noir << \" \" << static_cast<int>((100.0 * stat.dark_count) / stat.total_count + 0.5) << \"%\" << std::endl;\n\t\telse\n\t\t\tstd::cout\n\t\t\t<< traffic::vert << \" 0%\" << std::endl\n\t\t\t<< traffic::rouge << \" 0%\" << std::endl\n\t\t\t<< traffic::orange << \" 0%\" << std::endl\n\t\t\t<< traffic::noir << \" 0%\" << std::endl;\n\t}\n\n\tvoid ville::show_optimal_timestamp(capteur_stat::sensor_t d7, capteur_stat::sensor_t h_start, capteur_stat::sensor_t h_end, const vec<capteur_stat::sensor_t>& seg_ids)\n\t{\n\t\tdouble minimal_travel_duration = std::numeric_limits<double>::max();\n\t\tcapteur_stat::sensor_t minimal_travel_start_minute = 0;\n\t\tcapteur_stat::sensor_t minimal_travel_start_hour = 0;\n\n\t\tvec<vec<capteur_event>> segments_events; // vector of each specified segment's event vector\n\n\t\tif (seg_ids.length() > 0)\n\t\t{\n\t\t\t// For each specified segment/sensor, we find and sort its events vector\n\t\t\tfor (size_t seg_it = 0; seg_it < seg_ids.length(); ++seg_it)\n\t\t\t{\n\t\t\t\t// Find find 'capteur_stat_with_events' pair representing the <seg_it>-th segment of the travel\n\t\t\t\tcapteur_stat_with_events* segment = get_sensor_stat_with_events_by_id(seg_ids[seg_it]);\n\t\t\t\tif (segment == nullptr)\n\t\t\t\t\treturn; // Specified sensor id haven't been added\n\n\t\t\t\t// Sort all events of this segment (sort by their week timestamp)\n\t\t\t\tauto& seg_events = segment->second;\n\t\t\t\tseg_events.sort();\n\n\t\t\t\t// Add segment's events vector to 'segments_events' vector (to avoid searching them again)\n\t\t\t\tsegments_events.add(seg_events);\n\t\t\t}\n\n\t\t\t// For each minutes in specified interval, we get the travel duration and find the minimal one\n\t\t\tfor (capteur_stat::sensor_t hour = h_start; hour <= h_end; ++hour)\n\t\t\t{\n\t\t\t\tfor (capteur_stat::sensor_t minute = 0; minute < MIN_COUNT; ++minute)\n\t\t\t\t{\n\t\t\t\t\t// Recurse over segments to find travel duration if we start from this minute\n\t\t\t\t\tdouble travel_duration = get_travel_duration(segments_events, seg_ids, 0, d7, hour, minute);\n\n\t\t\t\t\t// Record best travel duration and start timestamp\n\t\t\t\t\tif (travel_duration < minimal_travel_duration)\n\t\t\t\t\t{\n\t\t\t\t\t\tminimal_travel_duration = travel_duration;\n\t\t\t\t\t\tminimal_travel_start_hour = hour;\n\t\t\t\t\t\tminimal_travel_start_minute = minute;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Print results\n\t\tstd::cout\n\t\t\t<< d7 << \" \"\n\t\t\t<< minimal_travel_start_hour << \" \"\n\t\t\t<< minimal_travel_start_minute << \" \"\n\t\t\t<< static_cast<unsigned int>(minimal_travel_duration + 0.5) << std::endl;\n\t}\n\n\tcapteur_stat* ville::get_sensor_stat_by_id(capteur_stat::sensor_t id)\n\t{\n\t\tcapteur_stat_with_events* stats_with_events = get_sensor_stat_with_events_by_id(id);\n\n\t\treturn (stats_with_events == nullptr ? nullptr : &stats_with_events->first);\n\t}\n\n\t//---------------------------------------------------------------------- Méthodes privées\n\n\tvoid ville::update_global_week_stats(capteur_event new_event)\n\t{\n\t\tauto& jam_stat = m_week_jam_distribution_by_hour[new_event.d7][new_event.hour];\n\t\tjam_stat.second++;\n\n\t\tauto& stat = m_week_traffic_distribution_by_day[new_event.d7];\n\t\tstat.total_count++;\n\n\t\tswitch (new_event.get_traffic())\n\t\t{\n\t\tcase traffic::noir:\n\t\t\tjam_stat.first++;\n\t\t\tstat.dark_count++;\n\t\t\tbreak;\n\t\tcase traffic::orange:\n\t\t\tjam_stat.first++;\n\t\t\tstat.orange_count++;\n\t\t\tbreak;\n\t\tcase traffic::rouge:\n\t\t\tstat.red_count++;\n\t\t\tbreak;\n\t\tcase traffic::vert:\n\t\t\tstat.green_count++;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tinline ville::capteur_stat_with_events* ville::get_sensor_stat_with_events_by_id(capteur_stat::sensor_t id)\n\t{\n\t\t// Create dummy 'capteur_stat_with_events' object with specified id\n\t\tcapteur_event dummy_sens_event;\n\t\tdummy_sens_event.id = id;\n\t\tauto dummy_sensor_stat_to_find = capteur_stat_with_events(capteur_stat(dummy_sens_event), vec<capteur_event>());\n\n\t\t// find it in 'm_sensor_stats'\n\t\tauto sensor_stat_idx = m_sensor_stats.find(dummy_sensor_stat_to_find);\n\n\t\tif (sensor_stat_idx > m_sensor_stats.MAX_ALLOCATION_SIZE)\n\t\t\treturn nullptr; // Specified sensor id haven't been added\n\n\t\tauto& sensor_stat = m_sensor_stats[sensor_stat_idx];\n\t\treturn &sensor_stat;\n\t}\n\n\tinline capteur_event::sensor_t ville::travel_duration_of_traffic(traffic state)\n\t{\n\t\tswitch (state)\n\t\t{\n\t\tcase traffic::vert: return 1;\n\t\tcase traffic::rouge: return 2;\n\t\tcase traffic::orange: return 4;\n\t\tcase traffic::noir: return 10;\n\t\t}\n\t\treturn 0; // impossible\n\t};\n\n\tdouble ville::get_travel_duration(const vec<vec<capteur_event>>& segments_events, const vec<capteur_stat::sensor_t>& seg_ids, size_t seg_idx, capteur_stat::sensor_t d7, capteur_stat::sensor_t hour, capteur_stat::sensor_t minute)\n\t{\n\t\tif (seg_idx >= segments_events.length())\n\t\t\treturn 0; // end of recursion\n\n\t\t// Correct minute and hour counts if nescessary\n\t\thour += static_cast<unsigned int>(minute / MIN_COUNT);\n\t\tminute %= MIN_COUNT;\n\t\td7 += static_cast<unsigned int>(hour / HOUR_COUNT);\n\t\thour %= HOUR_COUNT;\n\t\td7 = (d7 - 1) % DAYS_COUNT + 1;\n\n\t\tdouble travel_duration = 0.0;\n\t\tconst vec<capteur_event>& seg_events = segments_events[seg_idx]; // current segement's events\n\n\t\t// TODO: find the first one\n\t\t// Find if we have events for this minute\n\t\tauto event_idx = seg_events.find(capteur_event(seg_ids[seg_idx], d7, hour, minute));\n\n\t\tif (event_idx <= seg_events.MAX_ALLOCATION_SIZE)\n\t\t\t// Find travel duration by taking the mean of all events traffic with the same d7, hour and minute (and id)\n\t\t{\n\t\t\tunsigned int count = 0;\n\t\t\tdouble duration_mean = 0;\n\t\t\tcapteur_event event = seg_events[event_idx];\n\t\t\tcapteur_event previous_event;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t// add event's travel duration to the mean\n\t\t\t\tduration_mean += static_cast<double>(travel_duration_of_traffic(event.get_traffic()));\n\t\t\t\tcount++;\n\n\t\t\t\tif (UNLIKELY(++event_idx >= seg_events.length()))\n\t\t\t\t\tbreak; // no more events in segment events vector\n\n\t\t\t\tevent = seg_events[event_idx];\n\t\t\t\tprevious_event = event;\n\t\t\t} while (event == previous_event); // while next events in segment_events are in the same minute\n\n\t\t\ttravel_duration += duration_mean / count;\n\t\t}\n\t\telse\n\t\t\ttravel_duration += travel_duration_of_traffic(traffic::noir); // we suppose unkown traffic to be 'traffic::noir'\n\n\t\treturn travel_duration + get_travel_duration(segments_events, seg_ids, seg_idx + 1, d7, hour, minute + static_cast<capteur_stat::sensor_t>(travel_duration + 0.5));\n\t}\n}" }, { "alpha_fraction": 0.6202130913734436, "alphanum_fraction": 0.6219406723976135, "avg_line_length": 23.985610961914062, "blob_id": "4790613ed01d19664943d10cb0576669d78abbfc", "content_id": "3ca2d6c8c0126e305b38ca5972b13c4edb630c51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3473, "license_type": "permissive", "max_line_length": 236, "num_lines": 139, "path": "/TP2_SI/services/src/main/java/metier/modele/Client.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage metier.modele;\n\nimport com.google.maps.GeoApiContext;\nimport com.google.maps.GeocodingApi;\nimport com.google.maps.model.GeocodingResult;\nimport java.io.Serializable;\nimport javax.persistence.Id;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Column;\nimport com.google.maps.model.LatLng;\n\n/**\n *\n * @author qvecchio\n */\n@Entity\npublic class Client implements Serializable{\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n @Column(unique=true)\n private String pseudo;\n private String password;\n private String nom;\n private String prenom;\n private String mail;\n private String adresse;\n private String telephone;\n private Double longitude;\n private Double latitude;\n\n public Client() {\n }\n\n public Client(String pseudo, String password, String nom, String prenom, String adresse, String mail, String telephone) {\n this.pseudo = pseudo;\n this.password = password;\n this.nom = nom;\n this.prenom = prenom;\n this.mail = mail;\n this.setAdresse(adresse);\n this.telephone = telephone;\n }\n\n public Long getId() {\n return id;\n }\n\n public String getPseudo() {\n return pseudo;\n }\n\n public String getPassword() {\n return password;\n }\n\n public String getNom() {\n return nom;\n }\n\n public String getPrenom() {\n return prenom;\n }\n\n public String getMail() {\n return mail;\n }\n\n public String getAdresse() {\n return adresse;\n }\n\n public Double getLongitude() {\n return longitude;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public String getTelephone() {\n return telephone;\n }\n\n public void setPseudo(String pseudo) {\n this.pseudo = pseudo;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\n }\n\n public void setPrenom(String prenom) {\n this.prenom = prenom;\n }\n\n public void setMail(String mail) {\n this.mail = mail;\n }\n\n public void setAdresse(String adresse) {\n this.adresse = adresse;\n GeoApiContext monGeoApi = new GeoApiContext().setApiKey(\"AIzaSyDcVVJjfmxsNdbdUYeg9MjQoJJ6THPuap4\");\n try {\n GeocodingResult[] results = GeocodingApi.geocode(monGeoApi, adresse).await();\n this.latitude = results[0].geometry.location.lat;\n this.longitude = results[0].geometry.location.lng;\n } catch(Exception e) {\n System.out.println(\"Erreur : \" + e.getMessage());\n this.latitude = 0.0;\n this.longitude = 0.0;\n }\n }\n\n public void setCoordonnees(LatLng latLng) {\n this.longitude = latLng.lng;\n this.latitude = latLng.lat;\n }\n\n public void setTelephone(String telephone) {\n this.telephone = telephone;\n }\n\n @Override\n public String toString() {\n return \"Client{\" + \"id=\" + id + \", pseudo=\" + pseudo + \", nom=\" + nom + \", prenom=\" + prenom + \", mail=\" + mail + \", adresse=\" + adresse + \", telephone=\" + telephone + \", longitude=\" + longitude + \", latitude=\" + latitude + '}';\n }\n}\n" }, { "alpha_fraction": 0.5826255083084106, "alphanum_fraction": 0.5957528948783875, "avg_line_length": 43.63793182373047, "blob_id": "2042f6b9f15ab87e710683a7644c1afdea4ab2f2", "content_id": "aebdc3e7cbf9a3a25bcbd991b00246c5d8b294f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2591, "license_type": "permissive", "max_line_length": 122, "num_lines": 58, "path": "/TP3_cpp/includes/Help_txt.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tHelp text\n\t\t\t\t\t\t\t\t\t---------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n#ifndef HELP_TXT_H\n#define HELP_TXT_H\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//! Retourne le texte d'aide du programme\n\tconstexpr const char* Help_txt() noexcept\n\t{\n\t\treturn\n\t\t\tR\"help(NAME)help\" \"\\n\"\n\t\t\tR\"help(\tlog_analyzer - Analyze Apache Log)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(SYNOPSIS)help\" \"\\n\"\n\t\t\tR\"help(\tlog_analyzer LOG_FILE [OPTION]...)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(DESCRIPTION)help\" \"\\n\"\n\t\t\tR\"help(\tAnalyzes a given apache server LOG_FILE to output a 'get' request graph or a list of most used URLs.)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(\t-g, -G, --graph)help\" \"\\n\"\n\t\t\tR\"help(\t\tCreates a graph in which each node is a URL, and each link is a successfull)help\" \"\\n\"\n\t\t\tR\"help(\t\tGET request between these nodes. Outputs GraphViz text file using specfied filename.)help\" \"\\n\"\n\t\t\tR\"help(\t\tIf this option isn't specified, the program will only output a list of most used URLs)help\" \"\\n\"\n\t\t\tR\"help(\t\t\"with their respective occurrence number (sorted in descending usage order).)help\" \"\\n\"\n\t\t\tR\"help(\t-l, -L, --listCount)help\" \"\\n\"\n\t\t\tR\"help(\t\tSpecifies the maximum number of URLs in the outputed list of most used URLs.)help\" \"\\n\"\n\t\t\tR\"help(\t\tMust be greater than 1 (10 by default).)help\" \"\\n\"\n\t\t\tR\"help(\t-e, -E, --excludeMedia)help\" \"\\n\"\n\t\t\tR\"help(\t\tExcludes css, javascript and image files from the result.)help\" \"\\n\"\n\t\t\tR\"help(\t-t, -T, --hour)help\" \"\\n\"\n\t\t\tR\"help(\t\tIgnore all log entries which haven't been added at the specfied hour (hour GMT+0000).)help\" \"\\n\"\n\t\t\tR\"help(\t-h)help\" \"\\n\"\n\t\t\tR\"help(\t\tShow this documentation)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(EXAMPLES)help\" \"\\n\"\n\t\t\tR\"help(\tlog_analyzer mylog.log --hour 12 -e)help\" \"\\n\"\n\t\t\tR\"help(\tGet top ten list of URLs used at 12th hour and which aren't images, css nor javascript files)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(\tlog_analyzer mylog.log -e -g graph.dot)help\" \"\\n\"\n\t\t\tR\"help(\tGet GET request graph of URLs which aren't images, css nor javascript files)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(\tlog_analyzer mylog.log -t 2 -l 20)help\" \"\\n\"\n\t\t\tR\"help(\tGet top 20 list of URLs used at 2th hour)help\" \"\\n\"\n\t\t\tR\"help()help\" \"\\n\"\n\t\t\tR\"help(REPORTING BUGS)help\" \"\\n\"\n\t\t\tR\"help(\tYou didn't saw any bugs.)help\" \"\\n\\n\";\n\t}\n}\n\n#endif // HELP_TXT_H\n\n" }, { "alpha_fraction": 0.5834636688232422, "alphanum_fraction": 0.5935195684432983, "avg_line_length": 46.11579132080078, "blob_id": "fda3cd1629645f83407455c881b7409ddfc23edc", "content_id": "b4449acd5706380ced9be65f48e0646c35538a84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4500, "license_type": "permissive", "max_line_length": 231, "num_lines": 95, "path": "/TP2_cpp/includes/ville.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/**************************************************************************************\n\t\t\t\t\tville - A town with sensors at each road segments\n\t\t\t\t\t---------------------------------------------------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n**************************************************************************************/\n\n//------------------------- Interface de la classe ville ------------------------------\n#pragma once\n\n//------------------------------------------------------------------ Includes personels\n#include \"capteur_stat.h\"\n#include \"capteur_event.h\"\n#include \"vec.h\"\n#include \"utils.h\"\n\nnamespace TP2\n{\n\tclass ville\n\t{\n\t\t//---------------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//-------------------------------------------------- Constructeurs destructeurs\n\t\tville();\n\n\t\t//------------------------------------------------------------- Methodes public\n\n\t\t/// <summary> mets a jour la ville avec un evenement donné en parametre (commande ADD) </summary>\n\t\t///\t<param name='new_event'> Nouveau evenement </param>\n\t\tvoid add_sensor(capteur_event new_event);\n\n\t\t/// <summary> affiche les statistiques sur les embouteillage par heure pour le jour donné en parametre (commande JAM_DH) </summary>\n\t\t///\t<param name='d7'> Jour de la semaine </param>\n\t\tvoid show_day_traffic_by_hour(capteur_stat::sensor_t d7) const;\n\n\t\t/// <summary> affiche les statistiques de trafic pour un jour de la semaine donné (commande STATS_D7) </summary>\n\t\t///\t<param name='d7'> Jour de la semaine </param>\n\t\tvoid show_day_traffic(capteur_stat::sensor_t d7) const;\n\n\t\t/// <summary> affiche le moment de depart optimal et le temps de parcourt estimé pour un trajet et un interval de temps donné (commande OPT) </summary>\n\t\t///\t<param name='d7'> Jour de la semaine </param>\n\t\t///\t<param name='h_start'> Heure de début de l'interval </param>\n\t\t///\t<param name='h_end'> Heure de fin de l'interval </param>\n\t\t///\t<param name='seg_ids'> vecteur contenant l'id de chaque segment/capteur qui constitue le trajet </param>\n\t\tvoid show_optimal_timestamp(capteur_stat::sensor_t d7, capteur_stat::sensor_t h_start, capteur_stat::sensor_t h_end, const vec<capteur_stat::sensor_t>& seg_ids);\n\n\t\t/// <summary> Recherxhe les statistiques d'un capteur dont l'id est donné en paramètre (commande STATS_C) </summary>\n\t\t///\t<param name='id'> Identifiant du capteur à rechercher </param>\n\t\t/// <returns> Retourne un pointeur vers les statistiques d'un capteur ou nullptr si le capteur n'a pas été trouvé </returns>\n\t\tcapteur_stat* get_sensor_stat_by_id(capteur_stat::sensor_t id);\n\n\t\t//----------------------------------------------------------------------- PRIVE\n\tprivate:\n\t\t//--------------------------------------------------------------- Usings privés\n\t\tusing capteur_stat_with_events = pair<capteur_stat, vec<capteur_event>>;\n\t\tusing hour_jam_stat = pair<unsigned int, unsigned int>;\n\n\t\t//---------------------------------------------------------- Structures privées\n\t\t/// <summary> Structure représentant les statistiques du traffic d'une journée à l'échelle de la ville </summary>\n\t\tstruct day_traffic_stat\n\t\t{\n\t\t\tusing stat_t = unsigned int;\n\n\t\t\tday_traffic_stat() = default;\n\n\t\t\tstat_t total_count = 0;\n\t\t\tstat_t green_count = 0;\n\t\t\tstat_t red_count = 0;\n\t\t\tstat_t orange_count = 0;\n\t\t\tstat_t dark_count = 0;\n\t\t};\n\n\t\tvoid update_global_week_stats(capteur_event new_event);\n\n\t\tinline capteur_stat_with_events* get_sensor_stat_with_events_by_id(capteur_stat::sensor_t id);\n\n\t\t/// <summary> Fonction statique rertournant la quantité de minutes correspondant à l'état du traffic donné en paramètre </summary>\n\t\tstatic inline capteur_event::sensor_t travel_duration_of_traffic(traffic state);\n\n\t\tdouble get_travel_duration(const vec<vec<capteur_event>>& segments_events, const vec<capteur_stat::sensor_t>& seg_ids, size_t seg_events_idx, capteur_stat::sensor_t d7, capteur_stat::sensor_t hour, capteur_stat::sensor_t minute);\n\n\t\t// TODO: faire des fonctions statiques vérifiant les ranges des entrées (minutes, secondes, heures)\n\n\t\tstatic const size_t DAYS_COUNT = 7;\n\t\tstatic const size_t HOUR_COUNT = 24;\n\t\tstatic const size_t MIN_COUNT = 60;\n\t\tstatic const size_t MAX_IDS_COUNT = 1500;\n\t\tstatic const size_t MAX_EVENT_COUNT = 20000000;\n\n\t\tvec<capteur_stat_with_events> m_sensor_stats;\n\n\t\thour_jam_stat m_week_jam_distribution_by_hour[DAYS_COUNT][HOUR_COUNT];\n\t\tday_traffic_stat m_week_traffic_distribution_by_day[DAYS_COUNT];\n\t};\n}" }, { "alpha_fraction": 0.555424153804779, "alphanum_fraction": 0.5692801475524902, "avg_line_length": 29.98429298400879, "blob_id": "5fdac2f8cbe1024c3b4eecf347bb007be5033552", "content_id": "24327188a07cbf5bf9e124bc0e69994ae4082703", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5918, "license_type": "permissive", "max_line_length": 187, "num_lines": 191, "path": "/TP4_cpp/src/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tmain.cpp\n\t\t\t\t\t\t\t\t\t--------\n*********************************************************************************/\n\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/config.hpp>\n#include <boost/archive/archive_exception.hpp>\n\n#include \"Utils.h\"\n#include \"Scene.h\"\n#include \"Command.h\"\n#include \"Benchmark.h\"\n\nnamespace\n{\n\tinline void check_size(const std::vector<std::string>& words, size_t arg_count, bool is_inequality = false, bool additionnal_condition = true)\n\t{\n\t\tif ((is_inequality ? (words.size() < arg_count + 1) : (words.size() != arg_count + 1)) || !additionnal_condition)\n\t\t\tthrow std::invalid_argument(\"Wrong number of arguments\");\n\t}\n}\n\nint main()\n{\n\tusing TP4::move_str_to_coord_t;\n\n\tTP4::Scene geometry_scene;\n\tstd::string line;\n\tauto is_error_message_enabled = false;\n\n\twhile (true)\n\t{\n\t\tstd::cin.sync_with_stdio(false);\n\t\tstd::getline(std::cin, line);\n\t\tauto words = TP4::split(line, ' ');\n\n\t\tif (words.size() > 0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tswitch (TP4::overlying(words[0]))\n\t\t\t\t{\n\t\t\t\tcase TP4::command_type::ADD_SEGMENT:\n\t\t\t\t\tcheck_size(words, 5U);\n\t\t\t\t\tgeometry_scene.Add_segment(std::move(words[1]), { move_str_to_coord_t(words[2]), move_str_to_coord_t(words[3]) }, { move_str_to_coord_t(words[4]), move_str_to_coord_t(words[5]) });\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::ADD_RECTANGLE:\n\t\t\t\t\tcheck_size(words, 5U);\n\t\t\t\t\tgeometry_scene.Add_rectangle(std::move(words[1]), { move_str_to_coord_t(words[2]), move_str_to_coord_t(words[3]) }, { move_str_to_coord_t(words[4]), move_str_to_coord_t(words[5]) });\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::ADD_POLYGON:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 1U + 2U * 3, true, ((words.size() - 2U) % 2U) == 0);\n\t\t\t\t\tstd::vector<TP4::Point> points;\n\t\t\t\t\tfor (size_t i = 2; i < words.size(); i += 2)\n\t\t\t\t\t\tpoints.emplace_back(move_str_to_coord_t(words[i]), move_str_to_coord_t(words[i + 1]));\n\t\t\t\t\tgeometry_scene.Add_polygon(std::move(words[1]), points);\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::UNION:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 3U, true);\n\t\t\t\t\tstd::unordered_set<TP4::name_t> shape_names;\n\t\t\t\t\tfor (size_t i = 2; i < words.size(); ++i)\n\t\t\t\t\t\tif (!shape_names.insert(std::move(words[i])).second)\n\t\t\t\t\t\t\tthrow std::invalid_argument(\"Can't create union from duplicate shapes\");\n\n\t\t\t\t\tgeometry_scene.Union(std::move(words[1]), shape_names);\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::INTER:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 3U, true);\n\t\t\t\t\tstd::unordered_set<TP4::name_t> shape_names;\n\t\t\t\t\tfor (size_t i = 2; i < words.size(); ++i)\n\t\t\t\t\t\tif (!shape_names.insert(std::move(words[i])).second)\n\t\t\t\t\t\t\tthrow std::invalid_argument(\"Can't create union from duplicate shapes\");\n\n\t\t\t\t\tgeometry_scene.Intersect(std::move(words[1]), shape_names);\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::HIT:\n\t\t\t\t\tcheck_size(words, 3U);\n\t\t\t\t\tif (geometry_scene.Is_point_contained_by({ move_str_to_coord_t(words[2]), move_str_to_coord_t(words[3]) }, std::move(words[1])))\n\t\t\t\t\t\tstd::cout << \"YES\" << std::endl;\n\t\t\t\t\telse\n\t\t\t\t\t\tstd::cout << \"NO\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::DELETE:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 1U, true);\n\t\t\t\t\tstd::vector<TP4::name_t> shape_names;\n\t\t\t\t\tfor (size_t i = 1; i < words.size(); ++i)\n\t\t\t\t\t\tshape_names.push_back(std::move(words[i]));\n\t\t\t\t\tgeometry_scene.Delete(shape_names);\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::MOVE:\n\t\t\t\t\tcheck_size(words, 3U);\n\t\t\t\t\tgeometry_scene.Move_shape(std::move(words[1]), move_str_to_coord_t(words[2]), move_str_to_coord_t(words[3]));\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::LIST:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tgeometry_scene.List();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::UNDO:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tgeometry_scene.Undo();\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::REDO:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tgeometry_scene.Redo();\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::LOAD:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 1U);\n\t\t\t\t\tgeometry_scene.Load(std::move(words[1]));\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::SAVE:\n\t\t\t\t{\n\t\t\t\t\tcheck_size(words, 1U);\n\t\t\t\t\tgeometry_scene.Save(std::move(words[1]));\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase TP4::command_type::CLEAR:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tgeometry_scene.ClearCurrentState();\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::ENABLE_ERROR_MESSAGES:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tis_error_message_enabled = true;\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::DISABLE_ERROR_MESSAGES:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\tis_error_message_enabled = false;\n\t\t\t\t\tstd::cout << \"OK\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::BENCHMARK:\n\t\t\t\t\tcheck_size(words, 1U, true);\n\t\t\t\t\tTP4::execute_benchmarks(geometry_scene, std::stoi(words[1]));\n\t\t\t\t\tbreak;\n\t\t\t\tcase TP4::command_type::EXIT:\n\t\t\t\t\tcheck_size(words, 0U);\n\t\t\t\t\treturn EXIT_SUCCESS;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (const std::range_error&)\n\t\t\t{\n\t\t\t\tif (is_error_message_enabled)\n\t\t\t\t\tstd::cout << \"Error: Invalid command\" << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"ERR\" << std::endl;\n\t\t\t}\n\t\t\tcatch (const std::logic_error& e)\n\t\t\t{\n\t\t\t\tif (is_error_message_enabled)\n\t\t\t\t\tstd::cout << \"Error: \" << e.what() << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"ERR\" << std::endl;\n\t\t\t}\n\t\t\tcatch (const boost::archive::archive_exception& e)\n\t\t\t{\n\t\t\t\tif (is_error_message_enabled)\n\t\t\t\t\tstd::cout << \"Error during (de)serialization: \" << e.what() << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"ERR\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6091731190681458, "alphanum_fraction": 0.6124030947685242, "avg_line_length": 28.769229888916016, "blob_id": "b50cd93d221973628e7eee257b6220abe783ff6f", "content_id": "b30861e8c39698569d9145301e8253282745eb5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1549, "license_type": "permissive", "max_line_length": 86, "num_lines": 52, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/Utils/ConsoleUtils.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.Utils;\n\nimport java.util.List;\nimport java.io.IOException;\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\n\n/**\n * Classe regourpant quelques fonction utiles à l'interface console\n * @author B3330\n */\npublic class ConsoleUtils {\n\n public static String lireChaine(String invite) {\n String chaineLue = null;\n System.out.print(invite);\n try {\n InputStreamReader isr = new InputStreamReader(System.in);\n BufferedReader br = new BufferedReader(isr);\n chaineLue = br.readLine();\n } catch (IOException exception) {\n exception.printStackTrace(System.err);\n }\n return chaineLue;\n\n }\n\n public static Integer lireInteger(String invite) {\n Integer valeurLue = null;\n try {\n valeurLue = new Integer(lireChaine(invite));\n } catch (java.lang.NumberFormatException e) {\n System.out.println(\"erreur de saisie\");\n valeurLue = lireInteger(invite);\n }\n return valeurLue;\n }\n\n public static Integer lireInteger(String invite, List<Integer> valeursPossibles) {\n Integer valeurLue = null;\n try {\n valeurLue = new Integer(lireChaine(invite));\n if (!(valeursPossibles.contains(valeurLue))) {\n throw new Exception();\n }\n } catch (Exception e) {\n System.out.println(\"erreur de saisie\");\n valeurLue = lireInteger(invite, valeursPossibles);\n }\n return valeurLue;\n }\n}\n" }, { "alpha_fraction": 0.5721476674079895, "alphanum_fraction": 0.6736577153205872, "avg_line_length": 18.866666793823242, "blob_id": "7a018a521c05cac34619c1708dc0d653e60ff45e", "content_id": "8d8e995504134d87f9d968165248c9c4339d86e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 44, "num_lines": 60, "path": "/TD_Archi_cache/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": ".PHONY: clean cache_ex9 time_ex9\n\nclean:\n\trm cache_ex1\n\trm cache_ex2\n\trm cache_ex3\n\trm cache_ex9_v1\n\trm cache_ex9_v2\n\trm cache_ex9_v3\n\trm cache_ex9_v4\n\trm cache_ex9_v5\n\trm cache_ex9_v6\n\t\ncache_ex1: TD_cache_ex1.c\n\tgcc TD_cache_ex1.c -std=c11 -o cache_ex1\n\t\ncache_ex2: TD_cache_ex2.c\n\tgcc TD_cache_ex2.c -std=c11 -o cache_ex2\n\t\ncache_ex3: TD_cache_ex3.c\n\tgcc TD_cache_ex3.c -std=c11 -o cache_ex3\n\ncache_ex9_v1: cache_ex9_v1.c N.h\n\tgcc cache_ex9_v1.c -std=c11 -o cache_ex9_v1\n\t\ncache_ex9_v2: cache_ex9_v2.c N.h\n\tgcc cache_ex9_v2.c -std=c11 -o cache_ex9_v2\n\t\ncache_ex9_v3: cache_ex9_v3.c N.h\n\tgcc cache_ex9_v3.c -std=c11 -o cache_ex9_v3\n\t\ncache_ex9_v4: cache_ex9_v4.c N.h\n\tgcc cache_ex9_v4.c -std=c11 -o cache_ex9_v4\n\ncache_ex9_v5: cache_ex9_v5.c N.h\n\tgcc cache_ex9_v5.c -std=c11 -o cache_ex9_v5\n\t\ncache_ex9_v6: cache_ex9_v6.c N.h\n\tgcc cache_ex9_v6.c -std=c11 -o cache_ex9_v6\n\ncache_ex9:\n\tmake cache_ex9_v1\n\tmake cache_ex9_v2\n\tmake cache_ex9_v3\n\tmake cache_ex9_v4\n\tmake cache_ex9_v5\n\tmake cache_ex9_v6\n\t\ntime_ex9:\n\ttime ./cache_ex9_v1\n\t@echo \" \"\n\ttime ./cache_ex9_v2\n\t@echo \" \"\n\ttime ./cache_ex9_v3\n\t@echo \" \"\n\ttime ./cache_ex9_v4\n\t@echo \" \"\n\ttime ./cache_ex9_v5\n\t@echo \" \"\n\ttime ./cache_ex9_v6\n" }, { "alpha_fraction": 0.5500794649124146, "alphanum_fraction": 0.5580286383628845, "avg_line_length": 24.14666748046875, "blob_id": "8d160d1e6f2304fa72492f48d6142b34c9b76d7a", "content_id": "274a2a9f8915ff6d47b7f5c0d8601e2d4d2c256d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1893, "license_type": "permissive", "max_line_length": 96, "num_lines": 75, "path": "/TP2_Archi/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-16", "text": "############################################################################################\n################################## GENERIC MAKEFILE ########################################\n############################################################################################\n# TODO: gĂrer les sous-dossiers / fichiers ayants le mĂȘmes noms dans des dossiers diffĂ©rts\n# TODO: gĂrer les extentions .hpp, .cxx, ...\n\n# Compiler\nCC = msp430-gcc\n# Command used to remove files\nRM = rm -f\n# Compiler and pre-processor options\nCPPFLAGS = -Wall -mmcu=msp430fg4618 -mdisable-watchdog -std=c99\n#-Ofast\n# Debug flags\nDEBUGFLAGS = -g\n# Resulting program file name\nEXE_NAME = tp2.elf\n# The source file extentions\nSRC_EXT = c\n# The header file types\n# TODO allow .hpp header files\nHDR_EXT = h\n\n# Source directory\nSRCDIR = \n# Headers directory\nINCDIR = \n# Dependency files directory\nDEPDIR = dep\n# Libraries paths\nLIB_DIRS = \n# Library file names (e.g. '-lboost_serialization-mt')\nLIBS = -lm\n# List of include paths\nINCLUDES = \n\n# Source directory path\nSRC_PATH = ./$(SRCDIR)\n# Dependencies path\nDEP_PATH = ./$(DEPDIR)\n\n# List of source files\nSOURCES = lcd.c tp2-3.c\n# List of object files\nOBJS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(BUILD_PATH)/%.o)\n# List of dependency files\nDEPS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(DEP_PATH)/%.d)\n\n.PHONY: all clean rebuild help test\n\nall: $(EXE_NAME)\n\nclean:\n\t$(RM) *.o\n\t$(RM) $(EXE_NAME)\n\t$(RM) $(DEP_PATH)/*.d\n\t\nrebuild: clean all\n\nhelp:\n\t@echo '\t\t\t\t### MAKEFILE HELP ###'\n\t@echo 'PHONY TARGETS:'\n\t@echo '\tall \t...'\n\t@echo '\tclean \t...'\n\t@echo '\trebuild ...'\n\t@echo '\thelp\t...'\n\n# Build object files\n%.o: $(SRC_PATH)/%.$(SRC_EXT)\n\t@mkdir -p $(DEP_PATH)\n\t$(CC) $(CPPFLAGS) $(DEBUGFLAGS) -I $(INCLUDES) -MMD -M -MM -MP -MF $(DEP_PATH)/$*.d -c $< -o $@\n\n# Build main target\n$(EXE_NAME): $(OBJS)\n\t$(CC) $(LIB_DIRS) $(CPPFLAGS) -o $(EXE_NAME) $(OBJS) $(LIBS)\n\n" }, { "alpha_fraction": 0.8252426981925964, "alphanum_fraction": 0.8252426981925964, "avg_line_length": 40.20000076293945, "blob_id": "4dcf755260b7b9f715b08f7ac34ba5ab0979208b", "content_id": "1b33760f2cfe0cd510c8d58c6145264ef4d76a97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1236, "license_type": "permissive", "max_line_length": 45, "num_lines": 30, "path": "/TP1_SQL/scriptSuppressionTablesUniversal.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "drop table Country cascade constraints;\ndrop table City cascade constraints;\ndrop table Province cascade constraints;\ndrop table Economy cascade constraints;\ndrop table Population cascade constraints;\ndrop table Politics cascade constraints;\ndrop table Language cascade constraints;\ndrop table Religion cascade constraints;\ndrop table Ethnic_Group cascade constraints;\ndrop table Continent cascade constraints;\ndrop table borders cascade constraints;\ndrop table encompasses cascade constraints;\ndrop table Organization cascade constraints;\ndrop table is_member cascade constraints;\ndrop type GeoCoord;\ndrop table Mountain cascade constraints;\ndrop table Desert cascade constraints;\ndrop table Island cascade constraints;\ndrop table Lake cascade constraints;\ndrop table Sea cascade constraints;\ndrop table Lake cascade constraints;\ndrop table River cascade constraints;\ndrop table geo_Mountain cascade constraints;\ndrop table geo_Desert cascade constraints;\ndrop table geo_Island cascade constraints;\ndrop table geo_River cascade constraints;\ndrop table geo_Sea cascade constraints;\ndrop table geo_Lake cascade constraints;\ndrop table merges_with cascade constraints;\ndrop table located cascade constraints;\n" }, { "alpha_fraction": 0.7966625690460205, "alphanum_fraction": 0.8077874183654785, "avg_line_length": 32.020408630371094, "blob_id": "7043fefd0a5eccb0b32a44731785d3ba764e4f33", "content_id": "b84032cebca1dc6702e6d80c82bd2d775afa519b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1618, "license_type": "permissive", "max_line_length": 86, "num_lines": 49, "path": "/TP1_Archi/VHDL/Makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": ".PHONY: simulate_fulladder simulate_adder simulate_clock simulate_nbitsregister clean\n\ntestbench_fulladder: fulladder.o testbench_fulladder.o\n\tghdl -e testbench_fulladder\ntestbench_fulladder.o: testbench_fulladder.vhdl fulladder.o\n\tghdl -a testbench_fulladder.vhdl\nfulladder.o: fulladder.vhdl\n\tghdl -a fulladder.vhdl\nsimulate_fulladder: testbench_fulladder\n\t./testbench_fulladder --stop-time=20ns --vcd=testbench_fulladder.vcd\n\tgtkwave testbench_fulladder.vcd\n\n\ntestbench_adder8: adder.o testbench_adder.o fulladder.o\n\tghdl -e testbench_adder8\ntestbench_adder.o: testbench_adder.vhdl adder.o \n\tghdl -a testbench_adder.vhdl\nadder.o: adder.vhdl\n\tghdl -a adder.vhdl\nsimulate_adder: testbench_adder8\n\t./testbench_adder8 --stop-time=100ns --vcd=testbench_adder8.vcd\n\tgtkwave testbench_adder8.vcd\n\n\nclock.o: clock.vhdl\n\tghdl -a clock.vhdl\nclock_generator: clock.o\n\tghdl -e clock_generator\nsimulate_clock: clock_generator\n\t./clock_generator --stop-time=100ns --vcd=clock_generator.vcd\n\tgtkwave clock_generator.vcd\n\nnbitsregister.o: nbitsregister.vhdl\n\tghdl -a nbitsregister.vhdl\ndflipflop.o: dflipflop.vhdl\n\tghdl -a dflipflop.vhdl\ntestbench_nbitsregister.o: testbench_nbitsregister.vhdl\n\tghdl -a testbench_nbitsregister.vhdl\ntestbench_nbitsregister: testbench_nbitsregister.o nbitsregister.o clock.o dflipflop.o\n\tghdl -e testbench_nbitsregister\nsimulate_nbitsregister: testbench_nbitsregister\n\t./testbench_nbitsregister --stop-time=100ns --vcd=testbench_nbitsregister.vcd\n\tgtkwave testbench_nbitsregister.vcd\n\nclean:\n\trm *.o\n\trm *.vcd\n\trm *.cf\n\trm testbench_adder8 testbench_fulladder clock_generator testbench_nbitsregister\n" }, { "alpha_fraction": 0.6164020895957947, "alphanum_fraction": 0.6772486567497253, "avg_line_length": 15.434782981872559, "blob_id": "c21cafc1dac670b8121cf158263d2809e04b5071", "content_id": "1ecd56114207e1a85954d838f2066e86bd29dec4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "permissive", "max_line_length": 45, "num_lines": 23, "path": "/TP2_Archi/lcd__.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef LCD_H\n#define LCD_H\n\n#define LCD_START (unsigned char*)145\n#define LCD_END (unsigned char*)164\n\n\nunsigned char tbNumber[10];\n\n/* Initialize the LCD_A controller\n \n claims P5.2-P5.4, P8, P9, and P10.0-P10.5\n assumes ACLK to be default 32khz (LFXT1)\n*/\nvoid lcd_init();\n\nvoid lcd_display_number(int number);\n\nvoid lcd_clear();\n\nvoid lcd_fill();\n\n#endif // LCD_H\n" }, { "alpha_fraction": 0.6014471650123596, "alphanum_fraction": 0.6191027760505676, "avg_line_length": 18.86206817626953, "blob_id": "363ea001f986b896a215533cfbffe51671797757", "content_id": "b50118bc83428a525a841ecdc85a61443798bffd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3464, "license_type": "permissive", "max_line_length": 111, "num_lines": 174, "path": "/TD3_ALG/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "WINDOWS-1252", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define ALLOC_STEP 5\n\n/*\n * La racine se situe à l'index 0\n * Soit un nœud à l'index i alors son fils gauche est à l'index 2i+1 et son fils droit à 2i+2\n * Soit un nœud à l'index i>0 alors son père est à l'index int((i-1)/2)\n*/\n\ntypedef struct\n{\n\tint allocated;\n\tint filled;\n\tint* array;\n} BinaryHeap;\n\nvoid init(BinaryHeap* heap)\n{\n\tif (heap == NULL)\n\t\treturn;\n\n\theap->allocated = ALLOC_STEP;\n\theap->filled = 0;\n\theap->array = (int*)malloc(sizeof(int)*ALLOC_STEP);\n}\n\nvoid ReallocIfFull(BinaryHeap* heap)\n{\n\tif (heap == NULL)\n\t\treturn;\n\n\tif (heap->filled >= heap->allocated)\n\t{\n\t\theap->array = (int*)realloc(heap->array, sizeof(int) * (ALLOC_STEP + heap->allocated));\n\t\theap->allocated += ALLOC_STEP;\n\t}\n}\n\nvoid insert(BinaryHeap* heap, int value)\n{\n\tif (heap == NULL)\n\t\treturn;\n\tif (heap->array == NULL)\n\t\treturn;\n\n\tReallocIfFull(heap);\n\n\theap->array[heap->filled] = value;\n\n\tint position_pere = (heap->filled - 1) / 2;\n\tint position_element_insere = heap->filled;\n\twhile (position_pere >= 0 && heap->array[position_pere] < heap->array[position_element_insere])\n\t{\n\t\tint tampon = heap->array[position_pere];\n\t\theap->array[position_pere] = heap->array[position_element_insere];\n\t\theap->array[position_element_insere] = tampon;\n\t\tposition_element_insere = position_pere;\n\t\tposition_pere = (position_pere - 1) / 2;\n\t}\n\n\theap->filled++;\n}\n\nvoid Display(BinaryHeap* heap)\n{\n\tif (heap == NULL)\n\t\treturn;\n\tif (heap->array == NULL)\n\t\treturn;\n\n\tunsigned int i;\n\tfor (i = 0; i < heap->filled; i++)\n\t\tprintf(\"%d\\r\\n\", heap->array[i]);\n}\n\nvoid swapValues(int* array, unsigned int idx1, unsigned int* idx2)\n{\n\tunsigned int tmp = array[idx1];\n\tarray[idx1] = array[*idx2];\n\tarray[*idx2] = tmp;\n\t*idx2 = idx1;\n}\n\nint extract(BinaryHeap* heap, int* max)\n{\n\tif (heap->filled <= 0 || max == NULL || heap == NULL)\n\t\treturn 0;\n\t\n\t*max = heap->array[0];\n\n\tif (heap->filled > 1)\n\t{\n\t\t// swap first and last value\n\t\theap->array[0] = heap->array[heap->filled-1];\n\n\t\t// Remove last element from bnary heap\n\t\theap->filled--;\n\t\tunsigned int max_pos = heap->filled - 1;\n\n\t\tunsigned int pos_element = 0;\n\t\twhile (1)\n\t\t{\n\t\t\tunsigned int pos_fils1 = pos_element * 2 + 1;\n\t\t\tunsigned int pos_fils2 = pos_element * 2 + 2;\n\n\t\t\tif(pos_fils2 > max_pos && pos_fils1 <= max_pos) {\n\t\t\t\tif (heap->array[pos_fils1] > heap->array[pos_element])\n\t\t\t\t\tswapValues(heap->array, pos_fils1, &pos_element);\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if(pos_fils2 <= max_pos && pos_fils1 <= max_pos)\n\t\t\t{\n\t\t\t\tif (heap->array[pos_fils1] > heap->array[pos_element] || heap->array[pos_fils2] > heap->array[pos_element])\n\t\t\t\t{\n\t\t\t\t\tif (heap->array[pos_fils1] > heap->array[pos_fils2])\n\t\t\t\t\t\tswapValues(heap->array, pos_fils1, &pos_element);\n\t\t\t\t\telse\n\t\t\t\t\t\tswapValues(heap->array, pos_fils2, &pos_element);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t\theap->filled--;\n\n\treturn 1;\n}\n\nvoid dispose(BinaryHeap* heap)\n{\n\tfree(heap->array);\n\theap->array = NULL;\n}\n\nint main(int argc, const char* argv[])\n{\n\tchar input[30];\n\tBinaryHeap heap;\n\tinit(&heap);\n\n\twhile (1)\n\t{\n\t\tscanf(\"%s\", input);\n\n\t\tif (strcmp(\"bye\", input) == 0)\n\t\t\tbreak;\n\t\telse if (strcmp(\"insert\", input) == 0)\n\t\t{\n\t\t\tint value = 0;\n\t\t\tscanf(\"%d\", &value);\n\t\t\tinsert(&heap, value);\n\t\t}\n\t\telse if (strcmp(\"extract\", input) == 0)\n\t\t{\n\t\t\tint max = 0;\n\t\t\tif(extract(&heap, &max))\n\t\t\t\tprintf(\"%d\\r\\n\", max);\n\t\t}\n\t\telse\n\t\t\tprintf(\"Invalid input\");\n\t}\n\n\tdispose(&heap);\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.4552469253540039, "alphanum_fraction": 0.4652777910232544, "avg_line_length": 31.375, "blob_id": "85dbdebc45863a96162e60c7ba42991ab61edd80", "content_id": "875f2ac09e6c90351f5e2b8b9d2341f473081102", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1299, "license_type": "permissive", "max_line_length": 77, "num_lines": 40, "path": "/TP1_Concurrency/include/clavier.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\t\t\tClavier - tache gerant l'entree clavier\n\t\t\t\t\t-----------------------------------------\n\tdebut\t\t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//---------- Interface du module <CLAVIER> (fichier clavier.h) -----------\n#ifndef CLAVIER_H\n#define CLAVIER_H\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//--------------------------------------------------- Interfaces utilisees\n#include <sys/types.h>\n#include <stdlib.h>\n#include \"Outils.h\"\n\n//------------------------------------------------------------------ Types\n//! Structure utilisee par la message queue entre le clavier et les barrieres\nstruct car_incomming_msg\n{\n\tlong barriere_type;\n\tTypeUsager type_usager;\n};\n\n//! Structure utilisee par la message queue entre le clavier et la sortie\nstruct car_exit_msg\n{\n\tlong place_num;\n};\n\n//---------------------------------------------------- Fonctions publiques\n//! Démare la tache gerant l'interface console\n//! Retourne le PID du processus fils ou -1 en cas d'echec.\npid_t activer_clavier();\n\n//! Gere les commandes déclanchées par le menu\nvoid Commande(char code, unsigned int valeur);\n\n#endif // CLAVIER_H\n\n" }, { "alpha_fraction": 0.5802903771400452, "alphanum_fraction": 0.6088869571685791, "avg_line_length": 24.255556106567383, "blob_id": "3a6dda9117b8785474d051dd45034ad799e4780e", "content_id": "e6140b122acd96591cdd516311bcbcaa32851bbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2274, "license_type": "permissive", "max_line_length": 69, "num_lines": 90, "path": "/TP2_cpp/tests/test.sh", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "echo -----------------------------------------------------------\necho Tests pour le binome : $1\necho -----------------------------------------------------------\n # à executer depuis le dossier parent (avec 'make test' par exemple)\n\nnTestCount=0\nnSuccesfulTests=0\nnStrResult=\"$1 \"\n\necho ADD\nlet \"nTestCount=$nTestCount+1\"\n./$1 < tests/test0.in > tests/temp1.txt\ngrep -v '^#' tests/temp1.txt > tests/temp2.txt\ndiff -wB tests/test0.ou tests/temp2.txt\nif [ $? -eq 0 ]\n then\n\t\techo PASSED\n \tlet \"nSuccesfulTests=$nSuccesfulTests+1\"\n\t\tnStrResult=$nStrResult\" 1\"\n\telse\n\t\techo FAILED\n\t\tnStrResult=$nStrResult\" 0\"\nfi\n\necho STATS_C\nlet \"nTestCount=$nTestCount+1\"\n./$1 < tests/test1.in > tests/temp1.txt\ngrep -v '^#' tests/temp1.txt > tests/temp2.txt\ndiff -wB tests/test1.ou tests/temp2.txt\nif [ $? -eq 0 ]\n then\n\t\techo PASSED\n \tlet \"nSuccesfulTests=$nSuccesfulTests+1\"\n\t\tnStrResult=$nStrResult\" 1\"\n\telse\n\t\techo FAILED\n\t\tnStrResult=$nStrResult\" 0\"\nfi\n\necho STATS_D7\nlet \"nTestCount=$nTestCount+1\"\n./$1 < tests/test2.in > tests/temp1.txt\ngrep -v '^#' tests/temp1.txt > tests/temp2.txt\ndiff -wB tests/test2.ou tests/temp2.txt\nif [ $? -eq 0 ]\n then\n\t\techo PASSED\n \tlet \"nSuccesfulTests=$nSuccesfulTests+1\"\n\t\tnStrResult=$nStrResult\" 1\"\n\telse\n\t\techo FAILED\n\t\tnStrResult=$nStrResult\" 0\"\nfi\n\necho JAM_DH\nlet \"nTestCount=$nTestCount+1\"\n./$1 < tests/test3.in > tests/temp1.txt\ngrep -v '^#' tests/temp1.txt > tests/temp2.txt\ndiff -wB tests/test3.ou tests/temp2.txt\nif [ $? -eq 0 ]\n then\n\t\techo PASSED\n \tlet \"nSuccesfulTests=$nSuccesfulTests+1\"\n\t\tnStrResult=$nStrResult\" 1\"\n\telse\n\t\techo FAILED\n\t\tnStrResult=$nStrResult\" 0\"\nfi\n\necho OPT\nlet \"nTestCount=$nTestCount+1\"\n./$1 < tests/test4.in > tests/temp1.txt\ngrep -v '^#' tests/temp1.txt > tests/temp2.txt\ndiff -wB tests/test4.ou tests/temp2.txt\nif [ $? -eq 0 ]\n then\n\t\techo PASSED\n \tlet \"nSuccesfulTests=$nSuccesfulTests+1\"\n\t\tnStrResult=$nStrResult\" 1\"\n\telse\n\t\techo FAILED\n\t\tnStrResult=$nStrResult\" 0\"\nfi\n\necho -----------------------------------------------------------\necho RESULTS\necho -----------------------------------------------------------\necho Results: $nSuccesfulTests/$nTestCount\necho CSVLine: $nStrResult\necho $nStrResult >> tests/results.txt\n" }, { "alpha_fraction": 0.5575268864631653, "alphanum_fraction": 0.5693548321723938, "avg_line_length": 24.80555534362793, "blob_id": "336cf7c822b4285f1aea5fd335a309e3ea0a955a", "content_id": "6e967c036b5a97d509f2d253b12a4f1c2b2498fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1866, "license_type": "permissive", "max_line_length": 96, "num_lines": 72, "path": "/TP4_Archi/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "############################################################################################\n################################## GENERIC MAKEFILE ########################################\n############################################################################################\n# TODO: gÃrer les sous-dossiers / fichiers ayants le mêmes noms dans des dossiers différts\n# TODO: gÃrer les extentions .hpp, .cxx, ...\n\n# Compiler\nCC = msp430-gcc\n# Command used to remove files\nRM = rm -f\n# Compiler and pre-processor options\nCPPFLAGS = -Wall -mmcu=msp430fg4618 -mcpu=430 -mdisable-watchdog -std=c99\n#-Ofast\n# Debug flags\nDEBUGFLAGS = -g\n# Resulting program file name\nEXE_NAME = tp4.elf\nLST_NAME = tp4.lst\n# The source file extentions\nSRC_EXT = c\n# The header file types\n# TODO allow .hpp header files\nHDR_EXT = h\n\n# Source directory\nSRCDIR = \n# Headers directory\nINCDIR = \n# Dependency files directory\nDEPDIR = dep\n# Libraries paths\nLIB_DIRS = \n# Library file names (e.g. '-lboost_serialization-mt')\nLIBS = -lm\n# List of include paths\nINCLUDES = \n\n# Source directory path\nSRC_PATH = ./$(SRCDIR)\n# Dependencies path\nDEP_PATH = ./$(DEPDIR)\n\n# List of source files\nSOURCES = lcd.c ex1.c\n# List of object files\nOBJS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(BUILD_PATH)/%.o)\n# List of dependency files\nDEPS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(DEP_PATH)/%.d)\n\n.PHONY: all clean rebuild prog\n\nall: $(EXE_NAME)\n\nclean:\n\t$(RM) *.o\n\t$(RM) $(EXE_NAME)\n\t$(RM) $(DEP_PATH)/*.d\n\t\nrebuild: clean all\n\n# Build object files\n%.o: $(SRC_PATH)/%.$(SRC_EXT)\n\t@mkdir -p $(DEP_PATH)\n\t$(CC) $(CPPFLAGS) $(DEBUGFLAGS) -I $(INCLUDES) -MMD -M -MM -MP -MF $(DEP_PATH)/$*.d -c $< -o $@\n\n# Build main target\n$(EXE_NAME): $(OBJS)\n\t$(CC) $(LIB_DIRS) $(CPPFLAGS) -o $(EXE_NAME) $(OBJS) $(LIBS)\n\tmsp430-objdump -d $(EXE_NAME) > $(LST_NAME)\n\nprog: $(EXE_NAME)\n\tmspdebug -j -d /dev/ttyUSB0 uif\n\n\n" }, { "alpha_fraction": 0.566568911075592, "alphanum_fraction": 0.5683284401893616, "avg_line_length": 27.433332443237305, "blob_id": "bc3f7148c0ba68054e221c669869545d296259f6", "content_id": "b020521ce5d3b748bc8e2bf4cb8316c941076b7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1709, "license_type": "permissive", "max_line_length": 94, "num_lines": 60, "path": "/TP4_cpp/src/Polygon.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\t\tPolygon\n\t\t\t\t\t\t\t\t\t\t-------\n*********************************************************************************/\n\n#ifndef POLYGON_H\n#define POLYGON_H\n\n#include <string>\n\n#include \"Utils.h\"\n#include \"Command.h\"\n#include \"optional.h\"\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\t//----------------------------------------------------------------------------\n\t//! Structure représentant un polygone convexe.\n\t//! La structure est serialisable grâce à boost::serialization.\n\t//----------------------------------------------------------------------------\n\tstruct Polygon\n\t{\n\t\tPolygon() = default;\n\t\tPolygon& operator=(const Polygon&) = delete;\n\t\n\t\tstd::vector<Point> Get_vertices() const\n\t\t{\n\t\t\treturn vertices;\n\t\t}\n\n\tprivate:\n\t\texplicit Polygon(const std::vector<Point>&& vertices);\n\n\t\tstd::vector<Point> vertices;\n\n\t\tfriend std::ostream& operator<<(std::ostream &flux, const Polygon& polygone);\n\n\t\tfriend std::experimental::optional<Polygon> make_polygon(const std::vector<Point> vertices);\n\n\t\tfriend Polygon Move(const Polygon& shape, coord_t dx, coord_t dy);\n\t\tfriend bool Is_contained(const Polygon& shape, Point point);\n\n\t\tfriend class boost::serialization::access;\n\t\t\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\tar & boost::serialization::make_nvp(\"vertices\", vertices);\n\t\t}\n\t};\n\n\tPolygon Move(const Polygon& shape, coord_t dx, coord_t dy);\n\tbool Is_contained(const Polygon& shape, Point point);\n\n\tstd::experimental::optional<Polygon> make_polygon(const std::vector<Point> vertices);\n}\n\n#endif // !POLYGON_H" }, { "alpha_fraction": 0.5894522070884705, "alphanum_fraction": 0.5976107120513916, "avg_line_length": 15.34761905670166, "blob_id": "4be318f874131cc2ab6ce69b3814dac5da15ac92", "content_id": "f2df80136c8b10fe0951789195b31fe5d8281afe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3432, "license_type": "permissive", "max_line_length": 58, "num_lines": 210, "path": "/TP1_ALG/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n//#define TESTING\n#define ENDL \"\\r\\n\"\n\n//typedef enum { false, true } bool;\n\ntypedef struct element\n{\n\tint value;\n\tstruct element* previous;\n\tstruct element* next;\n} element;\n\nelement* make_list()\n{\n\telement* sentinel = (element*)malloc(sizeof(element));\n\tsentinel->next = sentinel;\n\tsentinel->previous = sentinel;\n\treturn sentinel;\n}\n\nelement* insert(element* list, int value)\n{\n\telement* new_element = (element*)malloc(sizeof(element));\n\tif (new_element == NULL || list == NULL)\n\t\treturn NULL;\n\tnew_element->value = value;\n\n\telement* it = list->next;\n\n\t// First element\n\tif (it == list)\n\t{\n\t\tlist->next = new_element;\n\t\tlist->previous = new_element;\n\t\tnew_element->previous = list;\n\t\tnew_element->next = list;\n\t\treturn new_element;\n\t}\n\n\twhile (list != it)\n\t{\n\t\tif (it->value >= value)\n\t\t{\n\t\t\t// Insert\n\t\t\tit->previous->next = new_element;\n\t\t\tnew_element->next = it;\n\t\t\tnew_element->previous = it->previous;\n\t\t\tit->previous = new_element;\n\t\t\treturn new_element;\n\t\t}\n\t\tit = it->next;\n\t}\n\n\t// Last element\n\tlist->previous->next = new_element;\n\tnew_element->next = list;\n\tnew_element->previous = list->previous;\n\tlist->previous = new_element;\n\treturn new_element;\n}\n\nelement* make_list2(int* values, size_t size)\n{\n\tif (values == NULL || size == 0)\n\t\treturn make_list();\n\n\telement* sentinel = make_list();\n\t\n\tunsigned int i;\n\tfor (i = 0; i < size; i++)\n\t\tinsert(sentinel, values[i]);\n\n\treturn sentinel;\n}\n\nvoid remove(element* list, int value)\n{\n\tif (list == NULL)\n\t\treturn;\n\n\telement* it = list->next;\n\n\t// Empty list\n\tif (it == list)\n\t\treturn;\n\n\twhile (list != it)\n\t{\n\t\tif (it->value == value)\n\t\t{\n\t\t\t// Remove element\n\t\t\tit->previous->next = it->next;\n\t\t\tit->next->previous = it->previous;\n\t\t\tfree(it);\n\t\t\treturn;\n\t\t}\n\t\tit = it->next;\n\t}\n\n\treturn;\n}\n\nvoid display(element* list)//, bool rubbishDisplayMode)\n{\n\tif (list != NULL)\n\t{\n\t//\tif (!rubbishDisplayMode)\n\t//\t\tprintf(\"[ \");\n\t\telement* it = list->next;\n\t\twhile (it != list)\n\t\t{\n\t//\t\tif(!rubbishDisplayMode)\n\t//\t\t\tprintf(it->next == list ? \"%d\" : \"%d, \", it->value);\n\t//\t\telse\n\t\t\t\tprintf(\"%d\\r\\n\", it->value);\n\t\t\tit = it->next;\n\t\t}\n\t//\tif (!rubbishDisplayMode)\n\t//\t\tprintf(\" ]\");\n\t}\n\telse\n\t\tprintf(\"NULL\");\n}\n\nvoid dispose(element* list)\n{\n\tif (list == NULL)\n\t\treturn;\n\n\t// Empty list\n\tif (list->next == list) {\n\t\tfree(list);\n\t\treturn;\n\t}\n\n\tlist->previous->next = NULL;\n\telement* it = list->next;\n\n\twhile (it->next != NULL)\n\t{\n\t\tfree(it->previous);\n\t\tit->previous = NULL;\n\t\tit = it->next;\n\t}\n\n\tif (it->previous != it)\n\t\tfree(it->previous);\n\tfree(it);\n}\n\nint main(int argc, const char* argv[])\n{\n#ifdef TESTING\n\tint initialValues[] = { 10, 30, -20, 4 };\n\telement* list = make_list(initialValues, 4);\n\n\tprintf(\"List = \");\n\tdisplay(list);\n\n\tinsert(list, 11);\n\tinsert(list, -15);\n\n\tprintf(\"\\r\\nList = \");\n\tdisplay(list);\n\n\tremove(list, 10);\n\tremove(list, 8);\n\n\tprintf(\"\\r\\nList = \");\n\tdisplay(list);\n\n\tdispose(list);\n#else\n\tchar input[30];\n\telement* list = make_list();\n\n\twhile (1)\n\t{\n\t\tscanf(\"%s\", input);\n\n\t\tif (strcmp(\"print\", input) == 0)\n\t\t{\n\t\t\tdisplay(list);\n\t\t\tprintf(ENDL);\n\t\t}\n\t\telse if (strcmp(\"bye\", input) == 0)\n\t\t\tbreak;\n\t\telse if (strcmp(\"insert\", input) == 0)\n\t\t{\n\t\t\tint value = 0;\n\t\t\tscanf(\"%d\", &value);\n\t\t\tinsert(list, value);\n\t\t}\n\t\telse if (strcmp(\"remove\", input) == 0)\n\t\t{\n\t\t\tint value = 0;\n\t\t\tscanf(\"%d\", &value);\n\t\t\tremove(list, value);\n\t\t}\n\t\telse\n\t\t\tprintf(\"Invalid input\");\n\t}\n#endif\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.6180627942085266, "alphanum_fraction": 0.6213592290878296, "avg_line_length": 34.03955841064453, "blob_id": "377373b76bef95ddf63a780378eb5397b88f6374", "content_id": "cc3302b8263e516b2ef1f45b11ac679b5e2a758b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22361, "license_type": "permissive", "max_line_length": 182, "num_lines": 632, "path": "/TP2_cpp/includes/vec.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/************************************************************************************\n\t\t\t\t\t\tvec - A dynamic and generic vector\n\t\t\t\t\t\t------------------------------------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n************************************************************************************/\n\n//---------------------- Interface de la classe vec<T> -----------------------\n#pragma once\n\n//------------------------------------------------------------------ Includes systeme\n#include <cstddef>\t\t// std::size_t\n#include <utility>\t\t// std::declval et std::forward\n#include <limits>\t\t// std::numeric_limits\n\n//----------------------------------------------------------------- Headers utilisées\n#include \"utils.h\"\n\nnamespace TP2\n{\n\t//-------------------------------------------------------------------------------\n\t/// vec\n\t/// <summary> Classe permettant de stocker un vecteur d'objets de type T </summary> \n\t///\t<remarks> Le stockage interne des élements est contigu en mémoire </remarks\n\t///\t<remarks> La capacité du vecteur doit être strictement inférieure à vec::MAX_ALLOCATION_SIZE </remarks>\n\t//-------------------------------------------------------------------------------\n\t// TODO: Implementer des itérateurs pour vec\n\ttemplate<typename T>\n\t// requires EqualityComparable<ValueType<T>>, N> // TODO: enlever ça (exemple de requires proposé par la c++ guideline \n\tclass vec\n\t{\n\t\t//-------------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\tusing size_type = std::size_t;\n\t\tusing predicate = bool(*)(const T&, const T&);\t// TODO: serais mieux avec std::function<> ou un foncteur maison (plus typé)\n\n\t\t//-------------------------------------------------------- Méthodes publiques\n\n\t\t/// <summary> Ajoute val_to_add dans le 'vec' courant </summary>\n\t\t/// <param name='val_to_add'> reférence constante vers une valeur de type T qui sera ajouté dans le vec </param>\n\t\t/// <remarks> Le vecteur considère qu'ajouter un élément peut changer l'ordre des éléments (désactive toutes optimisations liées au tri) </remarks>\n\t\tvoid add(const T& val_to_add);\n\n\t\t/// <summary> Ajoute un element de type T dans le vec courant à partir des argument d'un constructeur de T </summary>\n\t\t/// <param name='CtorArgsTypes'> Arguments donnés à un constructeur de T </param>\n\t\t/// <remarks> Le vecteur considère qu'ajouter un élément peut changer l'ordre des éléments (désactive toutes optimisations liées au tri) </remarks>\n\t\ttemplate<typename... CtorArgsTypes>\n\t\tT& add(CtorArgsTypes&&... ctor_args);\n\n\t\t/// <summary> Ajoute le contenu de le vec donné en paramètre </summary>\n\t\t///\t<param name='other'> reference vers le vec à réunir avec le vec courant </param>\n\t\t///\t<returns> Un booléen indiquant si des éléments de 'other' on bien été ajoutés au vec </returns>\n\t\t/// <remarks> Le vecteur considère qu'ajouter un élément peut changer l'ordre des éléments (désactive toutes optimisations liées au tri) </remarks>\n\t\tbool add(const vec& other);\n\n\t\t/// <summary> Retire old_val de le vec courant </summary>\n\t\t///\t<param name='old_val'> reference vers un T qui sera retiré de le vec </param>\n\t\t///\t<returns> Un booléen indiquant si au moins un élément a bien été retiré </returns>\n\t\t/// <remarks> le vecteur doit avoir un prédicat pour faire la comparaison </remarks>\n\t\tbool remove(const T& old_val);\n\n\t\t/// <summary> Retire l'ensemble des valeurs contenues dans le parametre 'vals' du vec courant </summary>\n\t\t///\t<param name='vals'> tableau de T qui seront retirés du vec </param>\n\t\t///\t<param name='size'> taille du tableau vals </param>\n\t\t///\t<returns> Un booléen indiquant si au moins un élément a bien été retiré </returns>\n\t\t/// <remarks> le vecteur doit avoir un prédicat pour faire la comparaison </remarks>\n\t\t// Non type-safe, TODO: utiliser gsl::array_view, std::array et/ou std::initializer_list\n\t\tbool remove(const T vals[], size_type size);\n\n\t\t/// <summary> Ajuste, si possible, la capacité du vec à la taille spécifiée </summary>\n\t\t///\t\t<param name='capacity'> nouvelle taille de mémoire allouée pour la structure de donnée interne </param>\n\t\t///\t<returns> Un booléen indiquant si un ajustement de la capacité a bien été effectué </returns>\n\t\tbool ajust(size_type capacity);\n\n\t\t/// <summary> Trouve un élément spécifié en paramaètre dans le vecteur </summary>\n\t\t///\t<param name='element_to_find'> Référence constante vers l'élement de type T à rechercher </param>\n\t\t/// <remarks> le vecteur doit avoir un prédicat pour faire la comparaison </remarks>\n\t\t/// <remarks> Si le vecteur à été trié avant, cette opération utlise un algorithme de recherche plus rappide </remarks>\n\t\t///\t<returns> L'indice de l'élément dans le vecteur ou MAX_ALLOCATION_SIZE+1 si aucun éléments n'a été trouvé </returns>\n\t\tsize_type find(const T& element_to_find) const;\n\n\t\t/// <summary> Trie les éléments du vecteur </summary>\n\t\t/// <remarks> Utilise l'opérateur 'inferieur à' pour comparer les éléments </remarks>\n\t\t/// <remarks> Il serait préférable que le type T dispose d'une surcharge de la fonction swap pour des raisons de performances </remarks>\n\t\tvoid sort();\n\n\t\t/// <summary> Retourne la taille occupée du vecteur </summary>\n\t\tsize_type length() const;\n\n\t\t/// <summary> Retourne la capacité du vecteur </summary>\n\t\tsize_type capacity() const;\n\n\t\t//--------------------------------------------------- Surcharges d'opérateurs\n\n\t\t/// <summary> Surcharge de l'operateur d'assignement par copie </summary>\n\t\tconst vec& operator=(vec other);\n\n\t\t/// <summary> Surcharges de l'operateur '[]' permettant l'accès d'un élément du vecteur </summary>\n\t\tT operator[](size_type idx) const;\n\t\t/// <summary> Surcharges de l'operateur '[]' permettant l'accès et la modification d'un élément du vecteur </summary>\n\t\tT& operator[](size_type idx);\n\n\t\t/// <summary> Permute deux vecs donnés en paramètres dont les types d'éléments, T, sont identiques. </summary>\n\t\ttemplate<typename U>\n\t\tfriend void swap(vec<U>& lhs, vec<U>& rhs) noexcept;\n\n\t\t//----------------------------------------------- Constructeurs - destructeur\n\n\t\t/// <summary> Constructeur par default ou constructeur définissant les opérateurs utilisés pour faire des comparaisons entre éléments </summary>\n\t\tvec();\n\n\t\t/// <summary> Constructeur de copie </summary>\n\t\tvec(const vec& other);\n\n\t\t/// <summary> Move constructeur </summary>\n\t\tvec(vec&& other) noexcept;\n\n\t\t/// <summary> Constructeur d'un vec de taille pré-allouée et de taille maximum données </summary>\n\t\t///\t<param name='capacity'> Taille du nouveau vec </param>\n\t\t///\t<param name='max_capacity'> Taille maximum du nouveau vec </param>\n\t\t///\t<param name='eq_pred'> Pointeur vers la fonction qui sera utilisée pour faire l'égalité entre deux éléments </param>\n\t\t///\t<param name='comp_inf_pred'> Pointeur vers la fonction qui sera utilisée pour faire une comparaison 'inférieur à' entre deux éléments </param>\n\t\texplicit vec(size_type capacity, size_type max_capacity = MAX_ALLOCATION_SIZE, predicate eq_pred = nullptr, predicate comp_inf_pred = nullptr);\n\n\t\t/// <summary> Constructeur d'un vec à partir d'un ensemble d'éléments donné en paramètre </summary>\n\t\t///\t<param name='vals'> tableau des éléments qui seront ajoutés au vec </param>\n\t\t///\t<param name='size'> taille du tableau vals </param>\n\t\t// Non type-safe, TODO: utiliser gsl::array_view ou std::array\n\t\t//vec(const T vals[], size_type size);\n\n\t\t/// <summary> Destructeur de la colection courante </summary>\n\t\tvirtual ~vec() noexcept;\n\n\t\t//------------------------------------------------------ Constantes publiques\n\n\t\tstatic const size_type MAX_ALLOCATION_SIZE = std::numeric_limits<size_type>::max() - 1;\n\n\t\t//------------------------------------------------------- Fonctions statiques\n\n\t\t// ces fonctions sont statiques car elles n'on aucuns liens avec une instance si ce n'est le type des objets en argument\n\t\t// (évite des problème liés au fait de marquer ces fonction 'const' ou non)\n\n\t\t/// <summary> Simple fonction retournant toujours 'false' (pour les types ne disposant pas de l'opérateur '==' </summary>\n\t\ttemplate<typename U>\n\t\tinline static bool default_equality_predicate(const U& a, const U& b) { return false; };\n\n\t\t/// <summary> Simple fonction retournant toujours 'false' (pour les types ne disposant pas de l'opérateur 'inferieur à' </summary>\n\t\ttemplate<typename U>\n\t\tinline static bool default_inferior_comp_predicate(const U& a, const U& b) { return false; };\n\t\t// TODO utiliser SFINAE sur la présence des overloads de == et < pour les utiliser si disponnibles\n\n\t\t//--------------------------------------------------------------------- PRIVE \n\tprotected:\n\t\t//-------------------------------------------------------- Méthodes protégées\n\n\t\t/// <summary> Réalloue la mémoire pour le tableau m_vals.\n\t\t///\t\tLa nouvelle capacité du vecteur sera la plus petite puissance de 2 superieure au double de la capacité actuelle </summary>\n\t\tinline void reallocateMemory();\n\n\t\t/// <summary> Algorithme récursif Quicksort </summary>\n\t\tinline void quickSort(size_type p, size_type q) const;\n\n\t\t/// <summary> Fonction de partition utilisée pour l'algorithme Quicksort </summary>\n\t\tinline size_type partition(size_type p, size_type q) const;\n\n\t\t/// <summary> Fonction de partition utilisée pour l'algorithme Quicksort.\n\t\t///\t\tUtilise les prédicats donnés en paramètre pour faire la comparaison 'inférieure à' et l'égalité entre deux éléments de type T </summary>\n\t\tsize_type dichoto(const size_type beg_idx, const size_type end_idx, const T& val) const;\n\n\t\t/// <summary> Trouve le nombre d'éléments apparetenant à la fois à 'm_vals' et au paramètre 'vals_to_find' </summary>\n\t\t///\t<param name='vals_to_find'> tableau d'éléments de type T qui seront recherchés dans le vec </param>\n\t\t///\t<param name='size'> taille du tableau 'vals_to_find' </param>\n\t\t///\t<returns> le nombre d'éléments apparetenant à la fois à 'm_vals' et à 'vals_to_find' </returns>\n\t\tunsigned int find_all_of(const T vals_to_find[], size_type size) const;\n\n\t\t/// <summary> Désalloue la mémoire allouée pour le tableau d'objets de type T </summary>\n\t\tvoid dispose() noexcept;\n\n\t\t//--------------------------------------------------------- Attributs protégés\n\n\t\t/// Tableau de T\n\t\tT* m_vals = nullptr;\n\t\t/// Taille du tableau m_vals\n\t\tsize_type m_capacity = 0;\n\t\t/// Taille maximale du tableau m_vals\n\t\tconst size_type m_max_capacity = MAX_ALLOCATION_SIZE;\n\t\t/// Taille utilisée du tableau m_vals\n\t\tsize_type m_size = 0;\n\t\t/// Booleen indiquant si le vecteur peut être considèré comme trié\n\t\tbool m_is_sorted = false;\n\t\t/// Pointeur vers la fonction qui sera utilisée pour faire l'égalité entre deux éléments \n\t\tpredicate m_eq_pred = nullptr;//default_equality_predicate<T>;\n\t\t/// Pointeur vers la fonction qui sera utilisée pour faire une comparaison 'inférieur à' entre deux éléments\n\t\tpredicate m_comp_inf_pred = nullptr;//default_equality_predicate<T>;\n\n\t\t//------------------------------------------------------- Constantes protégées\n\n\t\tstatic const size_type INITIAL_ALLOCATION_SIZE = 4;\n\t};\n\n\t//--------------------- Implémentation de la classe vec<T> -----------------------\n\n\t//------------------------------------------------------------------------- PUBLIC\n\n\ttemplate<typename T>\n\tvoid vec<T>::add(const T& val_to_add)\n\t{\n\t\t// Reallocate memory if we don't have free space anymore\n\t\tif (UNLIKELY(m_size == m_capacity))\n\t\t\treallocateMemory();\n\n\t\t// Append/Copy new value\n\t\tm_vals[m_size] = val_to_add;\n\t\t++m_size;\n\n\t\tm_is_sorted = false; // We assume vector is no more sorted\n\t}\n\n\ttemplate<typename T>\n\ttemplate<typename... CtorArgsTypes>\n\tT& vec<T>::add(CtorArgsTypes&&... ctor_args)\n\t{\n\t\tm_is_sorted = false; // We assume vector is no more sorted\n\n\t\t// Reallocate memory if we don't have free space anymore\n\t\tif (UNLIKELY(m_size == m_capacity))\n\t\t\treallocateMemory();\n\n\t\t// Just call T constructor with specified arguments without any memory allocation\n\t\tnew (m_vals + m_size) T(std::forward<CtorArgsTypes>(ctor_args)...);\n\t\treturn m_vals[m_size++];\n\t}\n\n\ttemplate<typename T>\n\tbool vec<T>::add(const vec& other)\n\t{\n\t\tif (other.m_size == 0 || other.m_vals == nullptr)\n\t\t\treturn false; // We don't have any elements to append\n\n\t\tif (m_capacity - m_size >= other.m_size)\n\t\t{\n\t\t\t// We have enought free allocated space to store other.m_vals in m_vals\n\t\t\tfor (size_type i = 0; i < other.m_size; ++i)\n\t\t\t\tm_vals[m_size + i] = other.m_vals[i];\n\n\t\t\tm_size += other.m_size;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Allocate a new array of T objects\n\t\t\tsize_type new_capacity = lowest_pow_of_two_greater_than(m_size + other.m_size);\n\t\t\tT* new_vals = new T[new_capacity];\n\n\t\t\t// Copy other.m_vals to new_vals\n\t\t\tfor (size_type i = 0; i < other.m_size; ++i)\n\t\t\t\tnew_vals[i + m_size] = other.m_vals[i];\n\n\t\t\tif (m_vals != nullptr)\n\t\t\t{\n\t\t\t\t// Copy m_vals objects to new_vals\n\t\t\t\tfor (size_type i = 0; i < m_size; ++i)\n\t\t\t\t\tnew_vals[i] = m_vals[i];\n\n\t\t\t\tdelete[] m_vals;\n\t\t\t}\n\n\t\t\t// Assign the new array to 'm_vals' and update 'm_capacity' and 'm_size'\n\t\t\tm_vals = new_vals;\n\t\t\tm_size += other.m_size;\n\t\t\tm_capacity = new_capacity;\n\t\t}\n\n\t\tm_is_sorted = false; // We assume vector is no more sorted\n\t\treturn true;\n\t}\n\n\t// Non type-safe, TODO: utiliser gsl::array_view ou std::array\n\ttemplate<typename T>\n\tbool vec<T>::remove(const T vals_to_remove[], size_type size)\n\t{\n\t\tif (vals_to_remove == nullptr || size == 0 || m_vals == nullptr)\n\t\t\treturn false;\n\n\t\t// Find the number of elements to remove and get the index of the first one\n\t\tunsigned int removes_todo_count = find_all_of(vals_to_remove, size);\n\n\t\tif (removes_todo_count == 0)\n\t\t\treturn false; // There isn't any element to remove\n\n\t\tif (removes_todo_count >= m_size)\n\t\t\tdispose(); // We remove all elements\n\t\telse\n\t\t{\n\t\t\tsize_type new_size = m_size - removes_todo_count;\n\t\t\tT* new_vals = new T[new_size];\n\n\t\t\t// Copy 'm_vals' values in 'new_vals' except those present in 'vals_to_remove'\n\t\t\tsize_type removes_count = 0;\n\t\t\tfor (size_type i = 0; i < m_size; ++i)\n\t\t\t{\n\t\t\t\tauto val = m_vals[i];\n\n\t\t\t\t// Check if 'm_vals[i]' is in 'vals_to_remove'\n\t\t\t\tbool is_to_copy = true;\n\t\t\t\tfor (size_type j = 0; j < size && removes_count < removes_todo_count; ++j)\n\t\t\t\t{\n\t\t\t\t\tif (m_eq_pred(vals_to_remove[j], val))\n\t\t\t\t\t{\n\t\t\t\t\t\t++removes_count;\n\t\t\t\t\t\tis_to_copy = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (is_to_copy)\n\t\t\t\t\tnew_vals[i - removes_count] = val;\n\t\t\t}\n\n\t\t\tdelete[] m_vals;\n\t\t\tm_vals = new_vals;\n\t\t\tm_size = new_size;\n\t\t\tm_capacity = new_size;\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate<typename T>\n\tbool vec<T>::remove(const T& old_value)\n\t{\n\t\treturn retirer(&old_value, 1);\n\t}\n\n\ttemplate<typename T>\n\tbool vec<T>::ajust(size_type new_capacity)\n\t{\n\t\tif (new_capacity < m_size || new_capacity == m_capacity)\n\t\t\treturn false; // We forbid any element removal during a 'vec::ajust' call\n\n\t\tif (new_capacity == 0)\n\t\t{\n\t\t\t// We know that 'm_size == 0', 'm_capacity > 0' and 'm_vals != nullptr' \n\t\t\t// We free all pre-allocated memory and return:\n\t\t\tdispose();\n\t\t\treturn true;\n\t\t}\n\n\t\t// Allocate a new array of T objects\n\t\tT* new_vals = new T[new_capacity];\n\n\t\t// If this vec have any T objects, we copy them to 'new_vals' and we delete 'm_vals'\n\t\tif (m_vals != nullptr)\n\t\t{\n\t\t\tfor (size_type i = 0; i < m_size; ++i)\n\t\t\t\tnew_vals[i] = m_vals[i];\n\n\t\t\tdelete[] m_vals;\n\t\t}\n\n\t\t// Assign the new array to 'm_vals' and update 'm_capacity'\n\t\tm_vals = new_vals;\n\t\tm_capacity = new_capacity;\n\n\t\treturn true;\n\t}\n\n\ttemplate<typename T>\n\ttypename vec<T>::size_type vec<T>::find(const T& element_to_find) const\n\t{\n\t\tif (UNLIKELY(m_eq_pred == nullptr || m_comp_inf_pred == nullptr))\n\t\t\treturn vec::MAX_ALLOCATION_SIZE + 1;\n\n\t\tif (LIKELY(m_size > 0))\n\t\t{\n\t\t\tif (m_is_sorted)\n\t\t\t{\n\t\t\t\tif (m_size != 1)\n\t\t\t\t\t// Dichotomic search\n\t\t\t\t\treturn dichoto(0, m_size-1, element_to_find);\n\t\t\t\telse\n\t\t\t\t\treturn m_eq_pred(element_to_find, m_vals[0]) ? 0 : MAX_ALLOCATION_SIZE + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Simple loop over vector elements\n\t\t\t\tfor (size_type i = 0; i < m_size; ++i)\n\t\t\t\t\tif (m_eq_pred(element_to_find, m_vals[i]))\n\t\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn vec::MAX_ALLOCATION_SIZE + 1;\n\t}\n\n\ttemplate<typename T>\n\tvoid vec<T>::sort()\n\t{\n\t\tif (UNLIKELY(m_eq_pred == nullptr || m_comp_inf_pred == nullptr))\n\t\t\treturn;\n\n\t\t// Use quick sort algorithm to sort elements\n\t\tquickSort(0, m_size);\n\n\t\tm_is_sorted = true;\n\t}\n\n\ttemplate<typename T>\n\ttypename vec<T>::size_type vec<T>::length() const { return m_size; }\n\n\ttemplate<typename T>\n\ttypename vec<T>::size_type vec<T>::capacity() const { return m_capacity; }\n\n\t//---------------------------------------------------- Constructeurs - destructeur\n\n\ttemplate<typename T>\n\tvec<T>::vec()\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'vec<T>::vec()'\" << endl;\n#endif\n\t}\n\n\ttemplate<typename T>\n\tvec<T>::vec(vec&& other) noexcept\n\t\t: vec()\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au move-constructeur 'vec<T>::vec(vec<T>&&)'\" << endl;\n#endif\n\t\tswap(*this, other);\n\t}\n\n\ttemplate<typename T>\n\tvec<T>::vec(const vec& other)\n\t\t: vec(other.m_capacity)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur de copie 'vec<T>::vec(const vec<T>&)'\" << endl;\n#endif\n\t\tm_size = other.m_size;\n\t\tm_eq_pred = other.m_eq_pred;\n\t\tm_comp_inf_pred = other.m_comp_inf_pred;\n\t\ttry // T's copy assignment operator could throw and let vec in incoherent state\n\t\t{\n\t\t\t// Copy 'other' vec elements\n\t\t\tfor (size_type i = 0; i < other.m_size; ++i)\n\t\t\t\tm_vals[i] = other.m_vals[i];\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tdispose();\n\t\t\tthrow;\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tvec<T>::vec(size_type capacity, size_type max_capacity, predicate eq_pred, predicate comp_inf_pred)\n\t\t: m_capacity(capacity), m_max_capacity(max_capacity), m_eq_pred(eq_pred), m_comp_inf_pred(comp_inf_pred)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'vec<T>::vec(size_type, predicate eq_pred = &default_equality_predicate<T>, predicate comp_inf_pred = &default_inferior_comp_predicate<T>)'\" << endl;\n#endif\n\n\t\tif (capacity > 0)\n\t\t\tm_vals = new T[capacity];\n\t\telse\n\t\t\tm_vals = nullptr;\n\t}\n\n\t/*template<typename T>\n\tvec<T>::vec(const T vals[], size_type size)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'vec<T>::vec(const T[], size_type)'\" << endl;\n#endif\n\n\t\tif (size > 0 && vals != nullptr)\n\t\t{\n\t\t\t// Create a new array of T objects\n\t\t\tm_vals = new T[size];\n\t\t\tm_capacity = size;\n\n\t\t\t// Copy given elements\n\t\t\tfor (size_type i = 0; i < size; ++i)\n\t\t\t\tm_vals[i] = vals[i];\n\t\t\tm_size = size;\n\t\t}\n\t}*/\n\n\ttemplate<typename T>\n\tvec<T>::~vec() noexcept\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au destructeur de 'vec<T>'\" << endl;\n#endif\n\t\t// On désalloue la mémoire allouée pour le tableau de T si nescessaire\n\t\tdispose();\n\t}\n\n\t//-------------------------------------------------------- Surcharges d'opérateurs\n\ttemplate<typename T>\n\tconst vec<T>& vec<T>::operator=(vec other)\n\t{\n\t\t// Copy and swap idiom (in 'rule of 4' context (copy elision))\n\t\tswap(*this, other);\n\t\treturn *this;\n\t}\n\n\ttemplate<typename T>\n\tT vec<T>::operator[](size_type idx) const { return m_vals[idx]; }\n\n\ttemplate<typename T>\n\tT& vec<T>::operator[](size_type idx) {\n\t\treturn m_vals[idx];\n\t}\n\n\ttemplate<typename U>\n\tvoid swap(vec<U>& lhs, vec<U>& rhs) noexcept\n\t{\n\t\t// if one of the following swap calls isn't noexcept, we raise a static_assert\n// Commenté car is_nothrow_swappable ne fonctionne pas avec gcc installé en IF\n//\t\tstatic_assert(is_nothrow_swappable<typename vec<U>::size_type, U*>(), \"Swap function could throw and let vec<T> objects in incoherant state!\");\n\n\t\t// enable ADL (following lines will use custom implementation of swap or std::swap if there isn't custom implementation)\n\t\tusing std::swap;\n\n\t\tswap(lhs.m_size, rhs.m_size);\n\t\tswap(lhs.m_capacity, rhs.m_capacity);\n\t\tswap(lhs.m_vals, rhs.m_vals);\n\t}\n\n\t//-------------------------------------------------------------------------- PRIVE\n\n\t//------------------------------------------------------------- Méthodes protégées\n\n\ttemplate<typename T>\n\tinline void vec<T>::reallocateMemory()\n\t{\n\t\t// Take a power of two capacity greater than 2 * m_size\n\t\tif (LIKELY(m_size > 0))\n\t\t{\n\t\t\tsize_type powOf2_size = lowest_pow_of_two_greater_than(2 * m_size);\n\t\t\tajust(powOf2_size < m_max_capacity ? powOf2_size : m_max_capacity);\n\t\t}\n\t\telse\n\t\t\tajust(INITIAL_ALLOCATION_SIZE);\n\t}\n\n\ttemplate<typename T>\n\tinline void vec<T>::quickSort(size_type p, size_type q) const\n\t{\n\t\tif (p < q)\n\t\t{\n\t\t\tsize_type r = partition(p, q);\n\t\t\tquickSort(p, r);\n\t\t\tquickSort(r + 1, q);\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tinline typename vec<T>::size_type vec<T>::partition(size_type p, size_type q) const\n\t{\n\t\t// enable ADL (following lines will use custom implementation of swap or std::swap if there isn't custom implementation)\n\t\tusing std::swap;\n\n\t\tT val = m_vals[p];\n\t\tsize_type i = p;\n\n\t\tfor (size_type j = p + 1; j < q; ++j)\n\t\t\tif (!(m_comp_inf_pred(val, m_vals[j])))\n\t\t\t\tswap(m_vals[++i], m_vals[j]);\n\n\t\tswap(m_vals[i], m_vals[p]);\n\t\treturn i;\n\t}\n\n\ttemplate<typename T>\n\ttypename vec<T>::size_type vec<T>::dichoto(size_type beg_idx, size_type end_idx, const T& val) const\n\t{\n\t\tlong beg_idx_l = beg_idx;\n\t\tlong end_idx_l = end_idx;\n\n\t\twhile (beg_idx_l <= end_idx_l)\n\t\t{\n\t\t\tconst long mid_idx = (end_idx_l + beg_idx_l) / 2; // get middle index\n\n\t\t\tif (m_eq_pred(m_vals[mid_idx], val))\n\t\t\t\treturn mid_idx;\t\t\t\t// return the index of the element we found\n\t\t\telse if (m_comp_inf_pred(m_vals[mid_idx], val))\n\t\t\t\tbeg_idx_l = mid_idx + 1;\t// we choose the right part\n\t\t\telse\n\t\t\t\tend_idx_l = mid_idx - 1;\t// we choose the left part\n\t\t}\n\n\t\treturn MAX_ALLOCATION_SIZE + 1; // Not found\n\t}\n\n\ttemplate<typename T>\n\tunsigned int vec<T>::find_all_of(const T vals_to_find[], size_type size) const\n\t{\n\t\tunsigned int matches_count = 0;\n\n\t\tif (size > 0 && vals_to_find != nullptr && m_size > 0)\n\t\t{\n\t\t\tfor (size_type idx2 = 0; idx2 < size; ++idx2)\n\t\t\t{\n\t\t\t\tif (find(vals_to_find[idx2]) < m_size)\n\t\t\t\t\t++matches_count;\n\t\t\t}\n\t\t}\n\n\t\treturn matches_count;\n\t}\n\n\ttemplate<typename T>\n\tvoid vec<T>::dispose() noexcept\n\t{\n\t\tif (m_vals != nullptr)\n\t\t{\n\t\t\tdelete[] m_vals;\n\t\t\tm_vals = nullptr;\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t}\n\t}\n\n\t//------------------------------------------------------------ Fonctions statiques\n\n/*\ttemplate<typename T>\n\tinline bool default_equality_predicate(const T& a, const T& b) { return a == b; }\n\n\ttemplate<typename T>\n\tinline bool default_inferior_comp_predicate(const T& a, const T& b) { return a < b; }*/\n\n}\n" }, { "alpha_fraction": 0.6430202126502991, "alphanum_fraction": 0.6523157358169556, "avg_line_length": 25.777292251586914, "blob_id": "584605c0e273998eee71969a21859664d7889dcc", "content_id": "68b25f004ff7ee9103f17f9cde22d8cf8ef60513", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6168, "license_type": "permissive", "max_line_length": 120, "num_lines": 229, "path": "/TP1_Probas/ProgrammeC/file_attente.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "#include \"file_attente.h\"\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <math.h>\n\n#include \"lois_distributions.h\"\n\nvoid init(file_attente* fa)\n{\n\tmemset(fa->arrivee, 0.0, sizeof(double)*ARRAY_MAX_SIZE);\n\tmemset(fa->depart, 0.0, sizeof(double)*ARRAY_MAX_SIZE);\n}\n\nvoid init_evol(evolution* evol)\n{\n\tmemset(evol->nombre, 0.0, sizeof(int)*ARRAY_MAX_SIZE);\n\tmemset(evol->temps, 0.0, sizeof(double)*ARRAY_MAX_SIZE);\n}\n\n// Création de la file d'attente en fonction des paramètres des deux distributions exponentielles et du temps D\nfile_attente FileMM1(double lambda, double mu, double D)\n{\n\tfile_attente fa;\n\tinit(&fa);\n\n\t// Creation du tableau d'arrivée\n\tdouble t = Exponentielle(lambda);\n\tfor (fa.size_arrivee = 0; 1; ++fa.size_arrivee)\n\t{\n\t\tt += Exponentielle(lambda);\n\t\tif (t > D)\n\t\t\tbreak;\n\t\tfa.arrivee[fa.size_arrivee] = t;\n\t}\n\n\t// Creation du tableau de départ\n\tdouble new_depart = fa.arrivee[0] + Exponentielle(mu);\n\tif (new_depart < D)\n\t{\n\t\tfa.depart[0] = new_depart;\n\t\tfor (fa.size_depart = 1; fa.size_depart < fa.size_arrivee; ++fa.size_depart)\n\t\t{\n\t\t\tif (fa.depart[fa.size_depart - 1] <= fa.arrivee[fa.size_depart])\n\t\t\t\tnew_depart = fa.arrivee[fa.size_depart] + Exponentielle(lambda);\n\t\t\telse\n\t\t\t\tnew_depart = fa.depart[fa.size_depart - 1] + Exponentielle(lambda);\n\n\t\t\tif (new_depart > D)\n\t\t\t\tbreak;\n\t\t\tfa.depart[fa.size_depart] = new_depart;\n\t\t}\n\t}\n\telse\n\t\tfa.size_depart = 0;\n\n\treturn fa;\n}\n\nfile_attente FileMMN(double lambda, double mu, double D, size_t n)\n{\n\tfile_attente fa;\n\tinit(&fa);\n\n\t// Creation du tableau d'arrivée (inchangé par rapport à MM1)\n\tdouble t = Exponentielle(lambda);\n\tfor (fa.size_arrivee = 0; 1; ++fa.size_arrivee)\n\t{\n\t\tt += Exponentielle(lambda);\n\t\tif (t > D)\n\t\t\tbreak;\n\t\tfa.arrivee[fa.size_arrivee] = t;\n\t}\n\n\t// Creation du tableau de départ (ici intervient les chagements pusique l'on traite jusqu'a deux clients à la fois)\n\tdouble new_depart = fa.arrivee[0] + Exponentielle(mu);\n\tdouble* servers = (double*)malloc(sizeof(double) * n); // contien l'heur j'usqu'a laquelle chaque serveur est occupé\n\tmemset(servers, 0.0, sizeof(double) * n);\n\n\tif (new_depart < D)\n\t{\n\t\tfa.depart[0] = new_depart;\n\t\tfor (fa.size_depart = 1; fa.size_depart < fa.size_arrivee; ++fa.size_depart)\n\t\t{\n\t\t\tdouble min_server_free_time = D+1;\n\t\t\tint started = 0;\n\t\t\tfor (size_t server_idx = 0; server_idx < n; ++server_idx)\n\t\t\t{\n\t\t\t\t// On met à jour le moment le plus tôt où un server est libre\n\t\t\t\tmin_server_free_time = servers[server_idx] < min_server_free_time ? servers[server_idx] : min_server_free_time;\n\t\t\t\t\n\t\t\t\t// On vérifie si le serveur n'est pas occupé\n\t\t\t\tif(fa.arrivee[fa.size_depart] >= servers[server_idx])\n\t\t\t\t{\n\t\t\t\t\t// On traite immédiatement la requette\n\t\t\t\t\tnew_depart = fa.arrivee[fa.size_depart] + Exponentielle(lambda);\n\t\t\t\t\tservers[server_idx] = new_depart;\n\t\t\t\t\tstarted = 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Si tous les serveurs sont occupés, ont retarde la tache pour être traité par le serveur qui auras fini le plus tôt\n\t\t\tif(started == 0)\n\t\t\t\tnew_depart = min_server_free_time + Exponentielle(lambda);\n\n\t\t\tif (new_depart > D)\n\t\t\t\tbreak;\n\t\t\tfa.depart[fa.size_depart] = new_depart;\n\t\t}\n\t}\n\telse\n\t\tfa.size_depart = 0;\n\n\tfree(servers);\n\n\treturn fa;\t\n}\n\n// Calcul de l'évolution de la file d'attente\nevolution get_evolution(file_attente* fa, double D)\n{\n\tevolution evol;\n\tinit_evol(&evol);\n\tevol.size = 1;\n\n\tsize_t arrivee_count = 0, depart_count = 0;\n\tsize_t arrivee_idx = 0, depart_idx = 0;\n\tdouble t = 0.0;\n\twhile (arrivee_idx < fa->size_arrivee)\n\t{\n\t\t// On se place soit sur un temps d'arrivée ou de départ (mise à jour pour chaque temps présent dans la file)\n\t\tif (fa->arrivee[arrivee_idx] <= fa->depart[depart_idx] || fa->depart[depart_idx] == 0)\n\t\t{\n\t\t\tevol.temps[1 + depart_idx + arrivee_idx] = t = fa->arrivee[arrivee_idx];\n\t\t\t++arrivee_idx;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tevol.temps[1 + depart_idx + arrivee_idx] = t = fa->depart[depart_idx];\n\t\t\t++depart_idx;\n\t\t}\n\n\t\t// Recherche du nombre d'arrivées avant t\n\t\tsize_t idx;\n\t\tfor (idx = arrivee_count; idx < fa->size_arrivee; ++idx)\n\t\t\tif (fa->arrivee[idx] > t)\n\t\t\t\tbreak;\n\t\tarrivee_count = idx;\n\n\t\t// Recherche du nombre de départs avant t\n\t\tfor (idx = depart_count; idx < fa->size_depart; ++idx)\n\t\t\tif (fa->depart[idx] > t)\n\t\t\t\tbreak;\n\t\tdepart_count = idx;\n\n\t\tevol.nombre[depart_idx + arrivee_idx] = arrivee_count - depart_count;\n\t\t++evol.size;\n\t}\n\n\tevol.temps[evol.size] = D;\n\tevol.nombre[evol.size] = evol.size > 0 ? evol.nombre[evol.size-1] : 0;\n\t++evol.size;\n\n\treturn evol;\n}\n\n// Serialisation de la file d'attente\nvoid fprint(file_attente* data, const char* filename)\n{\n\t// Ouverture du fichier CSV\n\tFILE* fichier = fopen(filename, \"w\");\n\tif (fichier != NULL)\n\t{\n\t\tfprintf(fichier, \"arrivee, depart \\n\");\n\n\t\tfor (size_t i = 0; i < data->size_arrivee || i < data->size_depart; ++i)\n\t\t\tfprintf(fichier, \"%lf, %lf\\n\", data->arrivee[i], data->depart[i]);\n\n\t\tfclose(fichier);\n\t}\n}\n\n// Sérialisation de l'évolution de la file d'attente\nvoid fprint_evol(evolution* data, const char* filename)\n{\n\t// Ouverture du fichier CSV\n\tFILE* fichier = fopen(filename, \"w\");\n\tif (fichier != NULL)\n\t{\n\t\tfprintf(fichier, \"t, nombre \\n\");\n\n\t\tfor (size_t i = 0; i < data->size; ++i)\n\t\t\tfprintf(fichier, \"%lf, %d\\n\", data->temps[i], data->nombre[i]);\n\n\t\tfclose(fichier);\n\t}\n}\n\n// Temps moyen de présence d'un client (attente + service)\ndouble get_time_mean(file_attente* fa, evolution* evol)\n{\n\t// Calcul du temps total de présence de tout les clients accumulé\n\tdouble sum = 0;\n\tdouble delta = 0;\n\tfor (size_t i = 0; i < evol->size; ++i)\n\t{\n\t\tdelta = i > 0 ? evol->temps[i] - evol->temps[i - 1] : evol->temps[i];\n\t\tsum += evol->nombre[i] * delta;\n\t}\n\n\treturn sum / fa->size_arrivee; // On divise par le nombre de clients\n}\n\n// Nombre moyen de clients dans le système\ndouble get_number_mean(evolution* evol)\n{\n\t// Calcul du temps total de présence de tout les clients accumulé\n\tdouble sum = 0;\n\tdouble delta = 0;\n\tfor (size_t i = 0; i < evol->size; ++i)\n\t{\n\t\tdelta = i > 0 ? evol->temps[i] - evol->temps[i - 1] : evol->temps[i];\n\t\tsum += evol->nombre[i] * delta;\n\t}\n\n\treturn sum / evol->temps[evol->size - 1]; // On divise par la durée totale\n}\n" }, { "alpha_fraction": 0.46167799830436707, "alphanum_fraction": 0.7188208699226379, "avg_line_length": 19.990476608276367, "blob_id": "1887b6a8043a6f008f9eef545b08b4b48b09dbd9", "content_id": "ac5a5a6506ef3d4e26599236dd1fdf06d46f2016", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2205, "license_type": "permissive", "max_line_length": 48, "num_lines": 105, "path": "/TP4_Archi/ex1.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"msp430fg4618.h\"\n#include \"lcd.h\"\n\n#define TACTL_TACLK\t\t\t0b0000000000000000\n#define TACTL_ACLK\t\t\t0b0000000100000000\n#define TACTL_SMCLK\t\t\t0b0000001000000000\n#define TACTL_INCLK\t\t\t0b0000001100000000\n\n#define TACTL_IDX1\t\t\t0b0000000000000000\n#define TACTL_IDX2\t\t\t0b0000000001000000\n#define TACTL_IDX4\t\t\t0b0000000010000000\n#define TACTL_IDX8\t\t\t0b0000000011000000\n\n#define TACTL_STOP\t\t\t0b0000000000000000\n#define TACTL_UP\t\t\t0b0000000000010000\n#define TACTL_CONT\t\t\t0b0000000000100000\n#define TACTL_UP_DOWN\t\t0b0000000000110000\n\n#define TACCTLx_NO_CAPTURE\t0b0000000000000000\n#define TACCTLx_RISING\t\t0b0100000000000000\n#define TACCTLx_FALLING\t\t0b1000000000000000\n#define TACCTLx_BOTH\t\t0b1100000000000000\n\n#define TACCTLx_CCIxA\t\t0b0000000000000000\n#define TACCTLx_CCIxB\t\t0b0001000000000000\n#define TACCTLx_GND\t\t\t0b0010000000000000\n#define TACCTLx_VCC\t\t\t0b0011000000000000\n\n#define TACCTLx_CAPT\t\t0b0000000100000000\n#define TACCTLx_COMP\t\t0b0000000000000000\n\n#define TASSEL_MASK\t\t\t0b0000001100000000\n#define IDx_MASK\t\t\t0b0000000011000000\n#define MCx_MASK\t\t\t0b0000000000110000\n#define TACLR_MASK\t\t\t0b0000000000000100\n#define TAIE_MASK\t\t\t0b0000000000000010\n#define TAIFG_MASK\t\t\t0b0000000000000001\n\n#define CCIE_MASK\t\t\t0b0000000000010000\n\n#define SMCLK_10MS 10486\n#define ACLK_10MS 328\n\nstatic unsigned int cpt = 0;\n\nstatic void init_timer()\n{\n\tTA0R = 0;\n\tCCR0 = SMCLK_10MS;\n\tCCTL0 = TACCTLx_RISING | TACCTLx_COMP | CCIE;\n\tTACTL = TASSEL_2 | ID_0 | MC_1;\n}\n\nvoid mon_traitement_interuption_timer(void) {\n\t\tcpt++;\n\t\tlcd_display_number(cpt);\n\t\tP5OUT = P5OUT ^ 0x02 ; // toggle P5.1 (LED4)\n\t\t//TACTL = TASSEL_2 | ID_0 | MC_2 | TAIE;\n}\n\nint main()\n{\n\tlcd_init(); // Initialize screen\n\tP5DIR |= 0x02 ; // Set P5.1 to output direction\n\t\n\tinit_timer();\n\n\tlcd_display_number(cpt);\n\t\n\t//SR |= GIE;\n\t\n\t__asm(\"EINT\");\n\t\n\tfor(;;)\n\t{\n\t\t\n\t}\n\n\treturn 0;\n}\n\nint main_2()\n{\n\tlcd_init(); // Initialize screen\n\tP5DIR |= 0x02 ; // Set P5.1 to output direction\n\t\n\tinit_timer();\n\n\tunsigned int cpt = 0;\n\tlcd_display_number(cpt);\n\t\n\tfor(;;)\n\t{\n\t\tif((TACTL & TAIFG) != 0x00)\n\t\t{\n\t\t\tcpt++;\n\t\t\tlcd_display_number(cpt);\n\t\t\tP5OUT = P5OUT ^ 0x02 ; // toggle P5.1 (LED4)\n\t\t\t\n\t\t\tTACTL = TASSEL_2 | ID_1 | MC_2 | TAIE;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.71257483959198, "alphanum_fraction": 0.7305389046669006, "avg_line_length": 21.33333396911621, "blob_id": "a2857dfcfcca3f7df8eed2a144d044a2b2697b5c", "content_id": "7406490d4dc26eb1b812511568a4cabe48d74c65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 334, "license_type": "permissive", "max_line_length": 76, "num_lines": 15, "path": "/TP1_BDDI/fragment victoire - pes/trigger_supp_employe.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "CREATE OR REPLACE TRIGGER SUPP_EMPLOYE \nBEFORE DELETE ON Employes \nFOR EACH ROW\nDECLARE\n isReferenced NUMBER;\nBEGIN\n SELECT COUNT(*) INTO isReferenced\n FROM Commandes\n WHERE NO_EMPLOYE = :OLD.NO_EMPLOYE;\n \n if(isReferenced != 0)\n THEN\n RAISE_APPLICATION_ERROR(-20002, 'Commande existante pour NO_EMPLOYE !');\n END IF;\nEND;" }, { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.75, "avg_line_length": 55, "blob_id": "2c4b06eb78571662be47da5d4a6fce0e77613b17", "content_id": "603d04d16fe3eb005a4a36b9b92d1e7f8201e7cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 57, "license_type": "permissive", "max_line_length": 55, "num_lines": 1, "path": "/TP1_Concurrency/readme.md", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "![Poster récapitulatif](http://i.imgur.com/pZqoW6Q.jpg)\n" }, { "alpha_fraction": 0.8065110445022583, "alphanum_fraction": 0.8065110445022583, "avg_line_length": 48.30303192138672, "blob_id": "fb79272ba5ec9e9e236951297014c364ba339b05", "content_id": "418cc464df8669a8dbe69c17e12659f750efded6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1628, "license_type": "permissive", "max_line_length": 106, "num_lines": 33, "path": "/TP1_BDDI/RioriConstraints.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "ALTER TABLE CATEGORIES ADD CONSTRAINT PK_CATEGORIES PRIMARY KEY (CODE_CATEGORIE) ;\n\nALTER TABLE CLIENTS ADD CONSTRAINT PK_CLIENTS PRIMARY KEY (CODE_CLIENT) ;\nALTER TABLE COMMANDES ADD CONSTRAINT PK_COMMANDES PRIMARY KEY (NO_COMMANDE) ;\nALTER TABLE DETAILS_COMMANDES ADD CONSTRAINT PK_DETAILS_COMMANDES PRIMARY KEY (NO_COMMANDE, REF_PRODUIT) ;\nALTER TABLE EMPLOYES ADD CONSTRAINT PK_EMPLOYES PRIMARY KEY (NO_EMPLOYE) ;\nALTER TABLE FOURNISSEURS ADD CONSTRAINT PK_FOURNISSEURS PRIMARY KEY (NO_FOURNISSEUR) ;\nALTER TABLE PRODUITS ADD CONSTRAINT PK_PRODUITS PRIMARY KEY (REF_PRODUIT) ;\n\n\nALTER TABLE COMMANDES ADD CONSTRAINT FK_COMMANDE_CLIENTS \nFOREIGN KEY (CODE_CLIENT) REFERENCES CLIENTS (CODE_CLIENT) ;\n\nALTER TABLE COMMANDES ADD CONSTRAINT FK_COMMANDE_EMPLOYES \nFOREIGN KEY (NO_EMPLOYE) REFERENCES EMPLOYES (NO_EMPLOYE) ;\n\nALTER TABLE DETAILS_COMMANDES ADD CONSTRAINT FK_DETAILS_COMMANDES_COMMANDES \nFOREIGN KEY (NO_COMMANDE) REFERENCES COMMANDES (NO_COMMANDE) ;\n\nALTER TABLE DETAILS_COMMANDES ADD CONSTRAINT FK_DETAILS_COMMANDES_PRODUITS\nFOREIGN KEY (REF_PRODUIT) REFERENCES PRODUITS (REF_PRODUIT) ;\n\nALTER TABLE DETAILS_COMMANDES ADD CONSTRAINT FK_DETAILS_PRODUITS_PRODUITS \nFOREIGN KEY (REF_PRODUIT) REFERENCES PRODUITS (REF_PRODUIT) ;\n\nALTER TABLE EMPLOYES ADD CONSTRAINT FK_EMPLOYES_EMPLOYES \nFOREIGN KEY (REND_COMPTE) REFERENCES EMPLOYES (NO_EMPLOYE) ;\n\nALTER TABLE PRODUITS ADD CONSTRAINT FK_PRODUITS_CATEGORIE \nFOREIGN KEY (CODE_CATEGORIE) REFERENCES CATEGORIES (CODE_CATEGORIE) ;\n\nALTER TABLE PRODUITS ADD CONSTRAINT FK_PRODUITS_FOURNISEUR \nFOREIGN KEY (NO_FOURNISSEUR) REFERENCES FOURNISSEURS (NO_FOURNISSEUR) ;\n\n" }, { "alpha_fraction": 0.6192771196365356, "alphanum_fraction": 0.6192771196365356, "avg_line_length": 54.04081726074219, "blob_id": "a558e1d787293f35cb81f5aaf8c73966d8c58eab", "content_id": "0f021eae52f7b708e3f8235c2385855faf5847b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 5439, "license_type": "permissive", "max_line_length": 125, "num_lines": 98, "path": "/TP1_BDDI/vues.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": " -- Vues\n\n -- Vue detail commandes\nCREATE VIEW Details_Commandes AS \n SELECT *\n FROM pesotir.details_commandes_Amerique\n UNION ALL\n select *\n FROM gsarnette.details_commandes_Europe_Nord@EUROPE_NORD_LINK\n UNION ALL\n select *\n FROM gsarnette.details_commandes_autre@EUROPE_NORD_LINK\n UNION ALL\n SELECT *\n FROM fmacerouss.DETAILS_COMMANDES_EUROPE_SUD@EUROPE_SUD_LINK;\n\n -- Vue commandes\nCREATE VIEW Commandes AS \n SELECT *\n FROM pesotir.commandes_Amerique\n UNION ALL\n select *\n FROM gsarnette.commandes_Europe_Nord@EUROPE_NORD_LINK\n UNION ALL\n select *\n FROM gsarnette.commandes_autre@EUROPE_NORD_LINK\n UNION ALL \n SELECT *\n FROM fmacerouss.COMMANDES_EUROPE_SUD@EUROPE_SUD_LINK;\n \n-- Vue stock\nCREATE OR REPLACE VIEW STOCK AS \n SELECT *\n FROM pesotir.stock_Amerique\n WHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela')\n UNION ALL \n select *\n FROM gsarnette.stock_Europe_Nord@EUROPE_NORD_LINK\n WHERE Pays IN ('Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', 'Belgique',\n 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n \n UNION ALL\n select *\n FROM gsarnette.Stock_autre@EUROPE_NORD_LINK\n WHERE Pays IS NULL OR Pays NOT IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela', 'Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican',\n 'Malte', 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine', 'Monténégro', 'Serbie', \n 'Slovénie', 'Bulgarie', 'Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', \n 'Belgique', 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne') \n UNION ALL\n SELECT *\n FROM fmacerouss.STOCK_EUROPE_SUD@EUROPE_SUD_LINK\n WHERE Pays IN ('Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican', 'Malte', \n 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine',\n 'Monténégro', 'Serbie', 'Slovénie', 'Bulgarie'); \n\n-- Vue Clients\nCREATE OR REPLACE VIEW Clients AS \n SELECT *\n FROM pesotir.Clients_Amerique\n WHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela')\n UNION ALL\n select *\n FROM gsarnette.Clients_Europe_Nord@EUROPE_NORD_LINK\n WHERE Pays IN ('Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', 'Belgique', \n 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n UNION ALL\n select *\n FROM gsarnette.Clients_autre@EUROPE_NORD_LINK\n WHERE Pays IS NULL OR Pays NOT IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela', 'Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican',\n 'Malte', 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine', 'Monténégro', 'Serbie', \n 'Slovénie', 'Bulgarie', 'Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', \n 'Belgique', 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n UNION ALL\n SELECT *\n FROM fmacerouss.CLIENTS_EUROPE_SUD@EUROPE_SUD_LINK\n WHERE Pays IN ('Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican', 'Malte', \n 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine',\n 'Monténégro', 'Serbie', 'Slovénie', 'Bulgarie');\n" }, { "alpha_fraction": 0.5921264886856079, "alphanum_fraction": 0.6156824827194214, "avg_line_length": 35.674556732177734, "blob_id": "6bde4addad4c6c3a7099a7d76e35db7430dc07f1", "content_id": "55eaaede18ed0b52176b190709f773e09adfaa15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6223, "license_type": "permissive", "max_line_length": 154, "num_lines": 169, "path": "/TP1_Probas/ProgrammeC/main.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <sys/time.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <time.h>\n#include <math.h>\n#include <limits.h>\n#include <stdbool.h>\n\n#include \"file_attente.h\"\n#include \"random_generation.h\"\n#include \"lois_distributions.h\"\n\n#ifdef _WIN32\n#include <intrin.h>\nuint64_t rdtsc() {\n\treturn __rdtsc();\n}\n#else\nint/*uint64_t ??*/ rdtsc()\n{\n\t// cette fonction cree un warning : c'est normal.\n\t__asm__ __volatile__(\"rdtsc\");\n}\n#endif\n\n//----------------------------------------------------------------------------- FORWARD DECLARATIONS\n\ndouble Frequency(generator_array* random_values);\ndouble p_value_monobit(generator_array* random_values);\ndouble Runs(generator_array* data);\n\n//--------------------------------------------------------------------------------------------- MAIN\n\nint main(int argc, char *argv[])\n{\n\tsrand(rdtsc());\n\n\t// Ouverture du fichier de resultat des tests des générateurs d'aléatoire\n\tFILE* fichier = fopen(\"../_test_results.csv\", \"w\");\n\tif (fichier == NULL)\n\t\treturn -1;\n\n\t// Calcul et affichage de la P-valeur des différentes méthodes de génération de valeures aléatoires (csv)\n\tfprintf(fichier, \"monobit pvalue, frequency, runs pvalue\\n\");\n\tfor (size_t i = 0; i < 25; ++i)\n\t{\n\t\t// Génération des tableaux de valeurs aléatoires\n\t\tgenerator_array von_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 13, \"../_von_neumann.csv\", generate_neumann); // de 0 à 9999 ? sur 14 ou 13 bits ?\n\t\tgenerator_array aes_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 32, \"../_aes.csv\", generate_aes);\n\t\tgenerator_array twi_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 32, \"../_twister.csv\", generate_twister);\n\t\tgenerator_array high_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 4, \"../_rand_high.csv\", generate_rand_high);\n\t\tgenerator_array low_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 4, \"../_rand_low.csv\", generate_rand_low);\n\t\tgenerator_array rand_values = GenerateRandomValues(RANDOM_VALUE_COUNT, 16 - 1, \"../_rand.csv\", rand);\n\n\t\t// Calcul et stockage des résultats des différents tests\n\t\tfprintf(fichier, \"rand(), %f, %f, %f \\n\", p_value_monobit(&rand_values), Frequency(&rand_values), Runs(&rand_values));\n\t\tfprintf(fichier, \"Von Neumann, %f, %f, %f\\n\", p_value_monobit(&von_values), Frequency(&von_values), Runs(&von_values));\n\t\tfprintf(fichier, \"Mersenne-Twister, %f, %f, %f\\n\", p_value_monobit(&twi_values), Frequency(&twi_values), Runs(&twi_values));\n\t\tfprintf(fichier, \"AES, %f, %f, %f\\n\", p_value_monobit(&aes_values), Frequency(&aes_values), Runs(&aes_values));\n\n\t\t// Libération de la mémoire\n\t\tdestroy(&von_values); destroy(&aes_values); destroy(&twi_values); destroy(&high_values); destroy(&low_values); destroy(&rand_values);\n\t}\n\n\tfclose(fichier);\n\n\tif (argc == 1) //----------------------------------- Test des fonctions simulant une loi de distribution f\n\t{\n\t\tdouble f_distrib_inv[3000], f_distrib_rej[3000];\n\n\t\t// Test de la fonction f_inversion (distribution de f avec la méthode d'inversion)\n\t\tstruct timeval tps1, tps2;\n\t\tgettimeofday(&tps1, NULL);\n\t\tfor (size_t i = 0; i < 3000; ++i)\n\t\t\tf_distrib_inv[i] = f_inversion();\n\t\tgettimeofday(&tps2, NULL);\n\t\tprintf(\"Temps d'execution du calcul de 3000 valeurs de la distribution f (inversion): %ld us\\n\", tps2.tv_usec - tps1.tv_usec);\n\n\t\t// Test de la fonction f_inversion (distribution de f avec la méthode par rejet)\n\t\tstruct timeval tps3, tps4;\n\t\tgettimeofday(&tps3, NULL);\n\t\tfor (size_t i = 0; i < 3000; ++i)\n\t\t\tf_distrib_rej[i] = f_rejet();\n\t\tgettimeofday(&tps4, NULL);\n\t\tprintf(\"Temps d'execution du calcul de 3000 valeurs de la distribution f (rejet): %ld us\\n\", tps4.tv_usec - tps3.tv_usec);\n\t\n\t\t// Ouverture du fichier où l'on vas enregister les distributions de f obtenues\n\t\tFILE* fichier_f = fopen(\"../_distributions_f.csv\", \"w\");\n\t\tif (fichier_f == NULL)\n\t\t\treturn -1;\n\n\t\tfprintf(fichier, \"inversion, rejet\\n\");\n\t\tfor (size_t i = 0; i < 3000; ++i)\n\t\t\tfprintf(fichier, \"%lf, %lf\\n\", f_distrib_inv[i], f_distrib_rej[i]);\n\n\t\tfclose(fichier_f);\n\t}\n\telse if (argc == 2) //----------------------------------- File d'attente MM1\n\t{\n\t\tdouble lambda = 12.0 / 60;\n\t\tfile_attente fa = FileMM1(lambda, 20.0 / 60, 3 * 60);\n\t\tfprint(&fa, \"../_file_mm1.csv\");\n\n\t\t// Calcul de l'évolution de la liste d'attante MM1\n\t\tevolution evol = get_evolution(&fa, 3 * 60);\n\t\tfprint_evol(&evol, \"../_evolution.csv\");\n\n\t\t// Affichage du nombre moyen de client dans le système et du temps moyen de présence\n\t\tdouble E_N = get_number_mean(&evol);\n\t\tdouble E_W = get_time_mean(&fa, &evol);\n\t\tprintf(\"Nombre moyen de clients dans la file : E(N) = %lf clients\\n\", E_N);\n\t\tprintf(\"Temps moyen de présence d'un client dans la file : E(W) = %lf min\\n\", E_W);\n\t\tprintf(\"D'ou, lambda * E(W) = %lf\\n\", lambda * E_W);\n\t}\n\telse if (argc == 3) //-----------------------------------File d'attente MMN\n\t{\n\t\t// Création et enregistrement d'une file M/M/N avec n = 2\n\t\tdouble lambda = 12.0 / 60;\n\t\tfile_attente mm2 = FileMMN(lambda, 20.0 / 60, 3 * 60, 2);\n\t\tfprint(&mm2, \"../_file_mm2.csv\");\n\t}\n\n\treturn 0;\n}\n\n\n//------------------------------------------------------------------------ TEST DE FREQUENCE MONOBIT\n\ndouble Frequency(generator_array* random_values)\n{\n\tint sum = 0;\n\tfor (size_t i = 0; i < size(random_values); ++i)\n\t\tsum += 2 * get_bit(random_values, i) - 1;\n\n\treturn abs(sum) / sqrt(size(random_values));\n}\n\n// Finds the p_value of 'value_count' integers encoded using 'bit_count' bits\ndouble p_value_monobit(generator_array* random_values)\n{\n\treturn erfc(Frequency(random_values) / sqrt(2));\n}\n\n\n//------------------------------------------------------------------------------------ TEST DES RUNS\n\ndouble Runs(generator_array* data)\n{\n\tsize_t n = size(data);\n\n\t// Compte le nombre de '1'\n\tunsigned int one_count = 0;\n\tfor (size_t i = 0; i < size(data); ++i)\n\t\tone_count += get_bit(data, i);\n\tdouble p = one_count / (double)n;\n\n\t// Vérifie si l'on peut arr^ter le test ici\n\tif (fabs(p - 1 / 2.0) >= 2.0 / sqrt(n))\n\t\treturn 0.0;\n\n\t// Calcule Vn(obs)\n\tunsigned int Vobs = 1;\n\tfor (size_t i = 0; i < size(data) - 1; ++i)\n\t\tVobs += ((get_bit(data, i) == get_bit(data, i + 1)) ? 0 : 1);\n\n\t// Retourne la p-valeur du test\n\treturn erfc(fabs(Vobs - 2.0 * one_count*(1 - p)) / (2.0 * sqrt(2.0 * n)*p*(1.0 - p)));\n}\n" }, { "alpha_fraction": 0.7526652216911316, "alphanum_fraction": 0.7867803573608398, "avg_line_length": 51.11111068725586, "blob_id": "a75a64955c6c95c13367358e4097cd27ea4a492b", "content_id": "f2ab783b8a73549df22fb9d29f9883371a40d3b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 476, "license_type": "permissive", "max_line_length": 160, "num_lines": 9, "path": "/TP1_Reseau/README.md", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "TODO: adapter le code pour utiliser les RMI\n\nA rendre: \n\t- javadoc\n\t- document de deux pages max résumant les étapes acomplies\n\t- jeu de tests manuels à préparer pour la démo\n\nVoir http://moodle2.insa-lyon.fr/course/view.php?id=1717 pour les socket multithread et se demander si en fait on est pas obligé de\nsuivre un protocol pourris textuel dont l'explication est donnée sur moodle : http://moodle2.insa-lyon.fr/pluginfile.php/18025/course/section/13927/protocol.pdf\n" }, { "alpha_fraction": 0.5961538553237915, "alphanum_fraction": 0.5976331233978271, "avg_line_length": 28.39130401611328, "blob_id": "8c9626fcd18aa34c234119d020f43f5838f0b346", "content_id": "de76252cb24d1127e95a8d743129e77c27409cc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2034, "license_type": "permissive", "max_line_length": 125, "num_lines": 69, "path": "/TP4_cpp/src/Rectangle.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tRectangle\n\t\t\t\t\t\t\t\t\t---------\n*********************************************************************************/\n\n#ifndef RECTANGLE_H\n#define RECTANGLE_H\n\n#include <string>\n\n#include \"Utils.h\"\n#include \"Command.h\"\n#include \"optional.h\"\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\t//----------------------------------------------------------------------------\n\t//! Structure représentant un rectangle définit à partir de son coin superieur \n\t//! gauche et de son coin inferieur bas. La structure est serialisable grâce à \n\t//! boost::serialization.\n\t//----------------------------------------------------------------------------\n\tstruct Rectangle\n\t{\n\t\tRectangle() = default;\n\t\tRectangle& operator=(const Rectangle&) = delete;\n\n\t\tPoint Get_top_left_corner() const\n\t\t{\n\t\t\treturn top_left_corner;\n\t\t}\n\n\t\tPoint Get_bottom_right_corner() const\n\t\t{\n\t\t\treturn bottom_right_corner;\n\t\t}\n\n\t\t\n\n\tprivate:\n\t\tRectangle(const Point&& top_left_corner, const Point&& bottom_right_corner);\n\n\t\tPoint top_left_corner;\n\t\tPoint bottom_right_corner;\n\n\t\tfriend std::ostream& operator<<(std::ostream &flux, const Rectangle& rect);\n\n\t\tfriend std::experimental::optional<Rectangle> make_rectangle(const Point top_left_corner, const Point bottom_right_corner);\n\t\t\n\t\tfriend Rectangle Move(const Rectangle& shape, coord_t dx, coord_t dy);\n\n\t\tfriend class boost::serialization::access;\n\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\tar & boost::serialization::make_nvp(\"top_left_corner\", top_left_corner)\n\t\t\t\t& boost::serialization::make_nvp(\"bottom_right_corner\", bottom_right_corner);\n\t\t}\n\t};\n\n\tRectangle Move(const Rectangle& shape, coord_t dx, coord_t dy);\n\tbool Is_contained(const Rectangle& shape, Point point);\n\n\tstd::experimental::optional<Rectangle> make_rectangle(const Point top_left_corner, const Point bottom_right_corner);\n}\n\n#endif // !RECTANGLE_H\n" }, { "alpha_fraction": 0.6727772951126099, "alphanum_fraction": 0.6759853363037109, "avg_line_length": 33.09375, "blob_id": "8215eda12aa3c84eb7bf014dc3b6a93415023a7d", "content_id": "b7eb686c023d015a0b7d586419dd5b0687864ad6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2183, "license_type": "permissive", "max_line_length": 129, "num_lines": 64, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/DAL/EventDAL.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.DAL;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport java.util.List;\nimport java.sql.Date;\n\nimport TP1_SI.metier.model.Member;\nimport TP1_SI.metier.model.Event;\n\n/**\n * Data Access Layer permettant d'obtenir, de créer et modifier des instances de la classe 'Event'.\n * Utilise JPA pour persiter les Evenements.\n * @author B3330\n */\npublic class EventDAL {\n\n public void create(Event event) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n em.persist(event);\n }\n\n public Event update(Event event) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.merge(event);\n }\n\n public Event findById(long id) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.find(Event.class, id);\n }\n\n public void AddAdherentToEvent(Event event, Member member) throws Throwable {\n event.getMembers().add(member);\n update(event);\n if (event.getMembers().size() == event.getActivity().getNbParticipants())\n event.setComplet();\n }\n\n public List<Event> findAll() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT a FROM Event a\");\n return (List<Event>)q.getResultList();\n }\n\n public List<Event> findDispo() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT a FROM Event a WHERE a.complet = FALSE\");\n return (List<Event>)q.getResultList();\n }\n\n public List<Event> findByMember(long member_id) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT e FROM Event e INNER JOIN e.members event_member WHERE event_member.id = \" + member_id);\n return (List<Event>)q.getResultList();\n }\n\n public List<Event> findByDate(Date date) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT a FROM Event a WHERE a.date = \" + date);\n return (List<Event>)q.getResultList();\n }\n\n}\n" }, { "alpha_fraction": 0.5511494278907776, "alphanum_fraction": 0.5626437067985535, "avg_line_length": 30.636363983154297, "blob_id": "ce784992822a5aa4badf835859e0303304d1705b", "content_id": "7af95466aa8bd7d8acd01a79c4795ba62261d271", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3485, "license_type": "permissive", "max_line_length": 172, "num_lines": 110, "path": "/TP2_cpp/sources/capteur_event.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/********************************************************************************************\n\t\t\t\t\t\t\t\t\t\tcapteur_event.cpp\n\t\t\t\t\t\t\t\t\t\t-----------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n********************************************************************************************/\n\n//--------------------------------------------------------------------------- Include système\n#include <iostream>\n\n//------------------------------------------------------------------------- Include personnel\n#include \"capteur_event.h\"\n#include \"utils.h\"\n\nnamespace TP2\n{\n\t//------------------------------------------------------------------------- Constructeurs\n\n\tcapteur_event::capteur_event(sensor_t id, sensor_t d7, sensor_t hour, sensor_t min, traffic state)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur de 'capteur_event'\" << endl;\n#endif\n\n\t\tthis->id = id;\n\t\tthis->d7 = d7;\n\t\tthis->hour = hour;\n\t\tthis->min = min;\n\t\tset_traffic(state);\n\t}\n\n\t//-------------------------------------------------------------------- Méthodes publiques\n\n\tvoid capteur_event::set_traffic(traffic state)\n\t{\n\t\tswitch (state)\n\t\t{\n\t\tcase traffic::vert:\n\t\t\ttraff = 0;\n\t\t\treturn;\n\t\tcase traffic::rouge:\n\t\t\ttraff = 1;\n\t\t\treturn;\n\t\tcase traffic::orange:\n\t\t\ttraff = 2;\n\t\t\treturn;\n\t\tcase traffic::noir:\n\t\t\ttraff = 3;\n\t\t\treturn;\n\t\t}\n\t}\n\n\ttraffic capteur_event::get_traffic() const\n\t{\n\t\tswitch (traff)\n\t\t{\n\t\tcase 0:\n\t\t\treturn traffic::vert;\n\t\tcase 1:\n\t\t\treturn traffic::rouge;\n\t\tcase 2:\n\t\t\treturn traffic::orange;\n\t\tcase 3:\n\t\t\treturn traffic::noir;\n\t\t}\n\t\treturn traffic::vert; // impossible\n\t}\n\n\t//--------------------------------------------------------------- Surcharges d'opérateurs\n\n\tvoid swap(capteur_event& lhs, capteur_event& rhs) noexcept\n\t{\n\t\t// if one of the following swap calls isn't noexcept, we raise a static_assert\n// Commenté car is_nothrow_swappable ne fonctionne pas avec gcc installé en IF\n//\t\tstatic_assert(is_nothrow_swappable<uint32_t&>(), \"'Swap(capteur_event&, capteur_event&)' function could throw !\");\n\n\t\t// enable ADL (following lines will use custom implementation of swap or std::swap if there isn't custom implementation)\n\t\tusing std::swap;\n\n\t\tswap(reinterpret_cast<uint32_t&>(lhs), reinterpret_cast<uint32_t&>(rhs));\n\t}\n\n\tbool operator==(const capteur_event& lhs, const capteur_event& rhs) {\n\t\treturn (reinterpret_cast<const uint32_t&>(lhs) & capteur_event::COMPARISION_MASK)\n\t\t\t== (reinterpret_cast<const uint32_t&>(rhs) & capteur_event::COMPARISION_MASK);\n\t}\n\tbool operator!=(const capteur_event& lhs, const capteur_event& rhs) { return !(lhs == rhs); }\n\n\tbool operator<(const capteur_event& lhs, const capteur_event& rhs) {\n\t\treturn (reinterpret_cast<const uint32_t&>(lhs) & capteur_event::COMPARISION_MASK)\n\t\t\t< (reinterpret_cast<const uint32_t&>(rhs) & capteur_event::COMPARISION_MASK);\t// exploite l'ordre des membres de la strucutre 'sensor_event' (et ignore l'attribut traff)\n\t}\n\tbool operator>(const capteur_event& lhs, const capteur_event& rhs) { return rhs < lhs; }\n\tbool operator<=(const capteur_event& lhs, const capteur_event& rhs) { return !(rhs < lhs); }\n\tbool operator>=(const capteur_event& lhs, const capteur_event& rhs) { return !(lhs < rhs); }\n\n\tstd::ostream& operator<<(std::ostream& os, const traffic& state)\n\t{\n\t\tos << static_cast<char>(state);\n\t\treturn os;\n\t}\n\n\tstd::istream& operator>>(std::istream& is, traffic& state)\n\t{\n\t\tauto c = static_cast<char>(traffic::noir);\n\t\tis >> c;\n\t\tstate = static_cast<traffic>(c);\n\t\treturn is;\n\t}\n}\n" }, { "alpha_fraction": 0.6308852434158325, "alphanum_fraction": 0.6339425444602966, "avg_line_length": 44.00917434692383, "blob_id": "05899a4002af7f76c491840dcc292c4ae24b1e25", "content_id": "fc2fff9fc32c3947f8fcd7702d113d43c6417126", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14779, "license_type": "permissive", "max_line_length": 195, "num_lines": 327, "path": "/TP3_cpp/includes/Typed_main_binding.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\tTyped_main_binding - An helper class for main args\n\t\t\t\t\t---------------------------------------------------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//---------- Interface de la classe template Typed_main_binding<Args...> ---------\n#ifndef TYPED_MAIN_BINDING_H\n#define TYPED_MAIN_BINDING_H\n\n//-------------------------------------------------------------- Includes systèmes\n#include <vector>\n#include <utility>\n#include \"optional.h\"\n#include <type_traits>\n\n//------------------------------------------------------------ Includes personnels\n#include \"Utils.h\"\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//-------------------------------------------------------------- Metafonctions\n\n\t//! Alias simplifiant la spécification du type de retour des méthodes 'get_option_tags()'\n\t//! @remarks\n\t//!\t\tLes seules contraintes concernant le concept de 'option_with_tags' est que le type\n\t//!\t\tde retour de 'get_option_tags()' soit itérable et contienne des valeurs implicitement \n\t//!\t\tconvertibles en 'std::string' (pas nescessairement statique ou de type tags_t<N>)\n\ttemplate<size_t N>\n\tusing tags_t = std::array<std::string, N>;\n\n\t//! Spécialisation d'une metafonction aidant à verifier si un type T n'est pas conforme\n\t//! au concept de 'option_with_tags'\n\ttemplate<typename T, typename = void>\n\tstruct has_option_tag_getter : std::false_type { };\n\n\t//! Spécialisation d'une metafonction aidant à verifier si un type T est conforme au\n\t//! concept de 'option_with_tags' (verifie seulement la présence de la méthode statique)\n\ttemplate<typename T>\n\tstruct has_option_tag_getter<T, decltype(std::declval<T>().get_option_tags(), void())> : std::true_type { };\n\n\t//! Spécialisation d'une metafonction aidant à verifier si un type T n'est pas conforme\n\t//! au concept de 'option_with_value'\n\ttemplate<typename T, typename = void>\n\tstruct option_has_value : std::false_type { };\n\n\t//! Spécialisation d'une metafonction aidant à verifier si un type T est conforme au\n\t//! concept de 'option_with_value'\n\ttemplate<typename T>\n\tstruct option_has_value<T, decltype(std::declval<T>().value, void())> : std::true_type { };\n\n\t// TODO: verifier que T n'est pas tags_t<0> :\n/*\ttemplate<typename T>\n\tconstexpr bool has_option_tag()\n\t{ return has_option_tag_getter<T>::value && std::is_same<decltype(std::declval<T>().get_option_tags()), tags_t<0>>::value; }*/\n\n\t//---------------------------------------------------------------------- Types\n\n\t//! Classe template permettant de simplifier l'interprétation de argv et argc.\n\t//! A partir d'une fonction dont la signature est du type 'typed_main_t<Args...>'\n\t//! (avec les types Args validants les concepts décrits ci dessous), la classe\n\t//! template en déduit statiquement la forme des commandes acceptables et gère\n\t//! automatiquement toutes les vérifications et conversions nécessaires au runtime\n\t//! pour pouvoir appeler, si possible, le main typé spécifié (avec les paramètres\n\t//! optionnels correspondants à la commande).\n\t//! @remarks\n\t//!\t\tLes arguments templates 'Args' doivent être conformes aux concepts de :\n\t//!\t\t- 'option_with_tags' et 'option_with_value' : option ayant un ou des tags\n\t//!\t\t\tet un paramètre (e.g. \"-t 21\")\n\t//!\t\t- ou 'option_with_tags' : option sans paramètre avec un tag (e.g. \"-e\")\n\t//!\t\t- ou 'option_with_value' : option sans tags et ayant un paramètre.\n\t//!\t\t\tCe type d'option est en fait obligatoire : il determine la forme de la\n\t//!\t\t\tcommande car toute les options de (Args...) avant celle-ci doivent être\n\t//!\t\t\tégalement avant dans argv (de même pour les options après une option sans tag)\n\t//! @remarks\n\t//!\t\t- Description du concept 'option_with_value' : Le type T doit contenir un attribut\n\t//!\t\t\tpublique 'value' tel que son type soit pourvus d'une surcharge de 'T TP3::parse<T>(std::string)'\n\t//!\t\t- Description du concept 'option_with_tags' : Le type T doit contenir une méthode\n\t//!\t\t\tpublique et statique 'get_option_tags()' retournant un objet itérable contenant\n\t//!\t\t\tdes valeurs implicitment convertibles en 'std::string'.\n\t// TODO: support default values\n\t// TODO: allow multiple typed_main implementation for alternative command usages\n\ttemplate<typename... Args>\n\tclass Typed_main_binding\n\t{\n\t\t//----------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//----------------------------------------------- Types et alias publiques\n\t\tusing typed_main_t = std::function<void(std::experimental::optional<Args>...)>;\n\n\t\t//----------------------------------------------------- Méthodes publiques\n\n\t\t//! Execute, si possible, le main typé en construisant les paramètres optionels \n\t\t//! du main typé à partir de argv et argc.\n\t\t//! @throw std::invalid_argument\n\t\t//! @throw std::out_of_range\n\t\tvoid exec(int argc, char* argv[]);\n\n\t\t//----------------------------------------------------- Méthodes spéciales\n\n\t\t//! Constructeur prenant en paramètre le main typé qui sera executé\n\t\texplicit Typed_main_binding(const typed_main_t& typed_main);\n\n\t\t//------------------------------------------------------------------ PRIVE\n\tprivate:\n\t\t//------------------------------------------------------- Méthodes privées\n\n\t\t//! spécialisation template utilisant SFINAE pour cibler les options ayant\n\t\t//! seulement un tag (validant le concept de 'option_with_tags')\n\t\ttemplate<typename T, typename = typename std::enable_if<!option_has_value<T>::value && has_option_tag_getter<T>::value>::type>\n\t\t// C++14: template<typename T, typename = typename std::enable_if_t<!option_has_value<T>::value && has_option_tag_getter<T>::value>>\n\t\tstd::experimental::optional<T> get_opt(int argc, char* argv[]);\n\n\t\t//! spécialisation template utilisant SFINAE pour cibler les options ayant\n\t\t//! un parametre (validant les concepts de 'option_with_tags' et 'option_with_value')\n\t\ttemplate<typename T, typename = typename std::enable_if<option_has_value<T>::value && has_option_tag_getter<T>::value>::type, typename = void>\n\t\tstd::experimental::optional<T> get_opt(int argc, char* argv[]);\n\n\t\t//! spécialisation template utilisant SFINAE pour cibler les options ne \n\t\t//! disposant pas de tags (validant le concept de 'option_with_value')\n\t\ttemplate<typename T, typename = typename std::enable_if<option_has_value<T>::value && !has_option_tag_getter<T>::value>::type, typename = void, typename = void>\n\t\tstd::experimental::optional<T> get_opt(int argc, char* argv[]);\n\n\t\t// TODO: ajouter une spécialisation de get_opt pour gérer les paramètres multiples pour une même option\n\n\t\t//------------------------------------------------------- Attributs privés\n\n\t\ttyped_main_t m_typed_main_func;\n\t\tstd::vector<std::pair<size_t, int>> m_found_parameters;\n\n\t\t//---------------------------------------------------- Fonctions statiques\n\n\t\t//! Fonction permettant la construction d'un tableau des tags de tout les types Args...\n\t\ttemplate<typename T, typename = typename std::enable_if<has_option_tag_getter<T>::value>::type>\n\t\tstatic std::vector<std::string> get_option_tags();\n\n\t\t//! Fonction permettant la construction d'un tableau des tags de tout les types Args...\n\t\ttemplate<typename T, typename = typename std::enable_if<!has_option_tag_getter<T>::value>::type, typename = void>\n\t\tstatic std::vector<std::string> get_option_tags();\n\t};\n\n\t//--------------------------------------------------------- Fonctions globales\n\n\t//! Fonction créant un objet de type 'Typed_main_binding<Args...>' à partir d'un pointeur de fonction vers un main typé\n\t//! @remarks This function permits implicit template deduction by taking C-style function pointer instead of std::function<...>\n\ttemplate<typename... Args>\n\tTyped_main_binding<Args...> make_typed_main_binding(void(*typed_main)(std::experimental::optional<Args>...) )\n\t{\n\t\treturn Typed_main_binding<Args...>(std::function<void(std::experimental::optional<Args>...)> (typed_main));\n\t}\n\n\t//----- Implémentation de la classe template Typed_main_binding<Args...> -----\n\n\ttemplate<typename... Args>\n\tTyped_main_binding<Args...>::Typed_main_binding(const typed_main_t& typed_main)\n\t\t: m_typed_main_func(typed_main) { }\n\t\n\ttemplate<typename... Args>\n\tvoid Typed_main_binding<Args...>::exec(int argc, char* argv[])\n\t{\n\t\tif (argc > 0 && argv != nullptr)\n\t\t{\n\t\t\tint arg_processed_cout = 1;\n\n\t\t\t// Store an array of booleans indicating Args...'s option type (tag presence and value presence)\n\t\t\tstd::array<std::pair<bool, bool>, sizeof...(Args)> options_types_info = decltype(options_types_info){ { std::make_pair(has_option_tag_getter<Args>::value, option_has_value<Args>::value)... }};\n\t\t\t// C++14: std::array<std::pair<bool, bool>, sizeof...(Args)> options_types_info = { std::make_pair(has_option_tag_getter<Args>::value, option_has_value<Args>::value)... };\n\t\t\t// Store an array of options tags\n\t\t\tstd::array<std::vector<std::string>, sizeof...(Args)> options_tags = decltype(options_tags){ { get_option_tags<Args>()... }};\n\t\t\t// C++14: std::array<std::vector<std::string>, sizeof...(Args)> options_tags = { get_option_tags<Args>()... }; \n\n\t\t\t// Find presence of options with tags in argv\n\t\t\tint previous_found_option_param_count = 0;\n\t\t\tint previous_found_option_idx = 0;\n\t\t\tstd::array<bool, sizeof...(Args)> processed_template_arg_indices;\n\t\t\tprocessed_template_arg_indices.fill(false);\n\t\t\tfor (auto arg_idx = 1; arg_idx < argc; ++arg_idx)\n\t\t\t{\n\t\t\t\tstd::string cmd_str(argv[arg_idx]);\n\t\t\t\tbool found = false;\n\n\t\t\t\tfor (size_t T_idx = 0; T_idx < sizeof...(Args) && !found; ++T_idx)\n\t\t\t\t{\n\t\t\t\t\tauto type_info = options_types_info[T_idx];\n\t\t\t\t\tif(type_info.first) // if T has option tag getter (ignore mandatory/tagless parameters for now)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto T_tags = options_tags[T_idx];\n\t\t\t\t\t\tif (T_tags.size() == 0)\n\t\t\t\t\t\t\tthrow std::invalid_argument(\"Option with tags don't have any tag\");\n\t\t\t\t\t\tfor (const auto& tag : T_tags)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (tag == cmd_str)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(arg_idx <= previous_found_option_param_count + previous_found_option_idx)\n\t\t\t\t\t\t\t\t\tthrow std::invalid_argument(\"No parameter after an option tag which need one\");\n\t\t\t\t\t\t\t\tprevious_found_option_param_count = type_info.second ? 1 : 0; // if T has option parameter/value\n\t\t\t\t\t\t\t\targ_processed_cout += 1 + previous_found_option_param_count;\n\t\t\t\t\t\t\t\tif (processed_template_arg_indices[T_idx])\n\t\t\t\t\t\t\t\t\t// (TODO: allow it) Don't allow multiple option usage for simplicity reasons\n\t\t\t\t\t\t\t\t\tthrow std::invalid_argument(\"Multiple tag for the same option\");\n\t\t\t\t\t\t\t\tm_found_parameters.emplace_back(T_idx, arg_idx);\n\t\t\t\t\t\t\t\tprocessed_template_arg_indices[T_idx] = true;\n\t\t\t\t\t\t\t\tprevious_found_option_idx = arg_idx;\n\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check mandatory/tagless parameters presence\n\t\t\tstd::vector<std::pair<size_t, size_t>> found_tagless_options;\n\t\t\tfor (size_t T_idx = 0; T_idx < sizeof...(Args); ++T_idx)\n\t\t\t{\n\t\t\t\tauto type_info = options_types_info[T_idx];\n\t\t\t\tif (!type_info.first) // if T has option tag getter\n\t\t\t\t{\n\t\t\t\t\tint idx = 1;\n\t\t\t\t\tbool reached_later_option = false;\n\t\t\t\t\tfor(const auto& p : m_found_parameters)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (reached_later_option && p.second == idx)\n\t\t\t\t\t\t\t// mandatory/tagless parameter index is actually used by an option with a tag\n\t\t\t\t\t\t\tthrow std::invalid_argument(\"Missing mandatory tagless option\");\n\n\t\t\t\t\t\tif(p.first < T_idx)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (reached_later_option)\n\t\t\t\t\t\t\t\tthrow std::invalid_argument(\"Invalid command shape (options order imposed by tagless option(s) not respected)\");\n\t\t\t\t\t\t\tidx = p.second + type_info.second ? 2 : 1; // if T has option parameter/value\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(p.first > T_idx && !reached_later_option)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (p.second == idx)\n\t\t\t\t\t\t\t\tthrow std::invalid_argument(\"Missing mandatory tagless option or invalid command shape\");\n\t\t\t\t\t\t\treached_later_option = true;\n\t\t\t\t\t\t\tfound_tagless_options.emplace_back(T_idx, idx);\n\t\t\t\t\t\t\targ_processed_cout++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(!reached_later_option && idx < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_tagless_options.emplace_back(T_idx, idx);\n\t\t\t\t\t\targ_processed_cout++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(arg_processed_cout < argc)\n\t\t\t\tthrow std::invalid_argument(\"Invalid options\");\n\n\t\t\tm_found_parameters.insert(std::end(m_found_parameters), std::begin(found_tagless_options), std::end(found_tagless_options));\n\n\t\t\t// We have verified command shape and found all options/parameters of the command, we can now parse parameters and call typed main:\n\t\t\tm_typed_main_func((get_opt<Args>(argc, argv))...);\n\t\t}\n\t}\n\n\ttemplate<typename... Args>\n\ttemplate<typename T, typename>\n\tstd::experimental::optional<T> Typed_main_binding<Args...>::get_opt(int argc, char* argv[])\n\t{\n\t\tconstexpr auto opt_template_idx = index_of<T, Args...>();\n\n\t\tfor (const auto& p : m_found_parameters)\n\t\t{\n\t\t\tif(p.first == opt_template_idx)\n\t\t\t\treturn std::experimental::optional<T>(T());\n\t\t}\n\t\treturn std::experimental::nullopt;\n\t}\n\n\ttemplate<typename... Args>\n\ttemplate<typename T, typename, typename>\n\tstd::experimental::optional<T> Typed_main_binding<Args...>::get_opt(int argc, char* argv[])\n\t{\n\t\tconstexpr auto opt_template_idx = index_of<T, Args...>();\n\n\t\tfor (const auto& p : m_found_parameters)\n\t\t{\n\t\t\tif (p.first == opt_template_idx)\n\t\t\t{\n\t\t\t\tT param;\n\t\t\t\tif (p.second+1 >= argc)\n\t\t\t\t\tthrow std::invalid_argument(\"No parameter after an option tag which need one\");\n\t\t\t\tparam.value = parse<decltype(param.value), true>(argv[p.second+1]);\n\t\t\t\treturn std::experimental::optional<T>(param);\n\t\t\t}\n\t\t}\n\t\treturn std::experimental::nullopt;\n\t}\n\n\ttemplate<typename... Args>\n\ttemplate<typename T, typename, typename, typename>\n\tstd::experimental::optional<T> Typed_main_binding<Args...>::get_opt(int argc, char* argv[])\n\t{\n\t\tconstexpr auto opt_template_idx = index_of<T, Args...>();\n\n\t\tfor (const auto& p : m_found_parameters)\n\t\t{\n\t\t\tif (p.first == opt_template_idx)\n\t\t\t{\n\t\t\t\tT tagless_option_param;\n\t\t\t\ttagless_option_param.value = parse<decltype(tagless_option_param.value), true>(argv[p.second]);\n\t\t\t\treturn std::experimental::optional<T>(tagless_option_param);\n\t\t\t}\n\t\t}\n\t\t// This kind of option is actually mandatory\n\t\tthrow std::invalid_argument(\"Missing tagless mandatory parameter\");\n\t}\n\n\ttemplate<typename ... Args>\n\ttemplate<typename T, typename>\n\tstd::vector<std::string> Typed_main_binding<Args...>::get_option_tags() {\n\t\tconst auto& tags_array = T::get_option_tags();\n\t\treturn std::vector<std::string>(std::begin(tags_array), std::end(tags_array));\n\t}\n\n\ttemplate<typename ... Args>\n\ttemplate<typename T, typename, typename>\n\tstd::vector<std::string> Typed_main_binding<Args...>::get_option_tags() { return std::vector<std::string>(0); }\n}\n\n#endif\n\n" }, { "alpha_fraction": 0.6823529601097107, "alphanum_fraction": 0.6901960968971252, "avg_line_length": 30.875, "blob_id": "3406715064245516d21568c25770e9e19b00e484", "content_id": "118e4e26a8544fa6f4086c3501fe963da01bbbeb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 255, "license_type": "permissive", "max_line_length": 47, "num_lines": 8, "path": "/TP1_cpp/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "CPP_FLAGS = -Wall -std=c++11\n\nEXE: collection.o main.o\n\tg++ collection.o main.o -o EXE\nmain.o: main.cpp dog.h collection.h tests.h\n\tg++ $(CPP_FLAGS) -c main.cpp -o main.o\ncollection.o: collection.cpp collection.h dog.h\n\tg++ $(CPP_FLAGS) -c collection.cpp\n" }, { "alpha_fraction": 0.3176848888397217, "alphanum_fraction": 0.3286173641681671, "avg_line_length": 35.16279220581055, "blob_id": "54a3aaf291708f8f8bf150e3a81c830321d9fec2", "content_id": "8eb70595d62a7aba7307d3281c5413ef33ab8bc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1556, "license_type": "permissive", "max_line_length": 108, "num_lines": 43, "path": "/TP1_cpp_gcc/includes/dog.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\tdog - dummy dog structure\n\t\t\t\t\t\t\t---------------------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n#ifndef DOG_H\n#define DOG_H\n\nnamespace TP1\n{\n\t//----------------------------------------------------------------------------\n\t// color: Enumèration de quelques couleurs\n\t//----------------------------------------------------------------------------\n\tenum class color { RED, GREEN, BLUE, YELLOW, BROWN };\n\n\t//----------------------------------------------------------------------------\n\t// dog: structure simple representant un chien\n\t//----------------------------------------------------------------------------\n\tstruct dog\n\t{\n\t\t//----------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//-------------------------------------------- Constructeurs - destructeur\n\n\t\tdog() = default;\n\t\texplicit dog(unsigned int age) : age(age) { }\n\t\tdog(color c, unsigned int age) : col(c), age(age) { }\n\n\t\t//------------------------------------------------------ Membres publiques\n\n\t\tcolor col = TP1::color::BLUE;\n\t\tunsigned int age = 2;\n\t};\n\n\t//------------------------------------------------------- OPERATOR OVERLOADING\n\n\tinline bool operator==(const dog& lhs, const dog& rhs) { return lhs.age == rhs.age && lhs.col == rhs.col; }\n\tinline bool operator!=(const dog& lhs, const dog& rhs) { return !(lhs == rhs); }\n}\n\n#endif // DOG_H\n" }, { "alpha_fraction": 0.7010869383811951, "alphanum_fraction": 0.7010869383811951, "avg_line_length": 17.399999618530273, "blob_id": "03fa40414f9b415629c651d8dc9c1941f3bee6ab", "content_id": "be9097dcf4d5550a3ec33dc5a1cf276614bb6757", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 184, "license_type": "permissive", "max_line_length": 46, "num_lines": 10, "path": "/TP2_Archi/lcd.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef LCD_H\n#define LCD_H\n\n\tvoid lcd_init();\n\tvoid lcd_clear();\n\tvoid lcd_fill();\n\tvoid lcd_display_digit(int pos, int digit);\n\tvoid lcd_display_number(unsigned int number);\n\n#endif\n" }, { "alpha_fraction": 0.600509762763977, "alphanum_fraction": 0.6086661219596863, "avg_line_length": 36.24683380126953, "blob_id": "a91a89cdc3f717a9f51d8bb0ad18d3f28c8ec501", "content_id": "2d3d12620cce856053792aa52022dec5a0876899", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5911, "license_type": "permissive", "max_line_length": 163, "num_lines": 158, "path": "/TP1_Concurrency/source/gestionSortie.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tGestion sortie - tache gerant les barrieres de sortie\n\t\t\t-----------------------------------------------------\n\tdebut \t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//- Realisaion de la tache <GESTION_SORTIE> (fichier gestionSortie.cpp) --\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//-------------------------------------------------------- Include système\n#include <unordered_map>\n#include <sys/wait.h>\n#include <sys/sem.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <utility>\n#include <string>\n#include <ctime>\n\n//------------------------------------------------------ Include personnel\n#include \"gestionSortie.h\"\n#include \"gestionEntree.h\"\n#include \"process_utils.h\"\n#include \"clavier.h\"\n\n/////////////////////////////////////////////////////////////////// PRIVE\nnamespace\n{\n\t//------------------------------------------------ Variables statiques\n\t//! On utilise des variables statiques plutot que automatiques pour qu'elles\n\t//! soient accessibles depuis les handlers de signaux car ce sont des lambdas \n\t//! qui ne peuvent rien capturer de leur contexte pour qu'elles puissent être \n\t//! castés en pointeur de fonction C.\n\tipc_id_t car_message_queue_id;\n\tipc_id_t sem_id;\n\tshared_mem<parking> parking_state;\n\tshared_mem<waiting_cars> waiting;\n\tshared_mem<places> parking_places;\n\tstd::unordered_map<pid_t, car_info> car_exiting_tasks;\n\n\t//-------------------------------------------------- Fonctions privées\n\t//! Termine la tache Gestion sortie\n\tvoid quit_sortie()\n\t{\n\t\t// On retire les handlers des signaux SIGCHLD et SIGUSR2\n\t\tunsubscribe_handler<SIGCHLD, SIGUSR2>();\n\n\t\t// Termine toutes les taches filles de sortie de voiture\n\t\tfor (const auto& task : car_exiting_tasks) {\n\t\t\tif (task.first > 0)\n\t\t\t{\n\t\t\t\tkill(task.first, SIGUSR2);\n\t\t\t\twaitpid(task.first, nullptr, 0);\n\t\t\t}\n\t\t}\n\n\t\t// Detache les memoires partagées\n\t\tdetach_shared_memory(parking_state.data);\n\t\tdetach_shared_memory(waiting.data);\n\t\tdetach_shared_memory(parking_places.data);\n\n\t\t// On notifie la tache mère de la fin pour qu'elle quitte les autres taches\n\t\tkill(getppid(), SIGCHLD);\n\n\t\texit(EXIT_SUCCESS);\n\t}\n}\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//----------------------------------------------------- Fonctions publique\n\npid_t ActiverPorteSortie()\n{\n\t// Creation du processus fils\n\treturn fork([]()\n\t{\n\t\t// Fonction lambda aidant a quitter en cas d'erreur\n\t\tauto quit_if_failed = [](bool condition)\n\t\t{\n\t\t\tif (!condition)\n\t\t\t\tquit_sortie();\n\t\t};\n\n\t\t// On ajoute un handler pour le signal SIGUSR2 indiquant que la tache doit se terminer\n\t\tquit_if_failed(handle<SIGUSR2>([](signal_t sig) { quit_sortie(); }));\n\n\t\t// Ouverture de la message queue utilisée pour recevoir les demandes de sortie\n\t\tquit_if_failed(open_message_queue(car_message_queue_id, 2));\n\n\t\t// Récuperation des semaphores\n\t\tsem_id = semget(ftok(\".\", 3), 4U, 0600);\n\t\tquit_if_failed(sem_id != -1);\n\n\t\t// Ouvre les memoires partagées\n\t\tparking_state = get_shared_memory<parking>(4);\n\t\tquit_if_failed(parking_state.data != nullptr);\n\t\twaiting = get_shared_memory<waiting_cars>(5);\n\t\tquit_if_failed(waiting.data != nullptr);\n\t\tparking_places = get_shared_memory<places>(6);\n\t\tquit_if_failed(parking_places.data != nullptr);\n\n\t\t// On ajoute un handler pour le signal SIGCHLD indiquant qu'une voiture est sortie\n\t\tquit_if_failed(handle<SIGCHLD>([](signal_t sig)\n\t\t{\n\t\t\t// On affiche les information de sortie, on efface les informations de la place et on met à jour la memoire partagée\n\t\t\tint status;\n\t\t\tpid_t chld = waitpid(-1, &status, WNOHANG);\n\t\t\tif (chld > 0 && WIFEXITED(status))\n\t\t\t{\n\t\t\t\tauto car = car_exiting_tasks[chld];\n\t\t\t\tauto place_num = WEXITSTATUS(status);\n\n\t\t\t\trequest req_prof, req_gb, req_autre;\n\t\t\t\tlock(sem_id, 0, [&car, place_num, &req_prof, &req_gb, &req_autre]() {\n\t\t\t\t\t// Met a jour le nombre de voitures dans le parking\n\t\t\t\t\tif (parking_state.data->car_count > 0)\n\t\t\t\t\t\tparking_state.data->car_count--;\n\n\t\t\t\t\treq_prof = waiting.data->waiting_fences[PROF_BLAISE_PASCAL - 1];\n\t\t\t\t\treq_gb = waiting.data->waiting_fences[ENTREE_GASTON_BERGER - 1];\n\t\t\t\t\treq_autre = waiting.data->waiting_fences[AUTRE_BLAISE_PASCAL - 1];\n\t\t\t\t});\n\n\t\t\t\t// Laisse entrer une voiture attendant à une barrière en prenant en compte les priorités\n\t\t\t\tif (req_prof.type != AUCUN && !(req_gb.type == PROF && req_gb.heure_requete < req_prof.heure_requete))\n\t\t\t\t\tsem_pv(sem_id, PROF_BLAISE_PASCAL, 1); // Ont débloque la barrière PROF_BLAISE_PASCAL\n\t\t\t\telse if (req_gb.type != AUCUN && (req_gb.type == PROF || !(req_autre.type != AUCUN && req_gb.type == AUTRE && req_autre.heure_requete < req_gb.heure_requete)))\n\t\t\t\t\tsem_pv(sem_id, ENTREE_GASTON_BERGER, 1); // Ont débloque la barrière ENTREE_GASTON_BERGER\n\t\t\t\telse if (req_autre.type != AUCUN)\n\t\t\t\t\tsem_pv(sem_id, AUTRE_BLAISE_PASCAL, 1); // Ont débloque la barrière AUTRE_BLAISE_PASCAL\n\n\t\t\t\tcar_exiting_tasks.erase(chld);\n\t\t\t\tEffacer(static_cast<TypeZone>(ETAT_P1 + place_num - 1));\n\t\t\t\tAfficherSortie((TypeUsager)car.user_type, car.car_number, car.heure_arrivee, time(nullptr));\n\t\t\t}\n\t\t}));\n\n\t\t// Phase moteur\n\t\twhile (true)\n\t\t{\n\t\t\t// On attend la reception d'un message issu de la tache clavier\n\t\t\tcar_exit_msg message;\n\t\t\tquit_if_failed(read_message(car_message_queue_id, 0, message));\n\n\t\t\t// On recupère les informations a la place spécifiée dans la memoire partagée\n\t\t\tcar_info car;\n\t\t\tquit_if_failed(lock(sem_id, 0, [&car, &message]() {\n\t\t\t\tcar = parking_places.data->places[message.place_num - 1];\n\t\t\t\tparking_places.data->places[message.place_num - 1] = { 0, AUCUN, 0 };\n\t\t\t}));\n\n\t\t\t// On sort la voiture si une voiture occupe la place spécifiée\n\t\t\tpid_t child_pid = SortirVoiture(message.place_num);\n\t\t\tcar_exiting_tasks.emplace(child_pid, car);\n\t\t}\n\t});\n}\n" }, { "alpha_fraction": 0.7064343094825745, "alphanum_fraction": 0.7064343094825745, "avg_line_length": 47.129032135009766, "blob_id": "d996b4f76067c39c9b4d916525351eaf7a84c65e", "content_id": "e1be2b257fcfbe83676e8323f7d4bf66b3643d15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1512, "license_type": "permissive", "max_line_length": 103, "num_lines": 31, "path": "/TP3_cpp/Tests/readme.txt", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "Programme de tests automatiques - mode d'emploi\n\n-------------------------------------------------------------------------------\ntest.sh [ repertoire [ fichier.csv ] ]\n\n- repertoire indique le répertoire dans lequel se trouvent les fichiers de \nconfiguration du test\n- fichier.csv indique un fichier dans lequel les résultats du tests seront \najoutés\n\nEn l'absence d'arguments, le script traitera le répertoire courant\n\nFichiers de configuration :\n- run : fichier texte indiquant la ligne de commande à éxécuter (obligatoire)\n- std.in : fichier texte indiquant une entrée clavier à simuler (facultatif)\n- std.out : fichier texte indiquant la sortie devant être produite (facultatif/validation*)\n- stderr.out : fichier texte indiquant la sortie d'erreur devant être produite (facultatif/validation*)\n- description : fichier texte donnant la description du test (facultatif)\n- returncode : fichier texte contenant l'entier code retour attendu (facultatif/validation*)\n- *.outfile : un ou plusieurs fichiers devant être produits par le programme (facultatif/validation*)\n si le fichier s'appelle exemple.txt.outfile, il sera comparé à exemple.txt\n\n*validation indique que le script va tester la conformité, si cette conformité \nn'est pas \nsatisfaite, il l'indiquera\n\n-------------------------------------------------------------------------------\nmktest.sh\n\nFichier à personnaliser. Dans l'état, il cherche à valider tous les tests \ncontenus dans les répertoires dont le nom commence par Test.\n" }, { "alpha_fraction": 0.4736512005329132, "alphanum_fraction": 0.485361784696579, "avg_line_length": 46.83000183105469, "blob_id": "24aaf6998b08b170c92e6908d5c05197949d80b2", "content_id": "ad7dcf8a23b7e7b471c0c5f804bcf56cdee99588", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4816, "license_type": "permissive", "max_line_length": 118, "num_lines": 100, "path": "/TP2_cpp/includes/capteur_event.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/***************************************************************************************\n\t\t\t\t\tcapteur_event - A sensor event structure\n\t\t\t\t\t------------------------------------------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n***************************************************************************************/\n\n//-------------------- Interface de la structure capteur_event -------------------------\n#pragma once\n\n//------------------------------------------------------------------ Includes personnels\n#include \"utils.h\"\n\nnamespace TP2\n{\n\t//----------------------------------------------------------------------------------\n\t/// <summary> Enumération typée représenatant un niveau de traffic </summary>\n\t//----------------------------------------------------------------------------------\n\tenum class traffic : char { vert = 'V', rouge = 'J', orange = 'R', noir = 'N' };\n\n\t//----------------------------------------------------------------------------------\n\t/// <summary> Structure représentant un évémenement 'ADD' (id, timestamp et traffic)\n\t///\t\tC'est une structure dont la taille est de 32 bits ce qui permet d'en stocker un grand\n\t///\t\tnombre en mémoire et faire des opérations de comparaison et copie plus rapide </summary> \n\t//----------------------------------------------------------------------------------\n\tstruct capteur_event\n\t{\n\t\t//----------------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//----------------------------------------------------------------------- Usings\n\t\tusing sensor_t = uint32_t; // alignement sur 32 bits\n\n\t\t//---------------------------------------------------------------- Constructeurs\n\t\t/// <summary> Constructeur de la structure 'capteur_event' </summary>\n\t\t///\t<param name='id'> Identifiant du capteur ayant produit cet évenement </param>\n\t\t///\t<param name='d7'> Jour de la semaine </param>\n\t\t///\t<param name='hour'> Heure de l'événement </param>\n\t\t///\t<param name='min'> Minute de l'événement </param>\n\t\t///\t<param name='state'> Etat du capteur (traffique) </param>\n\t\tcapteur_event(sensor_t id = 0, sensor_t d7 = 1, sensor_t hour = 0, sensor_t min = 0, traffic state = traffic::vert);\n\n\t\t//-------------------------------------------------------------------- Attributs\n\n\t\t/// Identifiant du capteur ayant produit cet évenement\n\t\tsensor_t id : 16;\t\t// (0 - 65536)\n\t\t/// Jour de la semaine\n\t\tsensor_t d7 : 3;\t\t// (0 - 7)\n\t\t/// Heure de l'événement \n\t\tsensor_t hour : 5;\t\t// (0 - 31)\n\t\t/// Minute de l'événement\n\t\tsensor_t min : 6;\t\t// (0 - 63)\n\t\t//------------------------------------------------------------------------ PRIVE\n\tprivate:\n\t\t/// Etat du capteur (traffique)\n\t\tsensor_t traff : 2;\t\t// (0 - 3)\t// private car il faut préfèrer la représentation typée d'un traffic (enum class)\n\n\t\t//----------------------------------------------------------- Méthodes publiques\n\n\t\t//----------------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\tvoid set_traffic(traffic state);\n\t\ttraffic get_traffic() const;\n\n\t\t//--------------------------------------------------------- Constantes statiques\n\n\t\t/// Nombre de valeurs différentes dans l'énumération 'traffic'\n\t\tstatic const size_t TRAFFIC_CARDINALITY = 4;\n\n\t\t//------------------------------------------------------------------------ PRIVE\n\tprivate:\n\t\t/// Masque permettant d'ignorer l'attribut traff lors de la comparaison d'objets 'capteur_event'\n\t\tstatic const sensor_t COMPARISION_MASK = 0xFFFFFFFC; // enlève les deux dernier bits\n\n\t\t//------------------------------------------------------ Surcharges d'opérateurs\n\n\t\tfriend void swap(capteur_event& lhs, capteur_event& rhs) noexcept;\n\n\t\tfriend bool operator==(const capteur_event& lhs, const capteur_event& rhs);\n\t\tfriend bool operator!=(const capteur_event& lhs, const capteur_event& rhs);\n\n\t\tfriend bool operator<(const capteur_event& lhs, const capteur_event& rhs);\n\t\tfriend bool operator>(const capteur_event& lhs, const capteur_event& rhs);\n\t\tfriend bool operator<=(const capteur_event& lhs, const capteur_event& rhs);\n\t\tfriend bool operator>=(const capteur_event& lhs, const capteur_event& rhs);\n\n\t\t// Permet à 'capteur_stat' d'accèder à 'traff' plus rappidement\n\t\tfriend struct capteur_stat;\n\t};\n\n\t// On s'assure que la structure fait bien 32 bits\n\tstatic_assert(sizeof(capteur_event) == 4, \"La structure 'capteur_event' doit avoir une taille de 4 octets.\");\n\n\t//---------------------------------------------------------- Surcharges d'opérateurs\n\n\t/// <summary> Surcharge de l'opérateur ostream pour le type traffic </summary>\n\tstd::ostream& operator<<(std::ostream& os, const traffic& state);\n\n\t/// <summary> Surcharge de l'opérateur istream pour le type traffic </summary>\n\tstd::istream& operator>>(std::istream& is, traffic& state);\n}" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7317784428596497, "avg_line_length": 21.933332443237305, "blob_id": "4de3f55d3b949a4dcbd9a71c8341bd06821c2502", "content_id": "a8865fbf1513e97316261b87ed430809ae738bb3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 343, "license_type": "permissive", "max_line_length": 64, "num_lines": 15, "path": "/TP1_BDDI/fragment victoire - pes/trigger_stock_produit.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "CREATE OR REPLACE TRIGGER FK_STOCK_PRODUIT \nBEFORE INSERT OR UPDATE ON Stock_Amerique \nFOR EACH ROW\nDECLARE\n isReferenced NUMBER;\nBEGIN\n SELECT COUNT(*) INTO isReferenced\n FROM Produits\n WHERE REF_PRODUIT = :NEW.REF_PRODUIT;\n \n if(isReferenced = 0)\n THEN\n RAISE_APPLICATION_ERROR(-20003, 'REF_PRODUIT inexistant !');\n END IF;\nEND;" }, { "alpha_fraction": 0.6644838452339172, "alphanum_fraction": 0.6673086881637573, "avg_line_length": 33.92376708984375, "blob_id": "52436e9d3f144a4bac2fbcd75c2a7d63c3d94cec", "content_id": "a973a9897b1d0c2835b783b58ff1dffa887476f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7827, "license_type": "permissive", "max_line_length": 194, "num_lines": 223, "path": "/TP4_cpp/src/Serializable_shape_history.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tHistory\n\t\t\t\t\t\t\t\t\t-------\n*********************************************************************************/\n\n#ifndef HISTORY_H\n#define HISTORY_H\n\n#include <unordered_map>\n#include <ostream>\n#include <boost/smart_ptr/shared_ptr.hpp> //#include <memory>\n#include <vector>\n\n#include <boost/config.hpp>\n#include <boost/serialization/shared_ptr.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/utility.hpp>\n#include <boost/serialization/split_free.hpp>\n#include <boost/serialization/assume_abstract.hpp>\n\n#include \"Command.h\"\n\n//----------------------------------------------------------- Forward declarations\nnamespace TP4\n{\n\tstruct Rectangle;\n\tstruct Segment;\n\tstruct Polygon;\n\n\ttemplate<bool is_union>\n\tstruct Group;\n\n\tusing Shape_union = Group<true>;\n\tusing Shape_intersection = Group<false>;\n}\n\nnamespace TP4\n{\n\t//----------------------------------------------------------------------------\n\t//! Classe permettant le polymorphisme sur tout type T validant le concept de forme (ayant une surcharge de 'move' et 'Is_contained')\n\t//! Cette classe permet d'isoler le méchanisme de polymorphisme des types de formes géométrique.\n\t//! Ainsi, les formes géométriques sont des types simples sans héritage (et immutables), ce qui facilite l'ajout de nouvelles formes\n\t//! et rend le code plus clair.\n\t//! @see https://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil\n\t//! La classe est serialisable grâce à boost::serialization.\n\t//! @remarks boost gère également la serialisation des shared_ptr dans TP4::History_shape de manière à ce que seul une copie d'une \n\t//! même forme soit en mémoire même si l'on déserialise plusieurs pointeurs vers cette forme.\n\t//----------------------------------------------------------------------------\n\tclass History_shape final\n\t{\n\tpublic:\n\t\tHistory_shape() = default;\n\t\t//! Constructeur de la classe History_shape à partir d'une forme de type T.\n\t\t//! Ce constructeur permet en autre la convertion implicite d'un type validant le concept de forme vers 'History_shape'.\n\t\ttemplate<typename Shape_t>\n\t\tHistory_shape(Shape_t shape) : m_self(boost::shared_ptr<shape_model<Shape_t>>(new shape_model<Shape_t>(std::move(shape)))) // Boost 60: std::make_shared<shape_model<Shape_t>>(std::move(shape))\n\t\t{ }\n\n\t\tHistory_shape clone() const;\n\n\t\tfriend bool Is_contained(const History_shape& history_obj, Point point);\n\t\tfriend History_shape Move(const History_shape& history_obj, coord_t dx, coord_t dy);\n\t\tfriend void Print(const History_shape& history_obj);\n\n\tprivate:\n\t\tstruct shape_concept\n\t\t{\n\t\t\tvirtual ~shape_concept() = default;\n\t\t\tvirtual bool polymorphic_is_contained(Point point) const = 0;\n\t\t\tvirtual History_shape polymorphic_move(coord_t dx, coord_t dy) const = 0;\n\t\t\tvirtual void polymorphic_print() const = 0;\n\t\t\tvirtual History_shape polymorphic_clone() const = 0;\n\n\t\tprivate:\n\t\t\tfriend class boost::serialization::access;\n\n\t\t\ttemplate<typename Archive>\n\t\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t\t{ }\n\t\t};\n\n\t\t//! Shape model forward declaration\n\t\ttemplate<typename Shape_t>\n\t\tstruct shape_model;\n\n\t\t//! Pointeur vers une forme quelquonque (par le quel les appels polymorphiques sont faits)\n\t\t//! @remarks C'est un shared_ptr car ce pointeur est propiétaire de la forme pointée et que\n\t\t//! l'historique peut contenir des mêmes formes à des moments différents (plusieurs shared_ptr\n\t\t//! pointent alors vers la même forme)\n\t\t//! @remarks on utilise boost::shared_ptr plutot que std::shared_ptr car la version de boost \n\t\t//! installée en IF ne supporte pas la serialisation de std::shared_ptr.\n\t\tboost::shared_ptr<const shape_concept> m_self;\n\n\t\tfriend class boost::serialization::access;\n\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\t// Ajoute au registre de l'archive de serialisation les types dérivés de 'shape_concept'. \n\t\t\t// Cela permet à boost::serialization de gèrer le polymorphisme lors de la (de)serialisation.\n\t\t\tar.template register_type<shape_model<Rectangle>>();\n\t\t\tar.template register_type<shape_model<Segment>>();\n\t\t\tar.template register_type<shape_model<Polygon>>();\n\t\t\tar.template register_type<shape_model<Shape_union>>();\n\t\t\tar.template register_type<shape_model<Shape_intersection>>();\n\n\t\t\t// Serialise le shared pointer\n\t\t\tar & boost::serialization::make_nvp(\"shape_ptr\", m_self);\n\t\t}\n\t};\n\n\t//! L'état d'un historique est une collection de 'History_shape' (History_state) et l'on copie cette collection à chaque étape \n\t//! annulable (appel à 'commit'), mais les formes ne sont pas copiées (les shared_ptr sont copiés). Finalement seul les modifications\n\t//! sont retenues dans l'historique puisque les formes sont immutables (de nouvelles fomes sont crées si des modifications sont \n\t//! nescessaires, elles ne seront présentes en mémoire q'une seule fois sinon).\n\tusing History_state = std::unordered_map<name_t, History_shape>;\n\n\tstruct Shape_history\n\t{\n\t\tconst History_state& current() const;\n\t\tHistory_state& current();\n\t\tvoid commit();\n\t\tvoid undo();\n\t\tvoid redo();\n\t\tvoid clear();\n\n\tprivate:\n\t\tstd::vector<History_state> m_history = { History_state() };\n\t\tdecltype(m_history)::iterator m_current_state = std::begin(m_history);\n\t};\n\n\tbool Is_contained(const History_shape& history_obj, Point point);\n\tHistory_shape Move(const History_shape& history_obj, coord_t dx, coord_t dy);\n}\n\n//------------------------------------------ History_shape::shape_model inner type\nnamespace TP4\n{\n\ttemplate<typename Shape_t>\n\tstruct History_shape::shape_model : shape_concept\n\t{\n\t\tshape_model() = default;\n\t\texplicit shape_model(Shape_t shape) : shape(std::move(shape))\n\t\t{ }\n\n\t\tbool polymorphic_is_contained(Point point) const override\n\t\t{\n\t\t\treturn Is_contained(shape, std::move(point));\n\t\t}\n\n\t\tHistory_shape polymorphic_move(coord_t dx, coord_t dy) const override\n\t\t{\n\t\t\treturn Move(shape, dx, dy);\n\t\t}\n\n\t\tvoid polymorphic_print() const override\n\t\t{\n\t\t\tstd::cout << shape;\n\t\t}\n\n\t\tHistory_shape polymorphic_clone() const override\n\t\t{\n\t\t\treturn shape;\n\t\t}\n\n\t\tShape_t shape;\n\n\tprivate:\n\t\tfriend class boost::serialization::access;\n\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\tar & boost::serialization::make_nvp(\"shape_concept\", boost::serialization::base_object<shape_concept>(*this))\n\t\t\t\t& boost::serialization::make_nvp(\"shape\", shape);\n\t\t}\n\t};\n}\n\n//------------------------------------------------------------ Boost serialization\nnamespace boost\n{\n\tnamespace serialization\n\t{\n\t\t//-------------------------------------------- History_state serialization\n\t\ttemplate<typename Archive>\n\t\tvoid save(Archive& ar, const TP4::History_state& shapes, const unsigned int version)\n\t\t{\n\t\t\t// Serialisation manuelle de 'shapes' (la version de boost installée en IF ne supporte pas la serialisation des unordered_map)\n\t\t\tauto size = shapes.size();\n\t\t\tar << make_nvp(\"shape_count\", size);\n\t\t\tfor (const auto& p : shapes)\n\t\t\t{\n\t\t\t\tar << make_nvp(\"name\", p.first)\n\t\t\t\t\t<< make_nvp(\"history_shape\", p.second);\n\t\t\t}\n\t\t}\n\n\t\ttemplate<typename Archive>\n\t\tvoid load(Archive& ar, TP4::History_state& shapes, const unsigned int version)\n\t\t{\n\t\t\tshapes.clear();\n\n\t\t\t// Deserialisation manuelle de 'shapes' (la version de boost installée en IF ne supporte pas la serialisation des unordered_map)\n\t\t\tTP4::History_state::size_type size;\n\t\t\tar >> make_nvp(\"shape_count\", size);\n\t\t\tshapes.reserve(size);\n\n\t\t\twhile (size-- != 0)\n\t\t\t{\n\t\t\t\tTP4::History_shape shape;\n\t\t\t\tTP4::name_t name;\n\t\t\t\tar >> make_nvp(\"name\", name);\n\t\t\t\tar >> make_nvp(\"history_shape\", shape);\n\t\t\t\tshapes[std::move(name)] = std::move(shape);\n\t\t\t}\n\t\t}\n\t}\n}\n\nBOOST_SERIALIZATION_SPLIT_FREE(TP4::History_state)\n\n#endif // !HISTORY_H\n" }, { "alpha_fraction": 0.6807817816734314, "alphanum_fraction": 0.6872963905334473, "avg_line_length": 37.375, "blob_id": "d629cc1786169b1c2f146d7a6df4d3ab7507d337", "content_id": "f04c36c5aba1eeb08d0715364597aaf3ef91514e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2150, "license_type": "permissive", "max_line_length": 155, "num_lines": 56, "path": "/TP4_cpp/src/Segment.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-2", "text": "#include \"Segment.h\"\n\n#include <string>\n\n#include \"Utils.h\"\n#include \"Command.h\"\n#include \"optional.h\"\n\nnamespace TP4\n{\n\tstd::experimental::optional<Segment> make_segment(const Point first_point, const Point second_point)\n\t{\n\t\tif (first_point == second_point)\n\t\t\treturn std::experimental::nullopt;\n\t\treturn std::experimental::optional<Segment>(Segment(std::move(first_point), std::move(second_point)));\n\t}\n\n\tSegment Move(const Segment& shape, coord_t dx, coord_t dy)\n\t{\n\t\tconst Point first_point{ shape.first_point.first + dx, shape.first_point.second + dy };\n\t\tconst Point second_point{ shape.second_point.first + dx, shape.second_point.second + dy };\n\n\t\treturn Segment(std::move(first_point), std::move(second_point));\n\t}\n\n\tbool Is_contained(const Segment& shape, Point point)\n\t{\n\t\t// TODO: definir ces opérations dans utils (produit vectoriel et scalaire) ?\n\t\tdouble cross_product =\t(shape.second_point.first - shape.first_point.first) * (point.second - shape.first_point.second)\n\t\t\t\t\t\t\t -\t(point.first - shape.first_point.first) * (shape.second_point.second - shape.first_point.second);\n\n\t\tif (abs(cross_product) < 0.001)\n\t\t{\n\t\t\tdouble scalar_product1 =\t(shape.second_point.first - shape.first_point.first) * (point.first - shape.first_point.first)\n\t\t\t\t\t\t\t\t +\t(shape.second_point.second - shape.first_point.second) * (point.second - shape.first_point.second);\n\t\t\t\n\t\t\tdouble scalar_product2 =\t(shape.second_point.first - shape.first_point.first) * (shape.second_point.first - shape.first_point.first)\n\t\t\t\t\t\t\t\t +\t(shape.second_point.second - shape.first_point.second) * (shape.second_point.second - shape.first_point.second);\n\n\t\t\tif (scalar_product1 > -0.001 && scalar_product1 < scalar_product2)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tstd::ostream& operator<<(std::ostream& flux, const Segment& seg)\n\t{\n\t\tflux << \"{ (\" << seg.first_point.first << \", \" << seg.first_point.second << \"); (\" << seg.second_point.first << \", \" << seg.second_point.second << \") }\";\n\t\treturn flux;\n\t}\n\n\tSegment::Segment(const Point&& first_point, const Point&& second_point)\n\t\t: first_point(std::move(first_point)), second_point(std::move(second_point))\n\t{ }\n}\n" }, { "alpha_fraction": 0.4292134940624237, "alphanum_fraction": 0.5550561547279358, "avg_line_length": 13.766666412353516, "blob_id": "3d4a3452b1e4aa442feb26c282f5888a6af567ea", "content_id": "45cf12568b6d90bf1db15682f8fb90c7d8f9ba21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 890, "license_type": "permissive", "max_line_length": 51, "num_lines": 60, "path": "/TP2_Archi/tp2-3.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "\n#include <msp430fg4618.h>\n\n#include \"lcd.h\"\n\n#define LED1 BIT2\n#define LED2 BIT1\n#define LED3 BIT1\n\n#define SW1 BIT0\n#define SW2 BIT1\n\nvolatile unsigned int i;\n\n\nint main(void)\n{\n\t\n\tlcd_init();\n\tlcd_clear();\n\t\n\tP1DIR = P1DIR & !SW1;\n\t\n\t//unsigned char borne = 40;\n\t//unsigned int s = 0;\n\t//unsigned int i = 0;\n\t/*for(;;)\n\t{\n\t\tunsigned char* ptr = (unsigned char*)(s/8 + 145);\n\t\t*ptr = s%8;\n\t\t\n\t\twhile ((P1IN & SW1) != 0x00);\n\t\tfor(i=0;i<100;i++);\n\t\twhile ((P1IN & SW1) == 0x00);\n\t\t\n\t\t//*ptr = 0x00;\n\t\t\n\t\ts = (s == (150 -145)*8 ? 0 : s + 1);\n\t\t\n\t\tlcd_fill();\n\t\tfor(i=0;i<20000;i++);\n\t\tlcd_clear();\n\t\tfor(i=0;i<20000;i++);\n\t}*/\n\t//unsigned char* ptr;\n\t\n\t/*ptr = (unsigned char*)0x95;\n\t*ptr = 0b00000100;\n\tptr = (unsigned char*)0x94;\n\t*ptr = 0b00000010;\n\tptr = (unsigned char*)0x93;\n\t*ptr = 0b00000001;*/\n\tlcd_display_number(165);\n\tfor(;;)\n\t{\n\t\t\n\t\t//for(i=0;i<1000;i++);\n\t}\n\t\n\treturn 0;\n}\n\n \n" }, { "alpha_fraction": 0.7538461685180664, "alphanum_fraction": 0.7538461685180664, "avg_line_length": 19.076923370361328, "blob_id": "e27f07b47f35f8cd39b8c74b347ff9faee875e28", "content_id": "7f255bf0e0e90e86c16d9b62ec6f527e0a210bc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 260, "license_type": "permissive", "max_line_length": 37, "num_lines": 13, "path": "/TP1_Probas/ProgrammeC/lois_distributions.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef LOIS_DISTRIBUTIONS_H\n#define LOIS_DISTRIBUTIONS_H\n\n#include <stdlib.h>\n#include <stdio.h>\n\ndouble Alea();\ndouble Exponentielle(double lambda);\ndouble Gauss(double sigma, double m);\ndouble f_inversion();\ndouble f_rejet();\n\n#endif // LOIS_DISTRIBUTIONS_H" }, { "alpha_fraction": 0.7364621162414551, "alphanum_fraction": 0.7418772578239441, "avg_line_length": 26.725000381469727, "blob_id": "31837b103774e94f4b8dee9985c0bec58c619c62", "content_id": "e328f4d8e50026e0935b7a717d4a189fc79817a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1111, "license_type": "permissive", "max_line_length": 125, "num_lines": 40, "path": "/TP1_Probas/ProgrammeC/random_generation.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "#ifndef RANDOM_GENERATION_H\n#define RANDOM_GENERATION_H\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n\n#define RANDOM_VALUE_COUNT 1024\n\n// 4 higher bits of rand()\nint generate_rand_high();\n// 4 lowers bits of rand()\nint generate_rand_low();\n// AES\nint generate_aes();\n// Mersenne-Twister\nint generate_twister();\n// Von eumann\nint generate_neumann();\n\n// Structure simplifiant la manipulation de la génération d'un tableau de valeurs aléatoires\ntypedef struct\n{\n\t// Tableau des valeures\n\tint* values;\n\t// Nombre de valeures\n\tsize_t values_count;\n\t// Nombre de bits pris en compte dans chaque valeures\n\tunsigned int bit_count;\n} generator_array;\n\nint get_bit(generator_array* data, size_t index);\nsize_t size(generator_array* data);\nvoid destroy(generator_array* data);\n\n// Generates 'n' random values (of 'bit_count' used bits) from given 'random_generator' and store them \n// into a file named 'name' (returns data as a generator_array).\ngenerator_array GenerateRandomValues(unsigned int n, unsigned int bit_count, const char* name, int(*random_generator)(void));\n\n#endif // RANDOM_GENERATION_H" }, { "alpha_fraction": 0.6584880352020264, "alphanum_fraction": 0.6594827771186829, "avg_line_length": 29.46464729309082, "blob_id": "ed945ae494db3c9900b863caa248c8c81cb9fc3f", "content_id": "4a523b881217ac75568d3cc3c91f03af94d3506c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3022, "license_type": "permissive", "max_line_length": 99, "num_lines": 99, "path": "/TP4_cpp/src/Scene.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tScene\n\t\t\t\t\t\t\t\t\t-----\n*********************************************************************************/\n\n#ifndef SCENE_H\n#define SCENE_H\n\n#include <string>\n#include <memory>\n\n#ifdef USE_TXT_ARCHIVE\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#else\n#ifdef USE_BINARY_ARCHIVE\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#else // Use XML archive\n#include <boost/archive/xml_iarchive.hpp>\n#include <boost/archive/xml_oarchive.hpp>\n#endif // !USE_BINARY_ARCHIVE\n#endif // !USE_TXT_ARCHIVE\n\n#include \"Serializable_shape_history.h\"\n#include \"Rectangle.h\"\n#include \"Command.h\"\n#include \"Segment.h\"\n#include \"Polygon.h\"\n#include \"Group.h\"\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\t//! ...\n\t//! TODO: faire une copie qui crée de nouveaux unique_ptr ?\n\tclass Scene final\n\t{\n\tpublic:\n\t\tScene() = default;\n\t\tScene(Scene&&) = default;\n\t\tScene(const Scene&) = delete;\n\t\tScene& operator=(Scene&&) = default;\n\t\tScene& operator=(const Scene&) = delete;\n\n\t\tvoid Undo();\n\t\tvoid Redo();\n\t\tvoid ClearAll();\n\t\tvoid ClearCurrentState();\n\t\tvoid List();\n\t\t//! @throws std::invalid_argument\n\t\tvoid Load(std::string filename);\n\t\t//! @throws std::invalid_argument\n\t\tvoid Save(std::string filename);\n\t\tvoid Delete(const std::vector<name_t>& name);\n\t\tvoid Add_segment(name_t name, Point x, Point y);\n\t\tvoid Add_rectangle(name_t name, Point x, Point y);\n\t\tbool Is_point_contained_by(Point point, name_t shape_name) const;\n\t\tvoid Move_shape(name_t shape_name, coord_t dx, coord_t dy);\n\t\tvoid Add_polygon(name_t name, const std::vector<Point>& vertices);\n\t\tvoid Union(name_t union_name, const std::unordered_set<name_t>& shapes_names);\n\t\tvoid Intersect(name_t inter_name, const std::unordered_set<name_t>& shapes_names);\n\n\tprivate:\n\t\tShape_history m_shapes;\n\n\t\ttemplate<typename Group_t>\n\t\tvoid Create_group(const name_t& group_name, const std::unordered_set<name_t>& shapes_names);\n\t};\n\n\ttemplate<typename Group_t>\n\tvoid Scene::Create_group(const name_t& group_name, const std::unordered_set<name_t>& shapes_names)\n\t{\n\t\tm_shapes.commit();\n\n\t\tstd::vector<History_state::iterator> shapes_its;\n\t\tauto& current_shapes = m_shapes.current();\n\n\t\t// Vérifie si le nom n'est pas déja pris\n\t\tif (current_shapes.find(group_name) != std::end(current_shapes))\n\t\t\tthrow std::invalid_argument(\"Shape name already existing\");\n\n\t\t// Trouve les formes concernées et vérifie qu'il n'y a pas de duplicats\n\t\tstd::vector<History_shape> shapes;\n\t\tfor (const auto& shape_name : shapes_names)\n\t\t{\n\t\t\tauto it = current_shapes.find(shape_name);\n\t\t\tif (it == std::end(current_shapes))\n\t\t\t\tthrow std::invalid_argument(\"One or more shape name is invalid\");\n\t\t\tshapes.emplace_back(it->second.clone());\n\t\t}\n\t\t\n\t\t// Add shape to current history state\n\t\tcurrent_shapes.emplace(group_name, Group_t(std::move(shapes)));\n\t}\n}\n\n#endif // !SCENE_H\n" }, { "alpha_fraction": 0.7262763381004333, "alphanum_fraction": 0.7323334217071533, "avg_line_length": 28.88793182373047, "blob_id": "62984a2391ae197875490f979e566778d84b6756", "content_id": "8825ea938a38d9b4003f28b16c507c2d1198188d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 3467, "license_type": "permissive", "max_line_length": 121, "num_lines": 116, "path": "/TP1_BDDI/fragment nicolas - florentin/fmacerouss_BDD.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "CREATE DATABASE LINK if_oracle01\n CONNECT TO fmacerouss IDENTIFIED BY mdporacle\n USING 'DB1'; \n \ndrop public database link RYORI;\n\nSELECT * \nFROM Ryori.clients@if_oracle01;\n\n--IMPORT PRODUITS ET CONTRAINTE\nCREATE TABLE Produits \nAS (SELECT * FROM Ryori.Produits@if_oracle01);\nALTER TABLE PRODUITS ADD CONSTRAINT PK_PRODUITS PRIMARY KEY (REF_PRODUIT) ;\nALTER TABLE PRODUITS ADD CONSTRAINT FK_PRODUITS_CATEGORIE \nFOREIGN KEY (CODE_CATEGORIE) REFERENCES CATEGORIES (CODE_CATEGORIE) ;\n\n--IMPORT CATEGORIES ET CONTRAINTE\nCREATE TABLE Categories \nAS (SELECT * FROM Ryori.Categories@if_oracle01);\nALTER TABLE CATEGORIES ADD CONSTRAINT PK_CATEGORIES PRIMARY KEY (CODE_CATEGORIE) ;\n\nSELECT distinct pays\nFROM Ryori.clients@if_oracle01\nORDER BY pays ASC;\n\n-- IMPORT CLIENTS ET CONTRAINTE\nCREATE TABLE Clients_Europe_Sud \nAS (SELECT * \n FROM Ryori.Clients@if_oracle01\n WHERE pays = 'Espagne'\n OR pays = 'France'\n OR pays = 'Portugal'\n OR pays = 'Italie' \n OR pays = 'Espagne'\n ); \nALTER TABLE CLIENTS_EUROPE_SUD ADD CONSTRAINT PK_CLIENTS_EUS PRIMARY KEY (CODE_CLIENT) ;\n \n-- IMPORT STOCK ET CONTRAINTE \nCREATE TABLE Stock_Europe_Sud \nAS (SELECT * \n FROM Ryori.Stock@if_oracle01\n WHERE pays = 'Espagne'\n OR pays = 'France'\n OR pays = 'Portugal'\n OR pays = 'Italie' \n OR pays = 'Espagne'\n );\nALTER TABLE STOCK_EUROPE_SUD ADD CONSTRAINT PK_STOCK_EUS PRIMARY KEY (REF_PRODUIT, PAYS) ;\nALTER TABLE STOCK_EUROPE_SUD ADD CONSTRAINT FK_STOCK_PROD_EUS \nFOREIGN KEY (REF_PRODUIT) REFERENCES PRODUITS (REF_PRODUIT) ;\n\n--IMPORT COMMANDES ET CONTRAINTE\nCREATE TABLE Commandes_Europe_Sud \nAS (SELECT * \n FROM Ryori.Commandes@if_oracle01 Com\n WHERE EXISTS\n (SELECT *\n FROM Clients_Europe_Sud cl\n WHERE cl.Code_Client = Com.Code_Client\n )\n);\nALTER TABLE COMMANDES_EUROPE_SUD ADD CONSTRAINT PK_COMMANDES_EUS PRIMARY KEY (NO_COMMANDE) ;\nALTER TABLE COMMANDES_EUROPE_SUD ADD CONSTRAINT FK_COMMANDE_CLIENTS_EUS \nFOREIGN KEY (CODE_CLIENT) REFERENCES CLIENTS_EUROPE_SUD (CODE_CLIENT) ;\n\n\n--IMPORT DETAILS_COMMANDES ET CONTRAINTE\nCREATE TABLE Details_Commandes_Europe_Sud \nAS (SELECT * \n FROM Ryori.Details_Commandes@if_oracle01 DetCom\n WHERE EXISTS\n (SELECT *\n FROM Commandes_Europe_Sud comEU\n WHERE comEU.NO_COMMANDE = DetCom.NO_COMMANDE\n )\n);\nALTER TABLE DETAILS_COMMANDES_EUROPE_SUD ADD CONSTRAINT PK_DETAILS_COMMANDES_EUS PRIMARY KEY (NO_COMMANDE, REF_PRODUIT) ;\nALTER TABLE DETAILS_COMMANDES_EUROPE_SUD ADD CONSTRAINT FK_DETAILS_COM_COM_EUS \nFOREIGN KEY (NO_COMMANDE) REFERENCES COMMANDES_EUROPE_SUD (NO_COMMANDE) ;\nALTER TABLE DETAILS_COMMANDES_EUROPE_SUD ADD CONSTRAINT FK_DETAILS_PROD_PROD_EUS \nFOREIGN KEY (REF_PRODUIT) REFERENCES PRODUITS (REF_PRODUIT) ;\n\n--DBLINK\nCREATE DATABASE LINK Amerique\n CONNECT TO fmacerouss IDENTIFIED BY mdporacle\n USING 'DB4'; \n\nCREATE DATABASE LINK Europe_Nord\n CONNECT TO fmacerouss IDENTIFIED BY mdporacle\n USING 'DB2'; \n\n--View\nCREATE VIEW Clients AS \n SELECT *\n FROM pesotir.Clients_Amerique@Amerique\n UNION\n select *\n FROM gsarnette.Clients_Europe_Nord@Europe_Nord\n UNION\n SELECT *\n FROM fmacerouss.CLIENTS_EUROPE_SUD;\n \nCREATE VIEW Produits AS \n SELECT *\n FROM pesotir.produits_Amerique@Amerique\n UNION\n select *\n FROM gsarnette.produits_Europe_Nord@Europe_Nord\n UNION\n SELECT *\n FROM fmacerouss.PRODUITS;\n\n\n--TRIGGER*\nSELECT *\nFROM GSARNETTE.Clients_Europe_Nord@Europe_Nord;\n" }, { "alpha_fraction": 0.3021390438079834, "alphanum_fraction": 0.31550800800323486, "avg_line_length": 37.35897445678711, "blob_id": "4ce6e75cc3a65f88942dea2a7d92cdafe4875fe5", "content_id": "5a85b8879da61b03236bf323db143468e31c6a5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1497, "license_type": "permissive", "max_line_length": 93, "num_lines": 39, "path": "/TP1_cpp_gcc/source/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/********************************************************************************************\n\t\t\t\t\t\t\t\t\t\tmain.cpp\n\t\t\t\t\t\t\t\t\t\t--------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n********************************************************************************************/\n\n//----------------------------------------------------------------------------------- INCLUDE\n//--------------------------------------------------------------------------- Include système\n#include <iostream>\n\n//------------------------------------------------------------------------- Include personnel\n#include \"collection.h\"\n#include \"tests.h\"\n\n//-------------------------------------------------------------------------------------- MAIN\n\nint main()\n{\n\tstd::cout\n\t\t<< R\"(\t\t\t _________ ___ _____ __ __ )\" << std::endl\n\t\t<< R\"(\t\t\t/_ __/ _ < / / ___/_/ /___/ /_)\" << std::endl\n\t\t<< R\"(\t\t\t / / / ___/ / / /__/_ __/_ __/)\" << std::endl\n\t\t<< R\"(\t\t\t/_/ /_/ /_/ \\___/ /_/ /_/ )\" << std::endl << std::endl;\n\n\tstd::cout << \"### TESTING COLLECTION CLASS (no dogs will be harmed during this test) ###\";\n\n\ttest(test_lifetime, \"OBJECT LIFETIME\");\t// test 1\n\ttest(test_afficher, \"AFFICHER\");\t\t// test 2\n\ttest(test_ajuster, \"AJUSTER\");\t\t\t// test 3\n\ttest(test_ajouter, \"AJOUTER\");\t\t\t// test 4\n\ttest(test_retirer, \"RETIRER\");\t\t\t// test 5\n\ttest(test_reunir, \"REUNIR\");\t\t\t// test 6\n\n\tstd::cout << std::endl << std::endl << \"Press ENTER to exit...\";\n\tstd::cin.get();\n\n\treturn EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7242472171783447, "alphanum_fraction": 0.7242472171783447, "avg_line_length": 19.354839324951172, "blob_id": "88b6815792969c278ed6e10129ef079d79e78520", "content_id": "89c492a3ad56d1287814dce2d252577d87eea36c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 634, "license_type": "permissive", "max_line_length": 67, "num_lines": 31, "path": "/TP1_TP2_Reseau_rendu/VersionSocket/Client/src/Client/Main.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package Client;\n\nimport javafx.stage.Stage;\nimport javafx.application.Application;\n\n/**\n * Classe principale de l'application client de chat.\n */\npublic class Main extends Application {\n\t@Override\n\tpublic void start(Stage primaryStage) throws Exception {\n\t\tm_page_navigator = new Navigator(primaryStage);\n\t\tm_page_navigator.showLoginPage(null);\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\tif(m_page_navigator != null)\n\t\t\tm_page_navigator.disposeDAL();\n\t}\n\n\t/**\n\t * Méthode main, point d'entrée du programme lançant l'application\n\t */\n\tpublic static void main(String[] args)\n\t{\n\t\tlaunch(args);\n\t}\n\n\tprivate Navigator m_page_navigator;\n}\n" }, { "alpha_fraction": 0.5811983346939087, "alphanum_fraction": 0.58574378490448, "avg_line_length": 42.60360336303711, "blob_id": "4b3759972c0210d9a318f95377296f3a487a815c", "content_id": "3aead4fe85f1b18a758c3a8fed2a2174b0387dc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4917, "license_type": "permissive", "max_line_length": 121, "num_lines": 111, "path": "/TP1_cpp_gcc/includes/collection.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\tcollection - A collection of dogs\n\t\t\t\t\t\t-----------------------------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//--------- Interface de la classe <collection.h> (fichier collection.h) ---------\n#ifndef COLLECTION_H\n#define COLLECTION_H\n\n//----------------------------------------------------------- Interfaces utilisées\n#include \"dog.h\"\n\nnamespace TP1\n{\n\t//----------------------------------------------------------------------------\n\t// collection:\n\t// classe qui permet de manipuler une collection d'objets de type dog\n\t//----------------------------------------------------------------------------\n\tclass collection\n\t{\n\t\t//----------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//----------------------------------------------------- Méthodes publiques\n\n\t\t// Description : affiche la valeur de la collection.\n\t\t//\tLa valeur de la collection est affichée sous la forme : \"({ <val1>, <val2>, ... }, <m_capacity>)\"\n\t\t//\tavec <val1>, <val2>, ... les âges des chiens et <m_capacity> la capacité de la collection.\n\t\tvoid afficher() const;\n\n\t\t// Description: ajoute dog_to_add dans la collection courante\n\t\t//\t\tnew_dog: reférence constante vers un dog qui sera ajouté dans la collection\n\t\tvoid ajouter(const dog& dog_to_add);\n\n\t\t// Description: retire old_dog de la collection courante\n\t\t//\t\told_dog: reference vers un dog qui sera retiré de la collection\n\t\t//\t\tRETOURNE: Un booléen indiquant si au moins un dog a bien été retiré\n\t\t//\tNOTE: ajuste la capacité de la collection au minimum même si old_dog n'est pas présent dans la collection \n\t\tbool retirer(const dog& old_dog);\n\n\t\t// Description: retire l'ensemble des dogs du parametre 'dogs' de la collection courante\n\t\t//\t\tdogs: tableau de dogs qui seront retirés de la collection\n\t\t//\t\tsize: taille du tableau dogs\n\t\t//\t\tRETOURNE: Un booléen indiquant si au moins un dog a bien été retiré\n\t\t//\tNOTE: ajuste la capacité de la collection au minimum même si aucun dog de dogs n'est pas présent dans la collection \n\t\tbool retirer(const dog dogs[], size_t size);\n\n\t\t// Description: ajuste, si possible, la capacité de la collection à la taille spécifiée\n\t\t//\t\tcapacity: nouvelle taille de mémoire allouée pour la structure de donnée interne\n\t\t//\t\tRETOURNE: Un booléen indiquant si un ajustement de la capacité a bien été effectué\n\t\tbool ajuster(size_t capacity);\n\n\t\t// Description: ajoute le contenu de la collection donnée en paramètre \n\t\t//\t\tother: reference vers la collection à réunir avec la collection courante\n\t\t//\t\tRETOURNE: Un booléen indiquant si des dogs de 'other' on bien été ajoutés à la collection\n\t\tbool reunir(const collection& other);\n\n\t\t//------------------------------------------------- Surcharge d'opérateurs\n\n\t\t// Empêche l'implémentation par défaut du 'copy assignement operator'\n\t\tcollection& operator=(const collection&) = delete;\n\n\t\t//-------------------------------------------- Constructeurs - destructeur\n\n\t\t// Empêche l'implémentation par défaut du constructeur de copie\n\t\tcollection(const collection&) = delete;\n\n\t\t// Description: Constructeur d'une collection de taille pré-allouée donnée\n\t\t//\t\tcapacity: Taille de la nouvelle collection\n\t\texplicit collection(size_t capacity);\n\n\t\t// Description: Constructeur d'une collection à partir d'un ensemble de dog donné en paramètre\n\t\t//\t\tdogs: tableau des dogs qui seront ajoutés à la collection\n\t\t//\t\tsize: taille du tableau dogs\n\t\tcollection(const dog dogs[], size_t size);\n\n\t\t// Description: Destructeur de la colection courante\n\t\tvirtual ~collection();\n\n\t\t//------------------------------------------------------------------ PRIVE \n\tprotected:\n\t\t//----------------------------------------------------- Méthodes protégées\n\n\t\t// Description: Trouve le nombre de dog apparetenant à la fois à 'm_dogs' \n\t\t//\tet au paramètre 'dogs_to_find'\n\t\t//\t\tdogs_to_find: tableau de dogs qui seront recherchés dans la collection\n\t\t//\t\tsize: taille du tableau 'dogs_to_find'\n\t\t//\t\tRETOURNE: le nombre de dog apparetenant à la fois à 'm_dogs' et à 'dogs_to_find'\n\t\tunsigned int find_all_of(const dog dogs_to_find[], size_t size) const;\n\n\t\t// Description: Désalloue la mémoire allouée pour le tableau de pointeur de dog \n\t\t//\tet pour les objets de type dog.\n\t\tvoid disposeDogs();\n\n\t\t//----------------------------------------------------- Attributs protégés\n\n\t\t// Tableau de pointeurs de dog\n\t\tdog** m_dogs = nullptr;\n\t\t// Taille du tableau m_dogs\n\t\tsize_t m_capacity = 0;\n\t\t// Taille utilisée du tableau m_dogs\n\t\tsize_t m_size = 0;\n\n\t\t//---------------------------------------------------- Constantes protégés\n\n\t\tstatic const size_t INITIAL_ALLOCATION_SIZE = 5;\n\t};\n}\n\n#endif // COLLECTION_H\n" }, { "alpha_fraction": 0.5926229357719421, "alphanum_fraction": 0.5950819849967957, "avg_line_length": 21.80373764038086, "blob_id": "f7ea17a2d958700ac1a41902e44f30fea54c9f89", "content_id": "27c885909478a37d29945634478521558b0e02d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2444, "license_type": "permissive", "max_line_length": 173, "num_lines": 107, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/metier/model/Member.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.metier.model;\n\nimport com.google.maps.model.LatLng;\n\nimport javax.persistence.Id;\nimport java.io.Serializable;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\n\n/**\n * Classe représentant un membre de l'association pouvant rejoindre ou créer des événements\n * @author B3330\n */\n@Entity\npublic class Member implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String address;\n private Double lat;\n private Double lng;\n private String mail;\n private String nom;\n private String prenom;\n\n public Member() { }\n\n public Member(String nom, String prenom, String address, String mail, LatLng coordonnees) {\n this.nom = nom;\n this.prenom = prenom;\n this.mail = mail;\n this.address = address;\n this.lat = coordonnees.lat;\n this.lng = coordonnees.lng;\n }\n\n public Long getId() {\n return id;\n }\n\n public String getNom() {\n return nom;\n }\n\n public String getPrenom() {\n return prenom;\n }\n\n public String getMail() {\n return mail;\n }\n\n public String getAddress() {\n return address;\n }\n\n public Double getLatitude() {\n return lat;\n }\n\n public Double getLongitude() {\n return lng;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\n }\n\n public void setPrenom(String prenom) {\n this.prenom = prenom;\n }\n\n public void setMail(String mail) {\n this.mail = mail;\n }\n\n public void setAddress(String adresse) {\n this.address = adresse;\n }\n\n public void setCoordonnees(LatLng latLng) {\n this.lat = latLng.lat;\n this.lng = latLng.lng;\n }\n\n @Override\n public int hashCode() {\n return (id != null ? id.hashCode() : 0);\n }\n\n @Override\n public boolean equals(Object object) {\n if (!(object instanceof Member))\n return false;\n\n Member other = (Member) object;\n if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Member{\" + \"id=\" + id + \", nom=\" + nom + \", prenom=\" + prenom + \", mail=\" + mail + \", adresse=\" + address + \", longitude=\" + lng + \", latitude=\" + lat + '}';\n }\n}\n" }, { "alpha_fraction": 0.5087719559669495, "alphanum_fraction": 0.5463659167289734, "avg_line_length": 14.736842155456543, "blob_id": "612f11897cc4150f3ea0ce53e11a8080297cca82", "content_id": "22878ca9914c27d2ab08b1f7a33153e0133a2ef2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1197, "license_type": "permissive", "max_line_length": 64, "num_lines": 76, "path": "/TP2_Concurrency/question3.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <pthread.h>\n\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t i = 0;\n uint64_t nPrime = n;\n printf(\"%ju: \", n);\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime%i == 0)\n\t\t{\n\t\t\tnPrime = nPrime/i;\n\t\t\tprintf(\"%ju \", i);\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\r\\n\");\n}\n\nvoid* print_prime_factors_thread(void* n)\n{\n\t\n\tuint64_t x = *((uint64_t*)n);\n\t\n\tprint_prime_factors(x);\n\t\n\treturn NULL;\n}\n\nint main(void)\n{\n\t\tFILE* primeList;\n\t\tprimeList = fopen(\"primes2.txt\", \"r\");\n\t\t\n\t\tpthread_t ta;\n\t\tpthread_t tb;\n\t\t\n\t\tif(primeList == NULL)\n\t\t{\n\t\t\tperror(\"erreur ouverture fichier\");\n\t\t\texit(-1);\n\t\t}\n\t\t\n\t\tchar line1[60];\n\t\tchar line2[60];\n\t\tint fin = 1;\n\t\twhile(fin == 1)\n\t\t{\n\t\t\tfin = 0;\n\t\t\tif(fgets(line1, 60, primeList) != NULL)\n\t\t\t{\n\t\t\t\tfin = 1;\n\t\t\t\tuint64_t i1 = atoll(line1);\n\t\t\t\tpthread_create (&ta, NULL, print_prime_factors_thread, &i1);\n\t\t\t}\n\t\t\tif(fgets(line2, 60, primeList) != NULL)\n\t\t\t{\n\t\t\t\tfin = 1;\n\t\t\t\tuint64_t i2 = atoll(line2);\n\t\t\t\tpthread_create (&tb, NULL, print_prime_factors_thread, &i2);\n\t\t\t}\n\t\t\t\n\t\t\tpthread_join (ta, NULL);\n\t\t\tpthread_join (tb, NULL);\n\t\t}\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.7012025713920593, "avg_line_length": 29.02777862548828, "blob_id": "9d7d8fdfc67d5752e126a675e54f1aadc450508d", "content_id": "95f992cb9980064aef1bb60d521b9eaf7750ab7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1083, "license_type": "permissive", "max_line_length": 102, "num_lines": 36, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/DAL/ActivityDAL.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.DAL;\n\nimport java.util.List;\nimport javax.persistence.Query;\nimport javax.persistence.EntityManager;\n\nimport TP1_SI.metier.model.Activity;\n\n/**\n * Data Access Layer permettant d'obtenir, de créer et modifier des instances de la classe 'Activity'.\n * Utilise JPA pour persiter les Activitées.\n * @author B3330\n */\npublic class ActivityDAL {\n\n public void create(Activity activity) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n em.persist(activity);\n }\n\n public Activity update(Activity activity) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.merge(activity);\n }\n\n public Activity findById(long id) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.find(Activity.class, id);\n }\n\n public List<Activity> findAll() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT a FROM Activity a\");\n return (List<Activity>) q.getResultList();\n }\n}\n" }, { "alpha_fraction": 0.5956426858901978, "alphanum_fraction": 0.5978213548660278, "avg_line_length": 26, "blob_id": "47d0e4b7e188a837c6be1d6badf69c7e91442075", "content_id": "4e976a9ee2570de971e1828ebfb37ca0ca690727", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2297, "license_type": "permissive", "max_line_length": 92, "num_lines": 85, "path": "/TP1_Concurrency/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "############################################################################################\n################################## GENERIC MAKEFILE ########################################\n############################################################################################\n# TODO: gerer les sous-dossiers / fichiers ayants le mêmes noms dans des dossiers différts\n# TODO: gerer les extentions .hpp, .cxx, ...\n\n# Debug mode (comment this line to build project in release mode)\nDEBUG = true\n\n# Compiler\nCC = g++\n# Command used to remove files\nRM = rm -f\n# Compiler and pre-processor options\nCPPFLAGS = -Wall -std=c++11 -Ofast\n# Debug flags\nDEBUGFLAGS = -g\n# Resulting program file name\nEXE_NAME = Parking\n# The source file extentions\nSRC_EXT = cpp\n# The header file types\n# TODO permettre les .hpp\nHDR_EXT = h\n\n# Source directory\nSRCDIR = source\n# Headers directory\nINCDIR = include\n# Main output directory\nOUTPUT_DIR = bin\n# Release output directory\nRELEASEDIR = release\n# Debug output directory\nDEBUGDIR = debug\n# Dependency files directory\nDEPDIR = dep\n# Libraries paths\nLIB_DIRS = -L libs\n# Library file names (e.g. '-lboost_serialization-mt')\nLIBS = -ltp -ltcl8.5 -lncurses\n# List of include paths\nINCLUDES = ./$(INCDIR)\n\nifdef DEBUG\nBUILD_PATH = ./$(OUTPUT_DIR)/$(DEBUGDIR)\nelse\nDEBUGFLAGS =\nBUILD_PATH = ./$(OUTPUT_DIR)/$(RELEASEDIR)\nendif\n# Source directory path\nSRC_PATH = ./$(SRCDIR)\n# Dependencies path\nDEP_PATH = ./$(BUILD_PATH)/$(DEPDIR)\n\n# List of source files\nSOURCES = $(wildcard $(SRC_PATH)/*.$(SRC_EXT))\n# List of object files\nOBJS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(BUILD_PATH)/%.o)\n# List of dependency files\nDEPS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(DEP_PATH)/%.d)\n\n.PHONY: all clean rebuild\n\nall: $(BUILD_PATH)/$(EXE_NAME)\n\nclean:\n\t#dos2unix clear_ipc.sh\n\t./clear_ipc.sh\n\t$(RM) $(BUILD_PATH)/*.o\n\t$(RM) $(BUILD_PATH)/$(EXE_NAME)\n\t$(RM) $(DEP_PATH)/*.d\n\nrebuild: clean all\n\n# Build object files\n$(BUILD_PATH)/%.o: $(SRC_PATH)/%.$(SRC_EXT)\n\t@mkdir -p $(DEP_PATH)\n\t$(CC) $(CPPFLAGS) $(DEBUGFLAGS) -I $(INCLUDES) -MMD -MP -MF $(DEP_PATH)/$*.d -c $< -o $@\n\n# Build main target\n$(BUILD_PATH)/$(EXE_NAME): $(OBJS)\n\t$(CC) $(LIB_DIRS) -o $(BUILD_PATH)/$(EXE_NAME) $(OBJS) $(LIBS)\n\t# Copie l'executable dans le dossier principal\n\tcp $(BUILD_PATH)/$(EXE_NAME) ./$(EXE_NAME)\n" }, { "alpha_fraction": 0.6790183782577515, "alphanum_fraction": 0.6807782649993896, "avg_line_length": 44.05727005004883, "blob_id": "8b8f527acd4f7cae834a6faa59fbb342120c9786", "content_id": "1f0e4e69b3ff9c22099d0e96f2da3aa888968622", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 10282, "license_type": "permissive", "max_line_length": 125, "num_lines": 227, "path": "/TP1_BDDI/fragment victoire - pes/Amerique.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "-- Creation du lien vers la base de donnée centralisée et les autres sites\n\nCREATE DATABASE LINK RYORI_LINK \nCONNECT TO pesotir IDENTIFIED BY mdporacle\nUSING 'DB1';\n\nCREATE DATABASE LINK EUROPE_SUD_LINK \nCONNECT TO pesotir IDENTIFIED BY mdporacle\nUSING 'DB3';\n\nCREATE DATABASE LINK EUROPE_NORD_LINK \nCONNECT TO pesotir IDENTIFIED BY mdporacle\nUSING 'DB2';\n\nDROP DATABASE LINK EUROPE_NORD_LINK ;\n\n-- Creation des tables d'amérique\ncreate table PESOTIR.EMPLOYES as select * from RYORI.EMPLOYES@RYORI_LINK;\n\ncreate table PESOTIR.Stock_Amerique as select * from RYORI.STOCK@RYORI_LINK\nWHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil,\n Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique,\n Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque,\n Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-\n Lucie', 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela');\n \ncreate table PESOTIR.Clients_Amerique as select * from RYORI.CLIENTS@RYORI_LINK\nWHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil,\n Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique,\n Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque,\n Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-\n Lucie', 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela');\n\ncreate table PESOTIR.COMMANDES_AMERIQUE as select * from RYORI.COMMANDES@RYORI_LINK\nWHERE CODE_CLIENT IN (SELECT CODE_CLIENT FROM PESOTIR.Clients_Amerique);\n\ncreate table PESOTIR.DETAILS_COMMANDES_AMERIQUE as select * from RYORI.DETAILS_COMMANDES@RYORI_LINK\nWHERE NO_COMMANDE IN (SELECT NO_COMMANDE FROM PESOTIR.COMMANDES_AMERIQUE);\n\n-- Gestion des droits\nGRANT SELECT, INSERT, UPDATE, DELETE\nON Clients_Amerique\nTO GSARNETTE, FMACEROUSS;\n\nGRANT SELECT, INSERT, UPDATE, DELETE\nON Stock_Amerique\nTO GSARNETTE, FMACEROUSS;\n\nGRANT SELECT\nON COMMANDES_AMERIQUE\nTO GSARNETTE, FMACEROUSS;\n\nGRANT SELECT\nON DETAILS_COMMANDES_AMERIQUE\nTO GSARNETTE, FMACEROUSS;\n\nGRANT SELECT\nON EMPLOYES\nTO GSARNETTE, FMACEROUSS;\n\n-- Vues\nCREATE OR REPLACE VIEW Produits AS \n SELECT *\n FROM fmacerouss.PRODUITS@EUROPE_SUD_LINK;\n \nCREATE OR REPLACE VIEW Categories AS \n SELECT *\n FROM fmacerouss.CATEGORIES@EUROPE_SUD_LINK;\n\nCREATE OR REPLACE VIEW FOURNISSEURS AS\n SELECT *\n FROM GSARNETTE.FOURNISSEURS@EUROPE_NORD_LINK;\n\nCREATE OR REPLACE VIEW Clients AS \n SELECT *\n FROM pesotir.Clients_Amerique\n WHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela')\n UNION ALL\n select *\n FROM gsarnette.Clients_Europe_Nord@EUROPE_NORD_LINK\n WHERE Pays IN ('Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', 'Belgique', \n 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n UNION ALL\n select *\n FROM gsarnette.Clients_autre@EUROPE_NORD_LINK\n WHERE Pays IS NULL OR Pays NOT IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela', 'Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican',\n 'Malte', 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine', 'Monténégro', 'Serbie', \n 'Slovénie', 'Bulgarie', 'Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', \n 'Belgique', 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n UNION ALL\n SELECT *\n FROM fmacerouss.CLIENTS_EUROPE_SUD@EUROPE_SUD_LINK\n WHERE Pays IN ('Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican', 'Malte', \n 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine',\n 'Monténégro', 'Serbie', 'Slovénie', 'Bulgarie');\n\nCREATE VIEW Details_Commandes AS \n SELECT *\n FROM pesotir.details_commandes_Amerique\n UNION ALL\n select *\n FROM gsarnette.details_commandes_Europe_Nord@EUROPE_NORD_LINK\n UNION ALL\n select *\n FROM gsarnette.details_commandes_autre@EUROPE_NORD_LINK\n UNION ALL\n SELECT *\n FROM fmacerouss.DETAILS_COMMANDES_EUROPE_SUD@EUROPE_SUD_LINK;\n\nCREATE VIEW Commandes AS \n SELECT *\n FROM pesotir.commandes_Amerique\n UNION ALL\n select *\n FROM gsarnette.commandes_Europe_Nord@EUROPE_NORD_LINK\n UNION ALL\n select *\n FROM gsarnette.commandes_autre@EUROPE_NORD_LINK\n UNION ALL \n SELECT *\n FROM fmacerouss.COMMANDES_EUROPE_SUD@EUROPE_SUD_LINK;\n \nCREATE OR REPLACE VIEW STOCK AS \n SELECT *\n FROM pesotir.stock_Amerique\n WHERE Pays IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela')\n UNION ALL \n select *\n FROM gsarnette.stock_Europe_Nord@EUROPE_NORD_LINK\n WHERE Pays IN ('Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', 'Belgique',\n 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n \n UNION ALL\n select *\n FROM gsarnette.Stock_autre@EUROPE_NORD_LINK\n WHERE Pays IS NULL OR Pays NOT IN ('Antigua-et-Barbuda', 'Argentine', 'Bahamas', 'Barbade', 'Belize', 'Bolivie', 'Bresil',\n 'Canada', 'Chili', 'Colombie', 'Costa Rica', 'Cuba', 'Republique dominicaine', 'Dominique',\n 'Equateur', 'Etats-Unis', 'Grenade', 'Guatemala', 'Guyana', 'Haïti', 'Honduras', 'Jamaïque',\n 'Mexique', 'Nicaragua', 'Panama', 'Paraguay', 'Perou', 'Saint-Christophe-et-Nievès', 'Sainte-Lucie',\n 'Saint-Vincent-et-les Grenadines', 'Salvador', 'Suriname', 'Trinite-et-Tobago', 'Uruguay',\n 'Venezuela', 'Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican',\n 'Malte', 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine', 'Monténégro', 'Serbie', \n 'Slovénie', 'Bulgarie', 'Norvège', 'Suède', 'Danemark', 'Islande', 'Finlande, Royaume-Uni', 'Irlande', \n 'Belgique', 'Luxembourg', 'Pays-Bas', 'Allemagne', 'Pologne')\n \n UNION ALL\n SELECT *\n FROM fmacerouss.STOCK_EUROPE_SUD@EUROPE_SUD_LINK\n WHERE Pays IN ('Espagne', 'Portugal', 'Andorre', 'France', 'Gibraltar', 'Italie', 'Saint-Marin', 'Vatican', 'Malte', \n 'Albanie', 'Bosnie-Herzégovine', 'Croatie', 'Grèce', 'Macédoine',\n 'Monténégro', 'Serbie', 'Slovénie', 'Bulgarie');\n \n-- Contraintes\nALTER TABLE CLIENTS_AMERIQUE ADD CONSTRAINT PK_CLIENTS PRIMARY KEY (CODE_CLIENT);\nALTER TABLE COMMANDES_AMERIQUE ADD CONSTRAINT PK_COMMANDES PRIMARY KEY (NO_COMMANDE);\nALTER TABLE DETAILS_COMMANDES_AMERIQUE ADD CONSTRAINT PK_DETAILS_COMMANDES PRIMARY KEY (NO_COMMANDE, REF_PRODUIT);\nALTER TABLE EMPLOYES ADD CONSTRAINT PK_EMPLOYES PRIMARY KEY (NO_EMPLOYE);\n\nALTER TABLE COMMANDES_AMERIQUE ADD CONSTRAINT FK_COMMANDE_CLIENTS \nFOREIGN KEY (CODE_CLIENT) REFERENCES CLIENTS_AMERIQUE (CODE_CLIENT);\n\nALTER TABLE COMMANDES_AMERIQUE ADD CONSTRAINT FK_COMMANDE_EMPLOYES \nFOREIGN KEY (NO_EMPLOYE) REFERENCES EMPLOYES (NO_EMPLOYE);\n\nALTER TABLE DETAILS_COMMANDES_AMERIQUE ADD CONSTRAINT FK_DETAILS_COMMANDES_COMMANDES \nFOREIGN KEY (NO_COMMANDE) REFERENCES COMMANDES_AMERIQUE (NO_COMMANDE);\n\n--ALTER TABLE DETAILS_COMMANDES_AMERIQUE ADD CONSTRAINT FK_DETAILS_COMMANDES_PRODUITS\n--FOREIGN KEY (REF_PRODUIT) REFERENCES FMACEROUSS.PRODUITS@EUROPE_SUD_LINK (REF_PRODUIT);\n\n--ALTER TABLE DETAILS_COMMANDES_AMERIQUE ADD CONSTRAINT FK_DETAILS_PRODUITS_PRODUITS \n--FOREIGN KEY (REF_PRODUIT) REFERENCES FMACEROUSS.PRODUITS@EUROPE_SUD_LINK (REF_PRODUIT);\n\nALTER TABLE EMPLOYES ADD CONSTRAINT FK_EMPLOYES_EMPLOYES \nFOREIGN KEY (REND_COMPTE) REFERENCES EMPLOYES (NO_EMPLOYE);\n\n-- Tests de requettes\nselect * from clients;\nselect * from clients where pays in ('Bresil', 'Etats-Unis');\nselect * from clients_Amerique;\n\nSELECT * FROM GSARNETTE.FOURNISSEURS@EUROPE_NORD_LINK;\n\nselect * from gsarnette.clients_europe_nord@europe_nord_link;\n\nSELECT * FROM FMACEROUSS.PRODUITS@EUROPE_SUD_LINK;\n\n-- Vues materialisées\nCREATE MATERIALIZED VIEW LOG ON EMPLOYES;\nGRANT SELECT ON MLOG$_EMPLOYES TO gsarnette;\n\nCREATE MATERIALIZED VIEW Fournisseurs\nREFRESH COMPLETE\nNEXT sysdate + (1/24/60)\nAS \nSELECT *\nFROM GSARNETTE.FOURNISSEURS@EUROPE_NORD_LINK;\n\nCREATE MATERIALIZED VIEW Categories\nREFRESH COMPLETE\nNEXT sysdate + (1/24/60)\nAS \nSELECT *\nFROM fmacerouss.CATEGORIES@EUROPE_SUD_LINK;\n\nCREATE MATERIALIZED VIEW Produits\nREFRESH FAST\nNEXT sysdate + (1/24/60)\nAS SELECT *\nFROM fmacerouss.PRODUITS@EUROPE_SUD_LINK;\n" }, { "alpha_fraction": 0.5234131217002869, "alphanum_fraction": 0.5598335266113281, "avg_line_length": 16.77777862548828, "blob_id": "dbc10d5c74aaf74c07a51b8c0f1d6477931c6ddd", "content_id": "de3c8452105498a32dc7bd95a47692d5ffcbb34b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 961, "license_type": "permissive", "max_line_length": 83, "num_lines": 54, "path": "/TP2_Concurrency/question4.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <pthread.h>\n\nvoid print_prime_factors(uint64_t* n)\n{\n uint64_t i = 0;\n uint64_t nPrime = *n;\n printf(\"%ju: \", *n);\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime%i == 0)\n\t\t{\n\t\t\tnPrime = nPrime/i;\n\t\t\tprintf(\"%ju \", i);\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\r\\n\");\n}\n\nint main(void)\n{\n\t\tFILE* primeList;\n\t\tprimeList = fopen(\"primes.txt\", \"r\");\n\t\t\n\t\tpthread_t ta;\n\t\tpthread_t tb;\n\t\t\n\t\tif(primeList == NULL)\n\t\t{\n\t\t\tperror(\"erreur ouverture fichier\");\n\t\t\texit(-1);\n\t\t}\n\t\t\n\t\tchar line1[60];\n\t\tchar line2[60];\n\t\twhile(fgets(line1, 60, primeList) != NULL && fgets(line2, 60, primeList) != NULL)\n\t\t{\n\t\t\tuint64_t i1 = atoll(line1);\n\t\t\tuint64_t i2 = atoll(line2);\n\t\t\tpthread_create (&ta, NULL, print_prime_factors, &i1);\n\t\t\tpthread_create (&tb, NULL, print_prime_factors, &i2);\n\t\t\tpthread_join (ta, NULL);\n\t\t\tpthread_join (tb, NULL);\t\n\t\t}\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6283886432647705, "alphanum_fraction": 0.630577564239502, "avg_line_length": 32.365169525146484, "blob_id": "d0e30bc6d4114ce471662e4ce1475304358ccbc5", "content_id": "5e35571f9f726e0c3ba5f08dd6cdefc2898f5e78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5942, "license_type": "permissive", "max_line_length": 164, "num_lines": 178, "path": "/TP4_cpp/src/Utils.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\tUtils - A few common functions or types\n\t\t\t\t\t-----------------------------------------\n*********************************************************************************/\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#include <type_traits>\n#include <sstream>\n#include <string>\n\n#include <boost/serialization/vector.hpp>\n\n// On utilise la fonction intrinsèque __builtin_expect si disponnible\n#ifdef __GNUC__\n#define LIKELY(expr) __builtin_expect((bool)(expr), !0)\n#define UNLIKELY(expr) __builtin_expect((bool)(expr), 0)\n#else\n#define LIKELY(expr) expr\n#define UNLIKELY(expr) expr\n#endif\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\tinline std::vector<std::string> split(const std::string& str, char delim) {\n\t\tstd::stringstream ss(str);\n\t\tstd::string item;\n\t\tstd::vector<std::string> tokens;\n\n\t\twhile (getline(ss, item, delim))\n\t\t\ttokens.push_back(item);\n\n\t\treturn tokens;\n\t}\n\n\t// TODO: voir si il serais mieux de faire une structure binary op\n\ttemplate <typename T, typename U, typename = typename std::enable_if<!std::is_arithmetic<T>::value>::type>\n\tinline U mod(T a, T b) {\n\t\treturn a % b;\n\t}\n\n\ttemplate <typename UnsignedInteger, typename = typename std::enable_if<std::is_integral<UnsignedInteger>::value && std::is_unsigned<UnsignedInteger>::value>::type>\n\tconstexpr UnsignedInteger mod(UnsignedInteger a, UnsignedInteger b) {\n\t\treturn UNLIKELY(a >= b) ? a % b : a; // voir https://www.youtube.com/watch?v=nXaxk27zwlk&feature=youtu.be&t=3394\n\t}\n\n\ttemplate <typename Integer, typename = typename std::enable_if<std::is_integral<Integer>::value && std::is_signed<Integer>::value>::type, typename = void>\n\tconstexpr Integer mod(Integer a, Integer b) {\n\t\treturn UNLIKELY(a >= b || -a >= b) ? a % b : a;\n\t}\n\n\ttemplate <typename Floating, typename = typename std::enable_if<std::is_floating_point<Floating>::value>::type, typename = void, typename = void>\n\tinline Floating mod(Floating a, Floating b) {\n\t\treturn std::fmod(a, b); // TODO: benchmark this to see if \"UNLIKELY(a >= b || -a >= b) ? ... : a;\" could help.\n\t}\n}\n\n\nnamespace boost\n{\n\tnamespace serialization\n\t{\n\t\t//template<class Archive, class Allocator, class T>\n\t\t//inline void save(Archive& ar, const std::vector<std::unique_ptr<T>, Allocator>& vec, const unsigned int file_version)\n\t\t//{\n\t\t//\tauto count = vec.size();\n\t\t//\tar << BOOST_SERIALIZATION_NVP(count);\n\n\t\t//\tfor (const auto& elt : vec)\n\t\t//\t\tar << make_nvp(\"item\", elt);\n\t\t//}\n\n\t\t//template<class Archive, class Allocator, class T>\n\t\t//inline void load(Archive& ar, std::vector<std::unique_ptr<T>, Allocator>& vec, const unsigned int file_version)\n\t\t//{\n\t\t//\tdecltype(vec)::size_type count;\n\t\t//\tar >> BOOST_SERIALIZATION_NVP(count);\n\t\t//\tvec.clear();\n\t\t//\tvec.reserve(count);\n\n\t\t//\twhile (count-- != 0)\n\t\t//\t{\n\t\t//\t\tstd::unique_ptr<T> ptr;\n\t\t//\t\tar >> make_nvp(\"item\", ptr);\n\t\t//\t\tvec.emplace_back(std::move(ptr));\n\t\t//\t}\n\t\t//}\n\n\t\t//template<class Archive, class k, class V, class Comp, class MapAlloc>\n\t\t//inline void save(Archive& ar, const std::map<k, std::unique_ptr<V>, Comp, MapAlloc>& map, const unsigned int file_version)\n\t\t//{\n\t\t//\tauto count = map.size();\n\t\t//\tar << BOOST_SERIALIZATION_NVP(count);\n\n\t\t//\tfor (const auto& pair : map)\n\t\t//\t{\n\t\t//\t\tar << make_nvp(\"key\", pair.first);\n\t\t//\t\tar << make_nvp(\"value\", pair.second);\n\t\t//\t}\n\t\t//}\n\n\t\t//template<class Archive, class K, class V, class Comp, class MapAlloc>\n\t\t//inline void load(Archive& ar, std::map<K, std::unique_ptr<V>, Comp, MapAlloc>& map, const unsigned int file_version)\n\t\t//{\n\t\t//\tdecltype(map)::size_type count;\n\t\t//\tar >> BOOST_SERIALIZATION_NVP(count);\n\t\t//\tmap.clear();\n\n\t\t//\twhile (count-- != 0)\n\t\t//\t{\n\t\t//\t\tK key;\n\t\t//\t\tar >> make_nvp(\"key\", key);\n\t\t//\t\tstd::unique_ptr<V> value;\n\t\t//\t\tar >> make_nvp(\"value\", value);\n\t\t//\t\tmap[key] = std::move(value);\n\t\t//\t}\n\t\t//}\n\n\t\t//template<class Archive, class Allocator, class T>\n\t\t//inline void serialize(Archive& ar, std::vector<std::unique_ptr<T>, Allocator>& vec, const unsigned int file_version)\n\t\t//{\n\t\t//\tsplit_free(ar, vec, file_version);\n\t\t//}\n\n\t\t//template<class Archive, class K, class V, class Comp, class Allocator>\n\t\t//inline void serialize(Archive& ar, std::map<K, std::unique_ptr<V>, Comp, Allocator>& map, const unsigned int file_version)\n\t\t//{\n\t\t//\tboost::serialization::split_free(ar, map, file_version);\n\t\t//}\n\n\n\t\t//template<class Archive, class First, class Second>\n\t\t//inline void save_construct_data(Archive& ar, const std::pair<First, std::unique_ptr<Second>>* pair, const unsigned int file_version)\n\t\t//{\n\t\t//\t// Save data required to construct instance\n\t\t//\tusing non_const_first_t = typename std::remove_const<First>::type;\n\t\t//\tar\t<< boost::serialization::make_nvp(\"first\", const_cast<non_const_first_t &>(pair->first))\n\t\t//\t\t<< boost::serialization::make_nvp(\"second\", pair->second);\n\t\t//}\n\n\t\t//template<class Archive, class First, class Second>\n\t\t//inline void load_construct_data(Archive& ar, std::pair<First, std::unique_ptr<Second>>* pair, const unsigned int file_version)\n\t\t//{\n\t\t//\ttypename std::remove_const<First>::type first;\n\t\t//\tstd::unique_ptr<Second> second;\n\t\t//\tar\t>> boost::serialization::make_nvp(\"first\", first)\n\t\t//\t\t>> boost::serialization::make_nvp(\"second\", second);\n\n\t\t//\t// Invoke inplace constructor to initialize instance of std::pair\n\t\t//\t::new(pair) std::pair<First, std::unique_ptr<Second>>(std::move(first), std::move(second));\n\t\t//}\n\n\t\t/*template<class Archive, class First, class Second>\n\t\tinline void serialize(Archive& ar, std::pair<First, std::unique_ptr<Second>>& pair, const unsigned int file_version)\n\t\t{\n\n\t\t}*/\n\t}\n}\n\n//\n//namespace boost\n//{\n//\tnamespace serialization\n//\t{\n//\t\t// TODO: enlever ça?\n//\t\ttemplate<typename T, typename Archive>\n//\t\tvoid serialize(Archive& ar, std::unique_ptr<T>& g, const unsigned int version)\n//\t\t{\n//\t\t\tar & (*g);\n//\t\t}\n//\t}\n//}\n\n#endif // !UTILS_H\n" }, { "alpha_fraction": 0.6503923535346985, "alphanum_fraction": 0.6517623662948608, "avg_line_length": 29.645038604736328, "blob_id": "6c9aec2a8f181d0615464d9a782e7da2f83b4084", "content_id": "7a8dc0a84bf3e1e53c43515f26eca8e6603cc278", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8059, "license_type": "permissive", "max_line_length": 181, "num_lines": 262, "path": "/TP2_Reseaux/Server/src/Server/ClientConnection.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package Server;\n\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.Socket;\nimport java.util.List;\nimport java.util.UUID;\n\nimport shared.*;\n\n/**\n * Classe représentant une connexion vers un client.\n * La classe traite les requettes du client dans son propre thread.\n */\npublic class ClientConnection extends Thread {\n\n\t/**\n\t * Construit une connexion client à partir d'un socket lié au client, de l'id temporaire du client (j'usqu'a ce qu'il se connecte) et du serveur\n\t * @param socket Socket lié au client\n\t * @param temporaryId ID temporaire du client (sera changé si l'utilisateur se connecte avec un compte existant déjà)\n\t * @param server Classe principale du serveur permettant à la connexion de faire appel à celle-ci\n */\n\tClientConnection(Socket socket, UUID temporaryId, Server server) {\n\t\tm_server = server;\n\t\tm_socket = socket;\n\t\tm_user_id = temporaryId;\n\t}\n\n\t/**\n\t * Méthode fermant la connexion et quittant le thread de reception des requettes client.\n\t */\n\tpublic void close() {\n\t\ttry\n\t\t{\n\t\t\tif(m_socket != null)\n\t\t\t\tm_socket.close();\n\t\t\tif(m_os != null)\n\t\t\t\tm_os.close();\n\t\t\tif(m_oos != null)\n\t\t\t\tm_oos.close();\n\t\t\tif(m_is != null)\n\t\t\t\tm_is.close();\n\t\t\tif(m_ois != null)\n\t\t\t\tm_ois.close();\n\t\t} catch(IOException e) { }\n\t\tfinally \n\t\t{\n\t\t\tm_socket = null;\n\t\t\tm_os = null;\n\t\t\tm_oos = null;\n\t\t\tm_os = null;\n\t\t\tm_oos = null;\n\t\t}\n\t}\n\n\t/**\n\t * Méthode permmettant l'envoi d'une requette serveur vers le client associé à l'instance de la connexion client courante\n\t * @param request Requette serveur à envoyer au client\n */\n\tpublic void SendRequest(ServerRequest request) {\n\t\tif(m_oos != null) {\n\t\t\ttry {\n\t\t\t\tm_oos.writeObject(request);\n\t\t\t} catch (IOException e) {\n\t\t\t/* TODO: remove user from server? */\n\t\t\t\tclose();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Méthode initialisant la connexion (doit être appelée avant start())\n\t * @throws IOException\n */\n\tpublic void open() throws IOException {\n\t\tif(m_socket != null)\n\t\t{\n\t\t\tm_is = m_socket.getInputStream();\n\t\t\tm_ois = new ObjectInputStream(m_is);\n\t\t\tm_os = m_socket.getOutputStream();\n\t\t\tm_oos = new ObjectOutputStream(m_os);\n\t\t}\n\t}\n\n\t/**\n\t * Méthode exécutée dans un thread à par pour recevoir les requettes issue d'un client.\n\t * Pour démarer le thread executant cette méthode, il faut appeler la méthode start() après avoir appelé open().\n\t */\n\t@Override\n\tpublic void run() {\n\t\twhile(m_socket != null)\n\t\t{\n\t\t\tObject obj;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tobj = m_ois.readObject();\n\t\t\t} catch (ClassNotFoundException|IOException e) {\n\t\t\t\t/* TODO: remove user from server */\n\t\t\t\tclose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif(obj instanceof ClientRequest)\n\t\t\t{\n\t\t\t\ttry {\n\t\t\t\t\thandleIncommingRequest((ClientRequest)obj);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t/*TODO: handle...*/\n\t\t\t\t\tclose();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t\tclose();\n\t\t\t/*TODO: sleep?*/\n\t\t}\n\n\t\tm_server.on_user_disconnected(m_user_id, m_username, m_last_joined_group);\n\t}\n\n\t/**\n\t * Gère la réception d'une reuette en fonction du type de la requette issue du client\n\t * @param request requette du client à traiter\n\t * @throws IOException\n */\n\tprivate void handleIncommingRequest(ClientRequest request) throws IOException {\n\t\tswitch(request.type)\n\t\t{\n\t\tcase LOGIN:\n\t\t\tif(is_valid_data(request.data, String.class, String.class)) {\n\t\t\t\tString username = (String)request.data[0];\n\t\t\t\tString password = (String)request.data[1];\n\t\t\t\tif(password != null && username != null) {\n\t\t\t\t\tif(!password.equals(\"\") && !username.equals(\"\")) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tUUID pass = UUID.fromString(password);\n\t\t\t\t\t\t\tif(m_server.Login(username, pass, m_user_id)) {\n\t\t\t\t\t\t\t\tm_user_id = pass; // Update connection's id to be user password\n\t\t\t\t\t\t\t\tm_username = username;\n\t\t\t\t\t\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.LOGIN_SUCCESS, new User(pass, username)));\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (IllegalArgumentException e) { }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.LOGIN_ERROR));\n\t\t\tbreak;\n\t\tcase GROUP_CREATION:\n\t\t\tif(is_valid_data(request.data, User.class, String.class)) {\n\t\t\t\tUser user = (User)request.data[0];\n\t\t\t\tif(user.Id != null && m_user_id != null && user.Name != null && m_username != null) {\n\t\t\t\t\tif(user.Id.equals(m_user_id) && user.Name.equals(m_username)) {\n\t\t\t\t\t\tGroup new_group = m_server.CreateGroup(user, (String) request.data[1]);\n\t\t\t\t\t\tif (new_group != null) {\n\t\t\t\t\t\t\tm_last_joined_group = new_group;\n\t\t\t\t\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_CREATION_SUCCESS, new_group));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_CREATION_ERROR));\n\t\t\tbreak;\n\t\tcase GROUP_QUIT:\n\t\t\tif(is_valid_data(request.data, User.class, Group.class) && m_last_joined_group != null) {\n\t\t\t\tUser user = (User)request.data[0];\n\t\t\t\tGroup group = (Group)request.data[1];\n\t\t\t\tif(user.Id != null && m_user_id != null && user.Name != null && m_username != null) {\n\t\t\t\t\tif(user.Id.equals(m_user_id) && user.Name.equals(m_username) && m_last_joined_group.equals(group)) {\n\t\t\t\t\t\tif (m_server.QuitGroup(user, group)) {\n\t\t\t\t\t\t\tm_last_joined_group = null;\n\t\t\t\t\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_EXIT_SUCCESS));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_EXIT_ERROR));\n\t\t\tbreak;\n\t\tcase GROUP_JOIN:\n\t\t\tif(is_valid_data(request.data, User.class, Group.class) && m_last_joined_group == null)\n\t\t\t{\n\t\t\t\tUser user = (User)request.data[0];\n\t\t\t\tif(user.Id != null && m_user_id != null && user.Name != null && m_username != null) {\n\t\t\t\t\tif(user.Id.equals(m_user_id) && user.Name.equals(m_username)) {\n\t\t\t\t\t\tGroup joined_group = (Group)request.data[1];\n\t\t\t\t\t\tPair<String[], List<Message>> group_data = m_server.JoinGroup(user, joined_group);\n\t\t\t\t\t\tif(group_data != null && joined_group != null) {\n\t\t\t\t\t\t\tm_last_joined_group = joined_group;\n\t\t\t\t\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_JOIN_SUCCESS, joined_group, group_data.first, group_data.second.toArray(new Message[group_data.second.size()])));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_last_joined_group = null;\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.GROUP_JOIN_ERROR));\n\t\t\tbreak;\n\t\tcase GROUP_GETTER:\n\t\t\t// TODO: savoir si ça donne le tableau sous la forme d'un seul argument de la fonction variadic (constructeur de ServerRequest)\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.SEND_GROUP_LIST, m_server.GetGroups()));\n\t\t\tbreak;\n\t\tcase SEND_MESSAGE:\n\t\t\tif(is_valid_data(request.data, Message.class)) {\n\t\t\t\tMessage message = (Message)request.data[0];\n\t\t\t\tif(message.userName != null && m_username != null && m_last_joined_group != null) {\n\t\t\t\t\tif(message.userName.equals(m_username))\n\t\t\t\t\t\tm_server.SendMessageToGroup(new User(m_user_id, m_username), m_last_joined_group, message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CREATE_USERNAME:\n\t\t\tif(is_valid_data(request.data, String.class) && m_username == null)\n\t\t\t{\n\t\t\t\tString username = (String)request.data[0];\n\t\t\t\tif(m_server.CreateUser(username, m_user_id)) {\n\t\t\t\t\tm_username = username;\n\t\t\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.CREATE_USERNAME_SUCCESS, new User(m_user_id, m_username)));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_oos.writeObject(new ServerRequest(ServerRequest.Type.CREATE_USERNAME_ERROR));\n\t\t\tbreak;\n\t\tcase LOGOUT:\n\t\t\tclose();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate boolean is_valid_data(Object[] data, Class<?>... types) {\n\t\tif(data != null && types != null)\n\t\t{\n\t\t\tif(types.length == data.length)\n\t\t\t{\n\t\t\t\tfor(int idx = 0; idx < types.length; ++idx) {\n\t\t\t\t\tObject obj = data[idx];\n\t\t\t\t\tif(obj == null)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif(!types[idx].equals(obj.getClass()))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tUUID m_user_id;\n\tString m_username = null;\n\tGroup m_last_joined_group = null;\n\n\tServer m_server;\n\tSocket m_socket;\n\tObjectInputStream m_ois = null;\n\tObjectOutputStream m_oos = null;\n\tInputStream m_is = null;\n\tOutputStream m_os = null;\n}\n" }, { "alpha_fraction": 0.6315955519676208, "alphanum_fraction": 0.6345971822738647, "avg_line_length": 30.48756217956543, "blob_id": "26c82faf2ffc27659ef97a055dedaca6ca3629f5", "content_id": "65a0e49f4ce1851f391ffe4d27df4e6533209cfd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6334, "license_type": "permissive", "max_line_length": 132, "num_lines": 201, "path": "/TP3_cpp/includes/Utils.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\tUtils - A few common functions or types\n\t\t\t\t\t\t\t-----------------------------------------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#include <tuple>\n#include <string>\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//----------------------------------------------- Variadic template indexing utils\n\n\t//! Obtient le Nème type T issu du variadic template 'Args...'\n\ttemplate <size_t N, typename... Args>\n\tusing get_by_Index_t = typename std::tuple_element<N, std::tuple<Args...>>::type;\n\n\t//! Metafunction recursive obtenant l'indice du premier type T dans le variadic template 'Args...'\n\ttemplate <typename T, typename... Args>\n\tstruct index_of;\n\n\t//! Metafunction recursive obtenant l'indice du premier type T dans le variadic template 'Args...' (condition d'arret)\n\ttemplate <typename T, typename... Args>\n\tstruct index_of<T, T, Args...> : std::integral_constant<std::size_t, 0> { };\n\n\t//! Metafunction recursive obtenant l'indice du premier type T dans le variadic template 'Args...' (récursion)\n\ttemplate <typename T, typename Tail, typename... Args>\n\tstruct index_of<T, Tail, Args...> : std::integral_constant<std::size_t, 1 + index_of<T, Args...>::value> { };\n\n\t//---------------------------------------------------------------- Positive modulo\n\ttemplate<typename T>\n\tconstexpr T positive_mod(T a, T b)\n\t{\n\t\treturn ((a % b) + b) % b;\n\t}\n\n\t//----------------------------------------------------------------- Parse<T, bool>\n\t//TODO: add support for any integer base\n\n\t//! Fonction template convertissant une 'std::string' vers le type T\n\t//TODO: quel sens donner à 'strong_convertion' ici ?\n\ttemplate<typename T, bool strong_convertion = true>\n\tinline T parse(const std::string& str)\n\t{\n\t\treturn static_cast<T>(str);\n\t}\n\n\ttemplate<>\n\tinline float parse<float, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stof(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to float\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline float parse<float, false>(const std::string& str) { return std::stof(str); }\n\n\ttemplate<>\n\tinline double parse<double, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stod(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to double\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline double parse<double, false>(const std::string& str) { return std::stod(str); }\n\n\ttemplate<>\n\tinline long double parse<long double, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stold(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to long double\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline long double parse<long double, false>(const std::string& str) { return std::stold(str); }\n\n\ttemplate<>\n\tinline int parse<int, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stoi(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to int\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline int parse<int, false>(const std::string& str) { return std::stoi(str); }\n\n\t// TODO: improve range check ?\n\ttemplate<>\n\tinline unsigned int parse<unsigned int, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = static_cast<unsigned int>(std::stoul(str, &idx));\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to unsigned int\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline unsigned int parse<unsigned int, false>(const std::string& str) { return static_cast<unsigned int>(std::stoul(str)); }\n\n\t// TODO: improve range check ?\n\ttemplate<>\n\tinline short parse<short, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = static_cast<short>(std::stol(str, &idx));\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to short\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline short parse<short, false>(const std::string& str) { return static_cast<short>(std::stol(str)); }\n\n\t// TODO: improve range check ?\n\ttemplate<>\n\tinline unsigned short parse<unsigned short, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = static_cast<unsigned short>(std::stoul(str, &idx));\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to unsigned short\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline unsigned short parse<unsigned short, false>(const std::string& str) { return static_cast<unsigned short>(std::stoul(str)); }\n\n\ttemplate<>\n\tinline long parse<long, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stol(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to long\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline long parse<long, false>(const std::string& str) { return std::stol(str); }\n\n\ttemplate<>\n\tinline unsigned long parse<unsigned long, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stoul(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to unsigned long\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline unsigned long parse<unsigned long, false>(const std::string& str) { return std::stoul(str); }\n\n\ttemplate<>\n\tinline long long parse<long long, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stoll(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to long long\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline long long parse<long long, false>(const std::string& str) { return std::stoll(str); }\n\n\ttemplate<>\n\tinline unsigned long long parse<unsigned long long, true>(const std::string& str)\n\t{\n\t\tsize_t idx;\n\t\tauto val = std::stoull(str, &idx);\n\t\tif (idx != str.length())\n\t\t\tthrow std::invalid_argument(\"Given std::string cannot be converted to unsigned long long\");\n\t\treturn val;\n\t}\n\n\ttemplate<>\n\tinline unsigned long long parse<unsigned long long, false>(const std::string& str) { return std::stoull(str); }\n}\n\n#endif // UTILS_H\n\n" }, { "alpha_fraction": 0.6650485396385193, "alphanum_fraction": 0.708737850189209, "avg_line_length": 21.77777862548828, "blob_id": "d7a1c99128b10b1b7e5cf216aa88e07f1661e414", "content_id": "ef8ed43733627de3f0169000e6163b369fc4b6f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 206, "license_type": "permissive", "max_line_length": 63, "num_lines": 9, "path": "/TP3_Archi/Makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "testbench.vcd: testbench.o memory256x8.o processor.o reg8bits.o\n\tghdl -e testbench\n\tghdl -r testbench --vcd=testbench.vcd --stop-time=50ns\n\n%.o: %.vhdl\n\tghdl -a $^\n\nclean: \n\trm *.o testbench work-obj93.cf\n\n" }, { "alpha_fraction": 0.6897832751274109, "alphanum_fraction": 0.6904024481773376, "avg_line_length": 34.88888931274414, "blob_id": "72df8bae5ad6e9e91d9cfa08b3af626a9a3b4910", "content_id": "7273b69c10e513b99a7b57dce76973b7a5766c9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1615, "license_type": "permissive", "max_line_length": 181, "num_lines": 45, "path": "/TP4_cpp/src/Rectangle.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"rectangle.h\"\n\n#include <string>\n\n#include \"Utils.h\"\n#include \"optional.h\"\n\nnamespace TP4\n{\n\tstd::experimental::optional<Rectangle> make_rectangle(const Point top_left_corner, const Point bottom_right_corner)\n\t{\n\t\tif (top_left_corner.first >= bottom_right_corner.first || top_left_corner.second <= bottom_right_corner.second)\n\t\t\treturn std::experimental::nullopt;\n\t\treturn std::experimental::optional<Rectangle>(Rectangle(std::move(top_left_corner), std::move(bottom_right_corner)));\n\t}\n\n\tRectangle Move(const Rectangle& shape, coord_t dx, coord_t dy)\n\t{\n\t\tconst Point top_left{ shape.top_left_corner.first + dx, shape.top_left_corner.second + dy };\n\t\tconst Point bottom_right{ shape.bottom_right_corner.first + dx, shape.bottom_right_corner.second + dy };\n\n\t\treturn Rectangle(std::move(top_left), std::move(bottom_right));\n\t}\n\n\tbool Is_contained(const Rectangle& shape, Point point)\n\t{\n\t\tauto x = point.first;\n\t\tauto y = point.second;\n\n\t\treturn x >= shape.Get_top_left_corner().first \n\t\t\t&& x <= shape.Get_bottom_right_corner().first\n\t\t\t&& y <= shape.Get_top_left_corner().second\n\t\t\t&& y >= shape.Get_bottom_right_corner().second;\n\t}\n\n\tstd::ostream& operator<<(std::ostream& flux, const Rectangle& rect)\n\t{\n\t\tflux << \"{ (\" << rect.top_left_corner.first << \", \" << rect.top_left_corner.second << \"); (\" << rect.bottom_right_corner.first << \", \" << rect.bottom_right_corner.second << \") }\";\n\t\treturn flux;\n\t}\n\n\tRectangle::Rectangle(const Point&& top_left_corner, const Point&& bottom_right_corner)\n\t\t: top_left_corner(std::move(top_left_corner)), bottom_right_corner(std::move(bottom_right_corner))\n\t{ }\n}\n" }, { "alpha_fraction": 0.6166054010391235, "alphanum_fraction": 0.6259605884552002, "avg_line_length": 46.507938385009766, "blob_id": "4ce83c50f0fe1ea3f29a5a87dae5668127114aaa", "content_id": "44f2f4ddf3151679c03a3c105a64d70428ced946", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6037, "license_type": "permissive", "max_line_length": 181, "num_lines": 126, "path": "/TP2_cpp/includes/utils.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/************************************************************************************\n\t\t\t\t\t\t\tutils - Quelques outils communs\n\t\t\t\t\t\t\t---------------------------------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n************************************************************************************/\n\n#pragma once\n\n//------------------------------------------------------------------ Includes systeme\n#include <type_traits> // pour exploiter SFINAE et pour 'std::declval()'\n\n//--------------------------------------------------------------------------- Defines\n\n#ifdef __GNUC__ // We use __builtin_expect intrinsinc if available\n/// <summary> Permet de contrôler comment les branchages (if-else, ...) sont traduits en \n///\t\tassembleur en donnant pour information au compilateur le fait que l'expression\n///\t\tbooleenne 'expr' a plus de chances d'être vraie que fausse </summary>\n///\t<remarks> La macro utilisant des fonctions intrinsèques au compilateur, il est possible\n///\t\t, selon le compilateur utilisé, que cette macro soit sans éffets. </remarks>\n#define LIKELY(expr) __builtin_expect((bool)(expr), !0)\n/// <summary> Permet de contrôler comment les branchages (if-else, ...) sont traduits en \n///\t\tassembleur en donnant pour information au compilateur le fait que l'expression\n///\t\tbooleenne 'expr' a plus de chances d'être fausse que vraie </summary>\n///\t<remarks> La macro utilisant des fonctions intrinsèques au compilateur, il est possible\n///\t\t, selon le compilateur utilisé, que cette macro soit sans éffets. </remarks>\n#define UNLIKELY(expr) __builtin_expect((bool)(expr), 0)\n#else\n/// <summary> Permet de contrôler comment les branchages (if-else, ...) sont traduits en \n///\t\tassembleur en donnant pour information au compilateur le fait que l'expression\n///\t\tbooleenne 'expr' a plus de chances d'être vraie que fausse </summary>\n///\t<remarks> La macro utilisant des fonctions intrinsèques au compilateur, il est possible\n///\t\t, selon le compilateur utilisé, que cette macro soit sans éffets. </remarks>\n#define LIKELY(expr) expr\n/// <summary> Permet de contrôler comment les branchages (if-else, ...) sont traduits en \n///\t\tassembleur en donnant pour information au compilateur le fait que l'expression\n///\t\tbooleenne 'expr' a plus de chances d'être fausse que vraie </summary>\n///\t<remarks> La macro utilisant des fonctions intrinsèques au compilateur, il est possible\n///\t\t, selon le compilateur utilisé, que cette macro soit sans éffets. </remarks>\n#define UNLIKELY(expr) expr\n#endif\n\nnamespace TP2\n{\n\t//-------------------------------------------------------------------------------\n\t/// pair\n\t/// <summary> Simple classe représantant une paire d'objets de type différents </summary>\n\t//-------------------------------------------------------------------------------\n\ttemplate<typename T1, typename T2>\n\tstruct pair\n\t{\n\t\tpair() = default;\n\t\tpair(T1 f, T2 s) : first(f), second(s) { }\n\n\t\tT1 first;\n\t\tT2 second;\n\t};\n\n\t//------------------------------------------------------- Surcharges d'opérateurs\n\t/// <summary> Overload de l'opérateur '==' pour le type 'pair' </summary>\n\ttemplate<typename T1, typename T2>\n\tbool operator==(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs)\n\t{\n\t\treturn\n\t\t\tlhs.first == rhs.first &&\n\t\t\tlhs.second == rhs.second;\n\t}\n\n\t/// <summary> Overload de l'opérateur '!=' pour le type 'pair' </summary>\n\ttemplate<typename T1, typename T2>\n\tbool operator!=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) { return !(lhs == rhs); }\n\n\t//------------------------------------------------------------ Fonctions globales\n\n\t// enable ADL (following lines will use custom implementation of swap or std::swap if there isn't custom implementation)\n\tnamespace { using std::swap; }\n\n\t// Commenté car is_nothrow_swappable ne fonctionne pas avec gcc installé en IF\n\t/*\n\t\t// TODO: faire une fonction plus générique vérifiant la noexcept-itude pour toute fonctions spécifiée en paramètre (pas seulement swap)\n\t\t/// <summary> Metafonction permettant d'aider à vérifier si un ensemble de types disposent d'une fonction swap marquée noexcept </summary>\n\t\t/// <returns> Un booléen indiquant si les types passés en paramètre template peuvent être tous swapés en sécurité </returns>\n\t\ttemplate <typename Head, typename T, typename... Ts>\n\t\tconstexpr bool is_nothrow_swappable() {\n\t\t\treturn noexcept(swap(std::declval<Head&>(), std::declval<Head&>())) &&\n\t\t\t\tis_nothrow_swappable<T, Ts...>(); // Récursion\n\t\t}\n\n\t\ttemplate <typename T>\n\t\tconstexpr bool is_nothrow_swappable() {\n\t\t\treturn noexcept(swap(std::declval<T&>(), std::declval<T&>())); // Fin de la récursion\n\t\t}\n\t*/\n\n\t// Possible sans récursion avec 'noexcept( std::tuple<Ts...>->swap() )'\n\t// Egalement possibe avec le c++ 17 (fold expressions) :\n\t/*template <typename... Ts>\n\tconstexpr bool is_nothrow_swappable() {\n\t\treturn noexcept(swap(std::declval<T&>(), std::declval<T&>())) && ...;\n\t}*/\n\n\t// TODO: correct if n overflows ?\n\t/// <summary> Calcule la plus petite puissance de 2 supérieure à n (0 si n est négatif) </summary>\n\ttemplate <typename Integer, typename = typename std::enable_if<std::is_integral<Integer>::value && std::is_signed<Integer>::value>::type>\n\tinline Integer lowest_pow_of_two_greater_than(Integer n)\n\t{\n\t\t// see \"http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\"\n\t\tif (n < 0)\n\t\t\treturn 0;\n\t\t--n;\n\t\tfor (uint32_t pow = 1; pow < 8 * sizeof(Integer); pow *= 2)\n\t\t\tn |= n >> pow;\n\t\treturn n + 1;\n\t}\n\n\t/// <summary> Calcule la plus petite puissance de 2 supérieure à n </summary>\n\ttemplate <typename UnsignedInteger, typename = typename std::enable_if<std::is_integral<UnsignedInteger>::value && std::is_unsigned<UnsignedInteger>::value>::type, typename = void>\n\tinline UnsignedInteger lowest_pow_of_two_greater_than(UnsignedInteger n)\n\t{\n\t\t// see \"http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\"\n\t\t--n;\n\t\tfor (uint32_t pow = 1; pow < 8 * sizeof(UnsignedInteger); pow *= 2)\n\t\t\tn |= n >> pow;\n\t\treturn n + 1;\n\t}\n}\n" }, { "alpha_fraction": 0.4822334945201874, "alphanum_fraction": 0.4974619150161743, "avg_line_length": 12.133333206176758, "blob_id": "50f9581e1959f8ec39ee2efeaf8f0d920249c135", "content_id": "27a90716585ccba59d0b8cee58d60fd652160302", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 197, "license_type": "permissive", "max_line_length": 32, "num_lines": 15, "path": "/TD_Archi_cache/TD_cache_ex3.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"N.h\"\n\nint main()\n{\n\tdouble v[N][N];\n\tdouble sum = 0;\n\n\tfor(size_t j = 0; j < N; j++) {\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\tsum += v[i][j];\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6432279348373413, "alphanum_fraction": 0.6432279348373413, "avg_line_length": 22.544445037841797, "blob_id": "985ee50bb223a7bceb6f01de226d97ac76f102eb", "content_id": "4871a94e31ae57a6f908b1cea53863c4c89f2515", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2119, "license_type": "permissive", "max_line_length": 134, "num_lines": 90, "path": "/TP2_SI/services/src/main/java/metier/modele/Livreur.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage metier.modele;\nimport java.io.Serializable;\nimport javax.persistence.Id;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\n/**\n *\n * @author qvecchio\n */\n\n @Entity\n @Inheritance (strategy = InheritanceType.JOINED)\npublic abstract class Livreur implements Serializable{\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private Double longitude;\n private Double latitude;\n private boolean IsFree;\n private double poidMax; \n private String mail; \n\n public Livreur() {\n }\n \n public Livreur(Double longitude, Double latitude, boolean IsFree, double poidMax, String mail) {\n this.longitude = longitude;\n this.latitude = latitude;\n this.IsFree = IsFree;\n this.poidMax = poidMax;\n this.mail = mail;\n }\n\n public Long getId() {\n return id;\n }\n \n public Double getLongitude() {\n return longitude;\n }\n\n public void setLongitude(Double longitude) {\n this.longitude = longitude;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n public boolean getIsFree() {\n return IsFree;\n }\n\n public void setIsFree(boolean IsFree) {\n this.IsFree = IsFree;\n }\n\n public double getPoidMax() {\n return poidMax;\n }\n\n public void setPoidMax(int poidMax) {\n this.poidMax = poidMax;\n }\n\n public String getMail() {\n return mail;\n }\n\n public void setMail(String mail) {\n this.mail = mail;\n }\n \n @Override\n public String toString() {\n return \"Livreur{\" + \"longitude=\" + longitude + \", latitude=\" + latitude + \", IsFree=\" + IsFree + \", poidMax=\" + poidMax + '}';\n } \n}\n" }, { "alpha_fraction": 0.6108969449996948, "alphanum_fraction": 0.6114109754562378, "avg_line_length": 26.99280548095703, "blob_id": "06046013b958d8bd932f090b1728cb2a8199ac0c", "content_id": "b1fba75dc659d3f5982af9b69bd792390d1b5ed6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3895, "license_type": "permissive", "max_line_length": 139, "num_lines": 139, "path": "/TP2_SI/services/src/main/java/metier/modele/Commande.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage metier.modele;\n\nimport java.io.Serializable;\nimport java.util.Date;\nimport java.util.List;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Temporal;\nimport javax.persistence.Version;\n\n/**\n *\n * @author qvecchio\n */\n@Entity\npublic class Commande implements Serializable{\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n @Temporal(javax.persistence.TemporalType.TIMESTAMP)\n private Date dateDebut;\n @Temporal(javax.persistence.TemporalType.TIMESTAMP)\n private Date dateFin;\n @ManyToMany\n private List<ProduitCommande> contenues;\n @OneToOne\n private Client client;\n @OneToOne\n private Restaurant restaurant;\n @OneToOne\n private Livreur livreur;\n \n public Commande() {\n }\n\n public Commande(Client client, Restaurant restaurant, Livreur livreur, Date dateDebut, Date dateFin, List<ProduitCommande> contenues) {\n this.client = client;\n this.restaurant = restaurant;\n this.livreur = livreur;\n this.dateDebut = dateDebut;\n this.dateFin = dateFin;\n this.contenues = contenues;\n }\n \n public Commande(Client client, Restaurant restaurant, List<ProduitCommande> contenues) {\n this.client = client;\n this.restaurant = restaurant;\n this.livreur = null;\n this.dateDebut = null;\n this.dateFin = null;\n this.contenues = contenues;\n }\n\n public Long getId() {\n return id;\n }\n\n public Client getClient() {\n return client;\n }\n\n public void setClient(Client client) {\n this.client = client;\n }\n\n public Restaurant getRestaurant() {\n return restaurant;\n }\n\n public void setRestaurant(Restaurant restaurant) {\n this.restaurant = restaurant;\n }\n\n public Livreur getLivreur() {\n return livreur;\n }\n\n public void setLivreur(Livreur livreur) {\n this.livreur = livreur;\n }\n\n public Date getDateDebut() {\n return dateDebut;\n }\n\n public void setDateDebut(Date dateDebut) {\n this.dateDebut = dateDebut;\n }\n\n public Date getDateFin() {\n return dateFin;\n }\n\n public void setDateFin(Date dateFin) {\n this.dateFin = dateFin;\n }\n\n public List<ProduitCommande> getContenues() {\n return contenues;\n }\n\n public void setContenues(List<ProduitCommande> contenues) {\n this.contenues = contenues;\n }\n\n @Override\n public String toString() {\n if(contenues.isEmpty()) {\n return \"Commande vide\";\n } else {\n String str = \"Commande \" + id + \"\\n\";\n str += \"Livré par livreur n°\" + livreur.getId() + \"\\n\";\n Float poidT = new Float(0); \n Float prixT = new Float(0);\n str += \"Restaurant \" + restaurant.getDenomination() + \"\\n\";\n str += restaurant.getAdresse() + \"\\n\\n\";//Adresse \n str += \"A livrer chez \" + client.getNom() + \" \" + client.getPrenom() + \"\\n\" + client.getMail() + \"\\n\";\n str += \"Contenues de la commande : \\n\";\n for(ProduitCommande p : contenues) {\n str += \"\\t\" + p.getProduit().getDenomination() + \" : \" + p.getQuantite() + \"\\n\";\n poidT += p.getProduit().getPoids();\n prixT += p.getProduit().getPrix();\n }\n str += \"\\n\\n\";\n str += \"Prix totale de la commande : \" + prixT + \"€\\n\";\n str += \"Poids totale de la commande : \" + poidT + \"g\\n\";\n return str;\n }\n }\n}\n" }, { "alpha_fraction": 0.6942379474639893, "alphanum_fraction": 0.6998141407966614, "avg_line_length": 28.88888931274414, "blob_id": "2c060e473625c4acf1b55506668132d91b1d896d", "content_id": "d7df1eb08d4aca079aa65f22229b13d1a01f2d59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1077, "license_type": "permissive", "max_line_length": 102, "num_lines": 36, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/DAL/LocationDAL.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.DAL;\n\nimport java.util.List;\nimport javax.persistence.Query;\nimport javax.persistence.EntityManager;\n\nimport TP1_SI.metier.model.Location;\n\n/**\n * Data Access Layer permettant d'obtenir, de créer et modifier des instances de la classe 'Location'.\n * Utilise JPA pour persiter les Lieux.\n * @author B3330\n */\npublic class LocationDAL {\n\n public void create(Location location) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n em.persist(location);\n }\n\n public Location update(Location location) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.merge(location);\n }\n\n public Location findById(long id) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n return em.find(Location.class, id);\n }\n\n public List<Location> findAll() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n Query q = em.createQuery(\"SELECT l FROM Location l\");\n return (List<Location>) q.getResultList();\n }\n}\n" }, { "alpha_fraction": 0.5354902744293213, "alphanum_fraction": 0.5378012657165527, "avg_line_length": 29.595958709716797, "blob_id": "57c59e6ee275dabd5eb7bd8d4b72dc44a56f931d", "content_id": "e5270ae15a49556ff0752de4014ed8d9f78db60c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3038, "license_type": "permissive", "max_line_length": 101, "num_lines": 99, "path": "/TP1_SI/Projet/src/main/java/TP1_SI/Utils/ConsoleMenu.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package TP1_SI.Utils;\n\nimport java.io.InputStreamReader;\nimport java.io.BufferedReader;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Classe aidant à la création d'un menu sur console.\n * Un choix est ajouté au menu en fournissant un nom de l'option et une fonction à appeler\n * si cette option est choisie (class implémentant l'interface 'Callable').\n * @author B3330\n */\npublic class ConsoleMenu {\n\n /**\n * Constructeur de la classe 'ConsoleMenu'\n * @param menu_name nom du menu\n */\n public ConsoleMenu(String menu_name) {\n menu_choices = new HashMap<>();\n this.menu_name = menu_name;\n this.exit_function = null;\n }\n\n /**\n * Constructeur de la classe permmettant de specifier une fonction à appeler pour quitter le menu\n * @param menu_name nom du menu\n * @param exit_function fonction à appeler si l'utilisateur veux quitter le menu\n */\n public ConsoleMenu(String menu_name, Callable exit_function) {\n menu_choices = new HashMap<>();\n this.menu_name = menu_name;\n this.exit_function = exit_function;\n }\n\n /**\n * Ajoute un choix au menu\n * @param function fonction à appeler si le l'option est choisie\n * @param choice_name nom de l'option affiché dans le menu\n */\n public void addChoice(Callable function, String choice_name) {\n menu_choices.put(menu_choices.size(), new menu_choice(choice_name, function));\n }\n\n /**\n * Affiche le menu\n */\n public void runMenu() {\n while (true) {\n System.out.println(\"\\n############## \" + menu_name + \" ##############\");\n int i = 0;\n for (Map.Entry<Integer, menu_choice> entry : menu_choices.entrySet()) {\n System.out.println(\"\\t\" + i + \":\\t\" + entry.getValue().name);\n i++;\n }\n\n if(exit_function != null)\n System.out.println(\"\\t \\tType any other number to exit menu\");\n\n while(true)\n {\n int num = ConsoleUtils.lireInteger(\"Enter your choice: \");\n if(num >= menu_choices.size() || num < 0)\n {\n if(exit_function != null)\n {\n System.out.println();\n exit_function.call();\n return;\n }\n }\n else\n {\n menu_choice choice = menu_choices.get(num);\n System.out.println();\n choice.callback.call();\n break;\n }\n }\n }\n }\n\n private static class menu_choice\n {\n public menu_choice(String name, Callable callback)\n {\n this.name = name;\n this.callback = callback;\n }\n\n public String name;\n public Callable callback;\n }\n\n private HashMap<Integer, menu_choice> menu_choices;\n private Callable exit_function;\n private String menu_name;\n}\n" }, { "alpha_fraction": 0.5329784154891968, "alphanum_fraction": 0.5380064845085144, "avg_line_length": 41.78480911254883, "blob_id": "a1df58c5af3a995aa503144fc295f009c504d8fa", "content_id": "408304e9d8da35c8924af5f09e6983691bbdf9dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3422, "license_type": "permissive", "max_line_length": 120, "num_lines": 79, "path": "/TP3_cpp/includes/Log_parser.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\tLog_parser - An apache log parser\n\t\t\t\t\t\t----------------------------------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//----------------------- Interface de la classe Log_parser ----------------------\n#ifndef LOG_PARSER_H\n#define LOG_PARSER_H\n\n//-------------------------------------------------------------- Includes systèmes\n#include <memory>\n#include <string>\n#include \"optional.h\"\n\n//----------------------------------------------------------- Interfaces utilisées\n#include \"Graph.h\"\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//---------------------------------------------------------------------- Types\n\n\t//! Classe permettant de parser un log apache et d'en déduire, soit un graphe\n\t//! des requettes GET soit la liste des URLs utilisés dans ces requêtes\n\tclass Log_parser\n\t{\n\t\t//----------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//----------------------------------------------- Types et alias publiques\n\t\tusing hour_t = unsigned short;\n\t\tusing URL_t = std::string;\n\t\tusing graph_t = Graph<URL_t>;\n\t\tusing urls_scores_t = std::unordered_multimap<URL_t, unsigned int>;\n\n\t\t//----------------------------------------------------- Méthodes publiques\n\n\t\tvoid enable_hour_filter(hour_t hour);\n\t\tvoid disable_hour_filter();\n\t\tvoid enable_exclusion() noexcept;\n\t\tvoid disable_exclusion() noexcept;\n\n\t\t//! Parse le log donné en parametre pour trouver la liste des URLs utlisés\n\t\t//! lors de requêtes GET valides associés à leur nombre d'occurrences.\n\t\t//! @remarks\n\t\t//!\t\t- Si 'enable_hour_filter(hour_t)' a été appellé, les résultat ne comprendra\n\t\t//!\t\tque les requettes faites à l'heure spécifiée.\n\t\t//!\t\t- Si enable_exclusion() a été appellé, les résultat ne comprendra que les\n\t\t//!\t\trequettes qui ne concernent pas des fichier css, javascript ou des images.\n\t\t//! @throws std::invalid_argument if specified log file couldn't be read\n\t\tstd::unique_ptr<urls_scores_t> parse_urllist(const std::string& log_file_name) const;\n\n\t\t//! Parse le log donné en parametre pour en déduire le graphe des requêtes\n\t\t//! GET valides.\n\t\t//! @remarks\n\t\t//!\t\t- Si 'enable_hour_filter(hour_t)' a été appellé, les résultat ne comprendra\n\t\t//!\t\tque les requettes faites à l'heure spécifiée.\n\t\t//!\t\t- Si enable_exclusion() a été appellé, les résultat ne comprendra que les\n\t\t//!\t\trequettes qui ne concernent pas des fichier css, javascript ou des images.\n\t\t//! @throws std::invalid_argument if specified log file couldn't be read\n\t\tstd::unique_ptr<graph_t> parse_graph(const std::string& log_file_name) const;\n\n\t\t//------------------------------------------------------------------ PRIVE\n\tprivate:\n\t\t//------------------------------------------------------- Méthodes privées\n\n\t\t//! Fonction aidant à la lecture d'un log apache ligne par ligne\n\t\tvoid for_each_log_line(const std::string& log_file_name, const std::function<void(URL_t, URL_t)>& parsing_func) const;\n\n\t\t//------------------------------------------------------- Attributs privés\n\n\t\tbool m_is_exclusion_filter_enabled = false;\n\t\tstd::experimental::optional<hour_t> m_filter_hour = std::experimental::nullopt;\n\t};\n}\n\n#endif // LOG_PARSER_H\n\n" }, { "alpha_fraction": 0.6899224519729614, "alphanum_fraction": 0.6980823874473572, "avg_line_length": 27.172412872314453, "blob_id": "7c8888c76935ecdebad84d3e76cfc4e890cfbc5c", "content_id": "fe070040149c12089141a903b2b69dc20da6589f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2482, "license_type": "permissive", "max_line_length": 133, "num_lines": 87, "path": "/TP1_TP2_Reseau_rendu/VersionSocket/Shared/src/shared/ServerRequest.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package shared;\n\nimport java.io.Serializable;\n\n/**\n * Classe représentant une requette du serveur vers un client.\n * Cette classe est utilisée pour définir le protocole basé sur les sockets: la classe contient un attribut type indiquant\n * le type de requette faite et un tableau d'objets représentant les données associées à la requette (devant être serialisables).\n */\npublic class ServerRequest implements Serializable {\n\t/**\n\t * Enumération des types de requettes serveur\n\t */\n\tpublic enum Type {\n\t\tLOGIN_SUCCESS,\n\t\tLOGIN_ERROR,\n\t\tGROUP_CREATION_ERROR,\n\t\tGROUP_CREATION_SUCCESS,\n\t\tGROUP_JOIN_ERROR,\n\t\tGROUP_JOIN_SUCCESS,\n\t\tGROUP_EXIT_SUCCESS,\n\t\tGROUP_EXIT_ERROR,\n\t\tSEND_GROUP_LIST,\n\t\tSEND_MESSAGE,\n\t\tCREATE_USERNAME_ERROR,\n\t\tCREATE_USERNAME_SUCCESS,\n\t\tGROUP_LIST_UPDATED,\n\t\tGROUP_USER_LIST_UPDATED};\n\n\t/**\n\t * Constructeur initialisant la requette avec son type et les données qu'elle contient\n\t * @param request_type Le type de la requette serveur\n\t * @param values Les objets associés à la requette serveur\n\t */\n\tpublic ServerRequest(Type request_type, Object... values)\n\t{\n\t\ttype = request_type;\n\t\tdata = values;\n\t}\n\n\t/**\n\t * Constructeur initialisant la requette avec son type et sans données associées\n\t * @param request_type Le type de la requette serveur\n\t */\n\tpublic ServerRequest(Type request_type)\n\t{\n\t\ttype = request_type;\n\t\tdata = null;\n\t}\n\n\t/**\n\t * Vérifie l'égalitée (basée sur l'égalité du type et des objets contenus) entre l'objet donné en paramètre et l'instance courante.\n\t * @param other L'objet avec le quel l'instance courante est comparée.\n\t * @return Un booléen indiquant l'égalité\n\t */\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif(other instanceof ServerRequest) {\n\t\t\tServerRequest request = (ServerRequest)other;\n\t\t\tif(type.equals(request.type)) {\n\t\t\t\tif (data == null && request.data == null)\n\t\t\t\t\treturn true;\n\t\t\t\tif (data.length == request.data.length) {\n\t\t\t\t\tfor (int i = 0; i < data.length; ++i)\n\t\t\t\t\t\tif(data[i] != null) {\n\t\t\t\t\t\t\tif (!data[i].equals(request.data[i]))\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif(request.data[i] != null)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic final Type type;\n\tpublic final Object[] data;\n\n\t/**\n\t * Numéro identifiant la classe lors de la serialization (utilisé pour verifier la présence de la classe lors de la déserialization)\n\t */\n\tprivate static final long serialVersionUID = 5215608498221700206L;\n}\n" }, { "alpha_fraction": 0.5361724495887756, "alphanum_fraction": 0.5736067295074463, "avg_line_length": 25.788732528686523, "blob_id": "688e06655d0ea68bc72f982e5009bfe4097f5bc7", "content_id": "5921a845231af4b893c0faa4b5f5f3c354b20d13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9570, "license_type": "permissive", "max_line_length": 134, "num_lines": 355, "path": "/TP1_cpp_gcc/includes/tests.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\ttests.h - Unary tests for TP1::collection class\n\t\t\t\t\t-------------------------------------------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n#ifndef TESTS_H\n#define TESTS_H\n\n//------------------------------------------------------------------------ INCLUDE\n//---------------------------------------------------------------- Include système\n#include <iostream>\n#include <sstream> // utilisé uniquement std::cout pour rediriger la sortie de std::cout\n\n//----------------------------------------------------------- Interfaces utilisées\n#include \"collection.h\"\n\n//------------------------------------------------------------------------- USINGS\n// Using définissant le prototype d'une fonction de test\nusing TestFuncPtr = const char*(*)();\n\n//---------------------------------------------------------------------- FONCTIONS\n\n// Forward déclaration de la fonction statique d'aide 'string_cmp'\nstatic int string_cmp(const char* lhs, const char* rhs);\n\n// Description: Excecute une fonction de test donnée en paramètre\n//\t\ttestFunc: pointeur vers une fonction de test\n//\t\ttestName: nom optionel du test\nvoid test(TestFuncPtr testFunc, const char* testName = \"\")\n{\n\tstatic unsigned test_count = 0;\n\n\tif (testName[0] == '\\0' || testName == nullptr)\n\t\tstd::cout << std::endl << std::endl << \"### TEST \" << ++test_count << \" ###\" << std::endl;\n\telse\n\t\tstd::cout << std::endl << std::endl << \"### TEST \" << ++test_count << \" (\" << testName << \") ###\" << std::endl;\n\n\t// Create a std::stringstream to redirect std::cout output\n\tstd::stringstream buffer;\n\tstd::streambuf * old = std::cout.rdbuf(buffer.rdbuf());\n\n\tconst char* expected_str;\n\n\ttry {\n\t\t// Execute test function and get expected output\n\t\texpected_str = testFunc();\n\t}\n\tcatch (...) {\n\t\t// Restore previous std::cout output buffer\n\t\tstd::cout.rdbuf(old);\n\n\t\tstd::cout << \"FAILED : Throwed an exception!\";\n\t\treturn;\n\t}\n\n\t// Get real test output\n\tstd::string str = buffer.str();\n\tconst char* output = str.data();\n\n\t// Restore previous std::cout output buffer\n\tstd::cout.rdbuf(old);\n\n\t// See if test output is as expected\n\tif (string_cmp(output, expected_str) == 0)\n\t\tstd::cout << \"PASSED (OUTPUT = \\\"\" << output << \"\\\")\";\n\telse\n\t\tstd::cout << \"FAILED : wrong output (\\tEXPECTED =\\t\\\"\" << expected_str << \"\\\",\\n\\t\\t\\tOUTPUT =\\t\\\"\" << output << \"\\\")\" << std::endl;\n}\n\n//-------------------------------------------------------------------------- TESTS\n\n// Empêche l'optimization du compilateur pour ce test, si possible\n#ifdef __GNUC__\n#pragma GCC push_options\n#pragma GCC optimize (\"O0\")\n#elif _MSC_VER\n#pragma optimize(\"\", off)\n#endif\n\n// Description: test des constructeurs et du destructeur de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée \n//\t\t\test correcte\n//\t\tNOTE: L'optimization de ce test est désactivée car on ne veut pas que les objets\n//\t\t\tde type 'TP1::collection' soit enlevés car non utilisés.\nconst char* test_lifetime()\n{\n\t{\n\t\tTP1::dog dogsArray[3] = {\n\t\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\t\tTP1::dog(TP1::color::RED, 3),\n\t\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t\tTP1::collection dogs1(3);\n\t\tTP1::collection dogs2(dogsArray, 3);\n\t} // 'dogs1' and 'dogs2' destructors will be called here\n\n\tvolatile auto dogs = new TP1::collection(100);\n\tdelete dogs;\n\n\t// Return expected output\n\treturn \"\";\n}\n\n#ifdef __GNUC__\n#pragma GCC pop_options\n#elif _MSC_VER\n#pragma optimize(\"\", on)\n#endif\n\n// Description: test de la méthode afficher de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée\n//\t\t\test correcte\nconst char* test_afficher()\n{\n\tTP1::dog dogsArray[3] = {\n\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\tTP1::dog(TP1::color::RED, 3),\n\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t{ // Sub-test 1\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 2\n\t\tTP1::collection dogs(2);\n\t\tdogs.afficher();\n\t}\n\n\t// Return expected output\n\treturn\n\t\t\"({ 50, 3, 99 }, 3) \"\t// Sub-test 1\n\t\t\"({ }, 2)\";\t\t\t\t// Sub-test 2\n}\n\n// Description: test de la méthode ajuster de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée\n//\t\t\test correcte\nconst char* test_ajuster()\n{\n\tTP1::dog dogsArray[3] = {\n\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\tTP1::dog(TP1::color::RED, 3),\n\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t{ // Sub-test 1\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tstd::cout << dogs.ajuster(2) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 2\n\t\tTP1::collection dogs(5);\n\t\tstd::cout << dogs.ajuster(0) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 3\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tstd::cout << dogs.ajuster(10) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 4\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tdogs.ajuster(10);\n\t\tstd::cout << dogs.ajuster(4) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\t// Return expected output\n\treturn\n\t\t\"0 ({ 50, 3, 99 }, 3) \"\t\t// Sub-test 1\n\t\t\"1 ({ }, 0) \"\t\t\t\t// Sub-test 2\n\t\t\"1 ({ 50, 3, 99 }, 10) \"\t\t// Sub-test 3\n\t\t\"1 ({ 50, 3, 99 }, 4)\";\t// Sub-test 4\n}\n\n// Description: test de la méthode ajouter de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée\n//\t\t\test correcte\nconst char* test_ajouter()\n{\n\tTP1::dog dogsArray[3] = {\n\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\tTP1::dog(TP1::color::RED, 3),\n\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t{ // Sub-test 1\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tdogs.ajouter(TP1::dog(TP1::color::GREEN, 5));\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 2\n\t\tTP1::collection dogs(0);\n\t\tdogs.ajouter(TP1::dog(TP1::color::GREEN, 5));\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 3\n\t\tTP1::collection dogs(1);\n\t\tdogs.ajouter(TP1::dog(TP1::color::GREEN, 5));\n\t\tdogs.afficher();\n\t}\n\n\t// Return expected output\n\treturn\n\t\t\"({ 50, 3, 99, 5 }, 6) \"\t// Sub-test 1\n\t\t\"({ 5 }, 5) \"\t\t\t\t// Sub-test 2\n\t\t\"({ 5 }, 1)\";\t\t\t\t// Sub-test 3\n}\n\n// Description: test de la méthode retirer de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée\n//\t\t\test correcte\nconst char* test_retirer()\n{\n\tTP1::dog dogsArray[3] = {\n\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\tTP1::dog(TP1::color::RED, 3),\n\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t{ // Sub-test 1\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tstd::cout << dogs.retirer(nullptr, 0) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 2\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tstd::cout << dogs.retirer(dogsArray, 3) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 3\n\t\tTP1::collection dogs(dogsArray, 3);\n\t\tdogs.ajouter(TP1::dog(TP1::color::RED, 3));\n\t\tstd::cout << dogs.retirer(dogsArray[1]) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 4\n\t\tTP1::collection dogs(0);\n\t\tdogs.ajouter(TP1::dog(TP1::color::GREEN, 5));\n\t\tstd::cout << dogs.retirer(dogsArray, 3) << \" \";\n\t\tdogs.afficher();\n\t}\n\n\t// Return expected output\n\treturn\n\t\t\"0 ({ 50, 3, 99 }, 3) \"\t// Sub-test 1\n\t\t\"1 ({ }, 0) \"\t\t\t// Sub-test 2\n\t\t\"1 ({ 50, 99 }, 2) \"\t// Sub-test 3\n\t\t\"0 ({ 5 }, 1)\";\t\t\t// Sub-test 4\n}\n\n// Description: test de la méthode reunir de la classe TP1::collection\n//\t\tRETOURNE: la chaine de charactère qui devrait être affichée si la méthode testée\n//\t\t\test correcte\nconst char* test_reunir()\n{\n\tTP1::dog dogsArray[3] = {\n\t\tTP1::dog(TP1::color::GREEN, 50),\n\t\tTP1::dog(TP1::color::RED, 3),\n\t\tTP1::dog(TP1::color::BLUE, 99) };\n\n\t{ // Sub-test 1\n\t\tTP1::dog dogsArray2[2] = {\n\t\t\tTP1::dog(TP1::color::RED, 4),\n\t\t\tTP1::dog(TP1::color::YELLOW, 1) };\n\n\t\tTP1::collection dogs1(dogsArray, 3);\n\t\tTP1::collection dogs2(dogsArray2, 2);\n\t\tstd::cout << dogs1.reunir(dogs2) << \" \";\n\t\tdogs1.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 2\n\t\tTP1::collection dogs1(dogsArray, 3);\n\t\tTP1::collection dogs2(2);\n\t\tstd::cout << dogs1.reunir(dogs2) << \" \";\n\t\tdogs1.afficher();\n\t}\n\n\tstd::cout << \" \";\n\n\t{ // Sub-test 3\n\t\tTP1::collection dogs1(10);\n\t\tTP1::collection dogs2(dogsArray, 3);\n\t\tstd::cout << dogs1.reunir(dogs2) << \" \";\n\t\tdogs1.afficher();\n\t}\n\n\t// Return expected output\n\t// NOTE: Capacity of dogs1 after a 'dogs1.reunir(dogs2)' call must be 2 * (dogs1.m_size + dogs2.m_size)\n\t//\texcept if 'dogs1' have enought capacity to store 'dogs2' dogs (occurs in sub-test 2 and 3)\n\treturn\n\t\t\"1 ({ 50, 3, 99, 4, 1 }, 10) \"\t// Sub-test 1\n\t\t\"0 ({ 50, 3, 99 }, 3) \"\t\t\t// Sub-test 2\n\t\t\"1 ({ 50, 3, 99 }, 10)\";\t\t// Sub-test 3\n}\n\n//------------------------------------------------------------------------ STATIC\n\n// Description: Fonction permettant de comparer deux chaines de charactères\n//\t\tlhs: première chaîne de charactère comparée\n//\t\trhs: deuxième chaîne de charactère comparée\n//\t\tRETOURNE: un entier nul si les chaines sont égales, négatif si le premier \n//\t\t\tcharactère différent a une valeur inferieure dans lhs et un entier \n//\t\t\tpositif sinon.\nstatic int string_cmp(const char* lhs, const char* rhs)\n{\n\tconst unsigned char *str1 = (const unsigned char *)lhs;\n\tconst unsigned char *str2 = (const unsigned char *)rhs;\n\n\twhile (*str1 != '\\0') {\n\t\tif (*str2 == '\\0') return 1;\n\t\tif (*str2 > *str1) return -1;\n\t\tif (*str1 > *str2) return 1;\n\n\t\t++str1;\n\t\t++str2;\n\t}\n\n\t// Return -1 if 'str2' has more characters than 'str1'\n\tif (*str2 != '\\0')\n\t\treturn -1;\n\n\treturn 0;\n}\n\n#endif // TESTS_H\n" }, { "alpha_fraction": 0.5546528697013855, "alphanum_fraction": 0.5701624751091003, "avg_line_length": 41.57232666015625, "blob_id": "1ac94b50c1e7ccd4eb01adf20179b6f9d5ce82c5", "content_id": "4f82bf76f783b3def948cdd0e6d1db9d4a8d691a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6775, "license_type": "permissive", "max_line_length": 197, "num_lines": 159, "path": "/TP3_cpp/sources/Log_parser.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\tLog_parser - An apache log parser\n\t\t\t\t\t\t----------------------------------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//-------------------- Implémentation de la classe Log_parser --------------------\n\n//-------------------------------------------------------------- Includes systèmes\n#include <array>\n#include <regex>\n#include <string>\n#include <memory>\n#include <utility>\n#include <fstream>\n#include <iterator>\n#include \"optional.h\"\n\n//------------------------------------------------------------ Includes personnels\n#include \"Log_parser.h\"\n#include \"Graph.h\"\n#include \"Utils.h\"\n\nnamespace TP3\n{\n\t//------------------------------------------------------------------- STATIQUE\n\t//------------------------------------------------------------ Regex statiques\n\n\t//! Extentions to be ignored if media exclusion filter is enabled\n\tstatic const std::string EXCLUDED_EXTENTIONS = \"js|css|png|ogg|jpg|jpeg|bmp|raw|tiff|gif|ppm|pgm|pbm|pnm|webp|heif|bpgcd5|deep|ecw|fits|fits|flif|ILBM|IMG|Nrrd|PAM|PCX|PGF|PLBM|SGI|SID|TGA|VICAR\";\n\n\t//! Regex matching an IP (ipv4 or ipv6)\n\tstatic const std::string IP_REGEX = R\"regex((?:(?:[0-9]{1,3}\\.){3}|^(?:[0-9]{1,3}\\.){5})[0-9]{1,3})regex\";\n\t// static const std::string IP_REGEX_WEAK = R\"regex((?:(?:[0-9]+.)+))regex\";\n\n\t//! Regex matching a timestamp (sub-matches hour and GMT+...)\n\tstatic const std::string TIMESTAMP_REGEX = R\"regex((?:\\[[0-9]{1,2}\\/[A-Z][a-z]{2,3}\\/[0-9]{4}:([0-9]{1,2}):(?:[0-9]{1,2}:?){2} ((?:\\+|\\-)?[0-9]{4})\\]))regex\";\n\n\t//! Regex matching an absolute URL (submatches insa intranet domain name if any) (based on regex of 'stephenhay' in link bellow)\n\t//! @link https://mathiasbynens.be/demo/url-regex\n\tstatic const std::string ABSOLUTE_URL_REGEX = R\"regex(\"((?:((?:https?|ftp):\\/\\/intranet-if\\.insa-lyon\\.fr)|(?:(?:https?|ftp):\\/\\/[^\\s/$.?#].))[^\\s]*)\")regex\";\n\n\t//! Regex matching a GET request (submatches relative URL)\n\tstatic const std::string GET_REGEX = R\"regex(\"GET\\s+(\\/[^\\s]*)\\s+HTTPS?\\/[0-9]+.[0-9]+\")regex\";\n\tstatic const std::string GET_REGEX_E = R\"regex(\"GET\\s+(\\/[^\\s]*\\.(?:(?!)regex\" + EXCLUDED_EXTENTIONS + R\"regex(|\\s).)*)\\s+HTTPS?\\/[0-9]+.[0-9]+\")regex\";\n\n\t//! Regex matching data size number\n\tstatic const std::string SIZE_REGEX = R\"regex([0-9]+)regex\";\n\n\t//! Regex matching an apache log line with GET and 200 as status code (hour and URLs can be extracted (submatches))\n\t// C++14: utiliser les string literals \"...\"s\n\tstatic const std::regex LOG_LINE_REGEX = std::regex(\n\t\t R\"r(^\\s*)r\" + IP_REGEX + R\"regex(\\s+-\\s+-)regex\" // <IP> - -\n\t\t+ R\"r(\\s+)r\" + TIMESTAMP_REGEX\n\t\t+ R\"r(\\s+)r\" + GET_REGEX\n\t\t+ R\"regex(\\s+200\\s+[0-9]+)regex\" // status code = 200 followed by data size number\n\t\t+ R\"r(\\s+)r\" + ABSOLUTE_URL_REGEX\n\t\t+ R\"r(\\s+)r\" + R\"regex(\\\".+\\\"$)regex\", std::regex::icase | std::regex::optimize); // use '/i' flag in order to ignore case\n\n\t//! Regex matching an apache log line with GET and 200 as status code (hour and URLs can be extracted (submatches))\n\tstatic const std::regex LOG_LINE_REGEX_E = std::regex(\n\t\t R\"r(^\\s*)r\" + IP_REGEX + R\"regex(\\s+-\\s+-)regex\" // <IP> - -\n\t\t+ R\"r(\\s+)r\" + TIMESTAMP_REGEX\n\t\t+ R\"r(\\s+)r\" + GET_REGEX_E\n\t\t+ R\"regex(\\s+200\\s+[0-9]+)regex\" // status code = 200 followed by data size number\n\t\t+ R\"r(\\s+)r\" + ABSOLUTE_URL_REGEX\n\t\t+ R\"regex(\\s+)regex\" + R\"regex(\\\".+\\\"$)regex\", std::regex::icase | std::regex::optimize); // use '/i' flag in order to ignore case\n\n\tstatic const size_t LINE_MATCH_NUM = 0;\n\tstatic const size_t HOUR_MATCH_NUM = 1;\n\tstatic const size_t TIMEZONE_MATCH_NUM = 2;\n\tstatic const size_t GET_URL_MATCH_NUM = 3;\n\tstatic const size_t REFERER_MATCH_NUM = 4;\n\tstatic const size_t INSA_INTRANET_MATCH_NUM = 5;\n\n\t//--------------------------------------------------------------------- PUBLIC\n\t//--------------------------------------------------------- Méthodes publiques\n\n\tvoid Log_parser::enable_hour_filter(hour_t hour) { m_filter_hour = hour; }\n\tvoid Log_parser::disable_hour_filter() { m_filter_hour = std::experimental::nullopt; }\n\n\tvoid Log_parser::enable_exclusion() noexcept { m_is_exclusion_filter_enabled = true; }\n\tvoid Log_parser::disable_exclusion() noexcept { m_is_exclusion_filter_enabled = false; }\n\n\tstd::unique_ptr<Log_parser::urls_scores_t> Log_parser::parse_urllist(const std::string& log_file_name) const\n\t{\n\t\t// Multimap storing documents URLs with their occurrence number \n\t\tauto urls = std::unique_ptr<urls_scores_t>(new urls_scores_t()); // C++14: std::make_unique<urls_scores_t>();\n\t\t\t\n\t\tfor_each_log_line(std::move(log_file_name), [this, &urls](URL_t doc_url, URL_t referer_url)\n\t\t{\n\t\t\tauto url_it = urls->find(doc_url);\n\t\t\tif (url_it != std::end(*urls))\n\t\t\t\turl_it->second++;\n\t\t\telse\n\t\t\t\turls->emplace(std::move(doc_url), 1);\n\t\t});\n\n\t\treturn urls;\n\t}\n\n\tstd::unique_ptr<Log_parser::graph_t> Log_parser::parse_graph(const std::string& log_file_name) const\n\t{\n\t\tauto log_graph = std::unique_ptr<graph_t>(new graph_t()); // C++14: std::make_unique<graph_t>();\n\n\t\tfor_each_log_line(std::move(log_file_name), [this, &log_graph](URL_t doc_url, URL_t referer_url)\n\t\t{\n\t\t\tlog_graph->add_link(std::move(referer_url), std::move(doc_url));\n\t\t});\n\n\t\treturn log_graph;\n\t}\n\n\n\t//---------------------------------------------------------------------- PRIVE\n\t//----------------------------------------------------------- Méthodes privées\n\n\tvoid Log_parser::for_each_log_line(const std::string& log_file_name, const std::function<void(URL_t, URL_t)>& parsing_func) const\n\t{\n\t\tstd::string line;\n\t\tstd::ifstream infile(log_file_name);\n\n\t\tif (!infile.is_open())\n\t\t\tthrow std::invalid_argument(\"Invalid log file name or don't have reading right (can't open log)\");\n\n\t\twhile (std::getline(infile, line))\n\t\t{\n\t\t\tstd::smatch matches;\n\t\t\tif (std::regex_search(line, matches, (m_is_exclusion_filter_enabled ? LOG_LINE_REGEX_E : LOG_LINE_REGEX)))\n\t\t\t{\n\t\t\t\tif (m_filter_hour)\n\t\t\t\t{\n\t\t\t\t\tauto timezone = parse<int>(matches[TIMEZONE_MATCH_NUM].str()) / 100;\n\t\t\t\t\tauto hour = parse<hour_t>(matches[HOUR_MATCH_NUM].str());\n\t\t\t\t\tif (*m_filter_hour != static_cast<hour_t>(positive_mod(hour - timezone, 24)))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tauto doc_url = matches[GET_URL_MATCH_NUM].str();\n\t\t\t\tconst auto& intranet_match = matches[INSA_INTRANET_MATCH_NUM];\n\n\t\t\t\tif (intranet_match.matched)\n\t\t\t\t{\n\t\t\t\t\tauto referer_url = matches[REFERER_MATCH_NUM].str().substr(intranet_match.str().size());\n\t\t\t\t\tparsing_func(std::move(doc_url), referer_url);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tparsing_func(std::move(doc_url), matches[REFERER_MATCH_NUM].str());\n\t\t\t}\n\t\t}\n\n\t\tif (infile.bad())\n\t\t\tthrow std::invalid_argument(\"Error while reading log file\");\n\n\t\tinfile.close();\n\t}\n\n}\n\n" }, { "alpha_fraction": 0.5774040818214417, "alphanum_fraction": 0.6067270636558533, "avg_line_length": 26.93975830078125, "blob_id": "040c9507e6fb43f94f4b182849ff26fad58045d4", "content_id": "e13f9e77bb36d96020dd6f8d13e0c2033e1b1731", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2319, "license_type": "permissive", "max_line_length": 137, "num_lines": 83, "path": "/TP2_Concurrency/generator.cs", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#-*-mode:c-*-\n(echo \"#line 3 \\\"$0\\\"\";echo;tail -n +4 $0) >/tmp/cs.$$.c && gcc -Wall -o /tmp/cs.$$ /tmp/cs.$$.c && /tmp/cs.$$ $*;rm -f /tmp/cs.$$*; exit\n\n/*\n\nUsage: ./generator.cs QUANTITY MAGNITUDE REDUNDANCY\n\nGenerates an arbitraty QUANTITY of \"random\" numbers. Each number is\nscaled down to a certain binary MAGNITUDE (e.g. if you set this\nparameter to 10, then all your numbers will be smaller than 1024).\n\nThe script also include a REDUNDANCY parameter to artificially control\nthe \"variety\" of the results. Setting this value to 100 will cause all\nnumbers to be the same. Setting this value to 0 will cause all numbers\nto be really random (even though we make no attempt to eliminate\nfortuitous repetitions)\n\nYou should redirect the ouput in to a file, like in the examples below:\n\n ./generator.cs 50 32 0 > fifty_distinct_smallish_numbers.txt\n\n ./generator.cs 10 64 100 > one_large_number_repeated_ten_times.txt\n\n*/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\nint main(int argc, char *argv[])\n{\n uint64_t number ;\n uint32_t *word = (void*) &number ;\n uint64_t *previous_numbers;\n \n // how many numbers to generate\n int quantity = 20;\n if( argc > 1)\n quantity=atoi(argv[1]);\n\n // maximum magnitude of numbers, in bits (0..64)\n int magnitude= 64;\n if( argc > 2)\n magnitude=atoi(argv[2]);\n\n // percentage of redundancy (0..100)\n // 30% means each number only has 2/3 chance to be a brand new one\n int redundancy=50;\n if( argc > 3)\n redundancy=atoi(argv[3]);\n\n // we seed the the generator with a constant value so as to get\n // reproducible results.\n srandom(0);\n\n previous_numbers=malloc(quantity*sizeof(uint64_t));\n \n int i;\n for(i=0; i<quantity; i++)\n {\n if( i==0 || random() % 100 > redundancy)\n {\n // let's generate a new number\n word[0] = random();\n word[1] = random();\n \n // shift right to reduce magnitude\n number >>= 64-magnitude ;\n }\n else\n {\n // let's pick from previously generated numbers\n number = previous_numbers[ random() % i ];\n }\n \n previous_numbers[i] = number;\n printf(\"%ju\\n\",(intmax_t)number);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5038639903068542, "alphanum_fraction": 0.5316846966743469, "avg_line_length": 13.704545021057129, "blob_id": "378677306cde8ba4b64da82677a274a62e88f4d3", "content_id": "e0829c1129a562707c48a667060dc702351666e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 647, "license_type": "permissive", "max_line_length": 43, "num_lines": 44, "path": "/TP2_Concurrency/question2.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t i = 0;\n uint64_t nPrime = n;\n printf(\"%ju: \", n);\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime%i == 0)\n\t\t{\n\t\t\tnPrime = nPrime/i;\n\t\t\tprintf(\"%ju \", i);\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\r\\n\");\n}\n\nint main(void)\n{\n\t\tFILE* primeList;\n\t\tprimeList = fopen(\"primes2.txt\", \"r\");\n\t\t\n\t\tif(primeList == NULL)\n\t\t{\n\t\t\tperror(\"erreur ouverture fichier\");\n\t\t\texit(-1);\n\t\t}\n\t\t\n\t\tchar line[60];\n\t\twhile(fgets(line, 60, primeList) != NULL)\n\t\t{\n\t\t\tprint_prime_factors(atoll(line));\n\t\t}\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6250950694084167, "alphanum_fraction": 0.6395437121391296, "avg_line_length": 34.5405387878418, "blob_id": "6d6657b8ccb4cc82c9f2a8073121e6c5e41a8944", "content_id": "0d1c5a5c7b78fca550382182f7048cbee606a0a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "permissive", "max_line_length": 108, "num_lines": 37, "path": "/TP1_Probas/ResultAnalysis.py", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "from ggplot import *\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom io import StringIO\nimport warnings\nimport subprocess\nwarnings.filterwarnings(\"ignore\")\n\ndef bitfield(n, size):\n if n >= 0:\n bits = np.array([int(digit) for digit in bin(n)[2:]])\n return np.lib.pad(bits, (size - int(n).bit_length(), 0), 'constant', constant_values=(0, 0))\n else:\n n += 1\n inverted = [-int(digit) + 1 for digit in bin(n)[3:]]\n inverted = np.lib.pad(inverted, (size - int(n).bit_length(), 0), 'constant', constant_values=(1, 1))\n return inverted\n\ndef plot_bit_sequence_fft(data, bits_count):\n # use ggplot style sheet\n from matplotlib import style\n style.use('ggplot')\n # Get bit sequence fft and plot it using matplot lib\n bitset = np.array([float(2 * b - 1) for d in data for b in bitfield(d, bits_count)])\n t = np.arange(bitset.size)\n sp = np.fft.fft(bitset)\n freq = np.fft.fftfreq(t.shape[-1])\n sp[0] = 0 # remove 0's high value\n plt.suptitle('Spectral test (DFT of monobit sequence)', fontsize = 16)\n plt.xlabel('frequency')\n plt.ylabel('amplitude')\n plt.plot(freq, sp.real, freq, sp.imag)\n plt.show()#Spectral Test\n \ndef width(data, bins):\n return abs((max(data['values']) - min(data['values']))/bins)\n" }, { "alpha_fraction": 0.741542637348175, "alphanum_fraction": 0.748308539390564, "avg_line_length": 32.54545593261719, "blob_id": "fae7704e27537a8933ae737051a2b62d06e6e2b8", "content_id": "e17946ae28c513903c88abd7413ab988720a3cd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 742, "license_type": "permissive", "max_line_length": 100, "num_lines": 22, "path": "/TP1_Probas/ProgrammeC/Makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "OBJ = mersenne_twister.o aes.o von_neumann.o file_attente.o lois_distributions.o random_generation.o\n\nsimu: main.c $(OBJ)\n\tgcc -Wall -std=c99 -pedantic -o simul -lm main.c $(OBJ)\n\n.PHONY: all clean rebuild\n\n# Ces 2 lignes définissent la méthode de création d'un .o\n.SUFFIXES: .o\n\n.c.o:; gcc -Wall -std=c99 -pedantic -c -o $@ -lm $<\naes.o: aes.h aes.c\nmersenne_twister.o: mersenne_twister.h mersenne_twister.c\nvon_neumann.o: von_neumann.h von_neumann.c\nfile_attente.o: file_attente.h file_attente.c lois_distributions.h\nlois_distributions.o: lois_distributions.h lois_distributions.c random_generation.h\nrandom_generation.o: random_generation.h random_generation.c von_neumann.h mersenne_twister.h\n\nclean:\n\trm *.o simu\n\nrebuild: clean all\n\n" }, { "alpha_fraction": 0.6835371851921082, "alphanum_fraction": 0.6840041279792786, "avg_line_length": 32.15480041503906, "blob_id": "2e1ad57a1ba85d362d1a6c4e91f6b333ce6ce0a3", "content_id": "f0a16b7bae641cedd54e6804c743b5b1c6801985", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10765, "license_type": "permissive", "max_line_length": 184, "num_lines": 323, "path": "/TP1_TP2_Reseau_rendu/VersionSocket/Server/src/Server/Server.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package Server;\n\nimport java.net.ServerSocket;\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.util.*;\n\nimport shared.*;\n\n/**\n * Classe principale du serveur.\n * La classe Server permet de gèrer les connexions entrantes des clients, gèrer les comptes, gèrer les groupes/rooms et distribuer les messages dans ces groupes.\n * Server utilise également la classe storageDAL pour enregister son état (utilisateurs, groupes et messages) et pouvoir le charger au lancement du serveur.\n */\npublic class Server {\n\n\t/**\n\t * Point d'entrée du programme côté serveur (lance le serveur).\n */\n\tpublic static void main(String[] args) {\n\t\tfinal int PORT = 1001;\n\t\tServer server = new Server(PORT, \"./\");\n\t\tSystem.out.println(\"Starting server on port: \" + PORT);\n\n\t\t// Make sure to dispose server on application shutdown\n\t\tRuntime.getRuntime().addShutdownHook(new Thread() {\n\t\t\tpublic void run() {\n\t\t\t\tif(server != null)\n\t\t\t\t\tserver.dispose();\n\t\t\t}\n\t\t});\n\n\t\t// Loop to accept new client connections\n\t\twhile(true)\n\t\t\tserver.AcceptConnection();\n\t}\n\n\t/**\n\t * Construit un Server à partir d'un numéro de port et du chemin du dossier dans le quel l'état du serveur est stocké.\n\t * @param port Numéro de port sur le quel lancer le serveur\n\t * @param storage_directory chemin du dossier dans le quel l'état du serveur est stocké\n */\n\tpublic Server(int port, String storage_directory) {\n\t\tm_port = port;\n\t\tm_client_connections = new HashMap<>();\n\t\tm_groups = new HashMap<>();\n\t\tm_messages = new HashMap<>();\n\t\tm_usernames = new HashMap<>();\n\t\tm_server_socket = null;\n\t\tm_storage = new StorageDAL(storage_directory, e -> {\n\t\t\t// TODO: handle exceptions\n\t\t});\n\n\t\t// Read stored user accounts, groups and messages if any\n\t\tList<User> users = m_storage.GetStoredUsers();\n\t\tMap<Group, List<Message>> groups_with_messages = m_storage.GetStoredGroups();\n\t\tif(users != null) {\n\t\t\t// Load users\n\t\t\tfor(User user : users) {\n\t\t\t\tif(user != null)\n\t\t\t\t\tm_usernames.put(user.Id, user.Name);\n\t\t\t}\n\t\t\tSystem.out.println(\"Loaded \" + users.size() + \" user account(s).\");\n\n\t\t\t// Load groups and messages\n\t\t\tif(groups_with_messages != null) {\n\t\t\t\tgroups_with_messages.forEach((group, messages) -> {\n\t\t\t\t\tif(group != null) {\n\t\t\t\t\t\tm_groups.put(group, new HashSet<>());\n\t\t\t\t\t\tif(messages != null)\n\t\t\t\t\t\t\tm_messages.put(group, messages);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tm_messages.put(group, new ArrayList<>());\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tSystem.out.println(\"Loaded \" + groups_with_messages.size() + \" group(s).\");\n\t\t\t}\n\t\t}\n\n\t\t// Make storage DAL ready to append objects to history\n\t\tm_storage.InitStorageWriting();\n\t}\n\n\t/**\n\t * Attend une connexion de la part d'un client et crée un nouvel objet de type ClientConnexion si un client se connecte (et démare son thread de traitement des requettes client)\n\t */\n\tpublic void AcceptConnection() {\n\t\ttry {\n\t\t\tif(m_server_socket == null)\n\t\t\t\tm_server_socket = new ServerSocket(m_port);\n\t\t\tSocket socket_to_client = m_server_socket.accept();\n\t\t\tif(socket_to_client != null)\n\t\t\t{\n\t\t\t\tUUID temporary_id = UUID.randomUUID();\n\t\t\t\tClientConnection new_connection = new ClientConnection(socket_to_client, temporary_id, this);\n\t\t\t\tnew_connection.open();\n\t\t\t\tnew_connection.start();\n\t\t\t\tm_client_connections.put(temporary_id, new_connection);\n\t\t\t\tSystem.out.println(\"Client connected\");\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\t// TODO: handle except.\n }\n\t}\n\n\t/**\n\t * Coupe toutes les connexions client et ferme le serveur.\n\t * @throws Throwable\n */\n\t@Override\n\tpublic void finalize() throws Throwable {\n\t\tsuper.finalize();\n\t\tdispose();\n\t}\n\n\t/**\n\t * Coupe toutes les connexions client et ferme le serveur\n\t */\n\tpublic void dispose() {\n\t\tSystem.out.println(\"Disposing server...\");\n\n\t\t// Close client connections\n\t\tif(m_client_connections != null) {\n\t\t\tm_client_connections.forEach((uuid, clientConnection) -> {\n\t\t\t\tif(clientConnection != null)\n\t\t\t\t\tclientConnection.close();\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tif(m_server_socket != null)\n\t\t\t\tm_server_socket.close();\n\t\t} catch (IOException e) { }\n\n\t\tif(m_storage != null)\n\t\t\tm_storage.CloseStorage();\n\n\t\tm_server_socket = null;\n\t\tm_storage = null;\n\t}\n\n\t/**\n\t * Gère la déconnexion d'un client (appelé par les ClientConexion)\n\t * @param user_id Id du client\n\t * @param username Eventuel nom de l'utilisateur\n\t * @param group Eventuel groupe dans lequel est l'utilisateur\n */\n\tpublic void on_user_disconnected(UUID user_id, String username, Group group) {\n\t\t// Remove user from its group if necessary\n\t\tQuitGroup(new User(user_id, username), group);\n\t\t// Remove user connection\n\t\tif(m_client_connections.remove(user_id) != null)\n\t\t\tSystem.out.println(\"Client disconnected\");\n\n\t}\n\n\t/**\n\t * Crée un nouvel utilisateur si les paramètres sont corrects (noms d'utilisateur et id unique)\n\t * @param username Nom de l'utilisateur\n\t * @param id Id de l'utilisateur\n * @return un booléen indiquant si l'utilisateur a effectivement été crée\n */\n\tpublic boolean CreateUser(String username, UUID id) {\n\t\tif(username != null)\n\t\t\tif(!username.equals(\"\"))\n\t\t\t\tif(!m_usernames.containsValue(username))\n\t\t\t\t\tif(m_usernames.putIfAbsent(id, username) == null) {\n\t\t\t\t\t\tm_storage.AppendUser(new User(id, username));\n\t\t\t\t\t\tSystem.out.println(\"New user created: \" + username);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Vérifie la validité du nom d'utilisateur et de son mots de passe (Id) et modifie l'id temporaire de la connexion pour être l'id de l'utilisateur si les informations sont correctes.\n\t * @param username Nom de l'utilisateur\n\t * @param password Mots de passe de l'utilisateur\n\t * @param connection_temporary_id Id temporaire de la connexion client\n * @return un booléen indiquant que les informatiuons sont correctes (utilisateur loggé)\n */\n\tpublic boolean Login(String username, UUID password, UUID connection_temporary_id) {\n\t\tif(password != null && username != null) {\n\t\t\tif(!username.equals(\"\")) {\n\t\t\t\tString pass_username = m_usernames.get(password);\n\t\t\t\tif(pass_username != null) {\n\t\t\t\t\tif (pass_username.equals(username)) {\n\t\t\t\t\t\t// Update key/password associated with user connection according to user credentials\n\t\t\t\t\t\tClientConnection connection = m_client_connections.remove(connection_temporary_id);\n\t\t\t\t\t\tm_client_connections.put(password, connection);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Crée un groupe si il n'y a pas d'autre groupe ayant le même nom\n\t * @param creator Créateur du groupe (utilisateur)\n\t * @param name Nom du groupe à créer\n * @return le groupe crée ou null si le groupe n'a pas été crée\n */\n\tpublic Group CreateGroup(User creator, String name) {\n\t\tGroup new_group = new Group(new Date(), name);\n\t\tif (!m_groups.containsKey(new_group) && !name.isEmpty())\n\t\t{\n\t\t\tHashSet<User> users = new HashSet<>();\n\t\t\tusers.add(creator);\n\t\t\tm_groups.put(new_group, users);\n\t\t\tm_messages.put(new_group, new ArrayList<>());\n\t\t\tm_storage.AppendGroup(new_group);\n\t\t\tSystem.out.println(\"New group created: \" + name);\n\n\t\t\t// Update group list for every client\n\t\t\tm_client_connections.forEach((uuid, clientConnection) -> {\n\t\t\t\tServerRequest request = new ServerRequest(ServerRequest.Type.GROUP_LIST_UPDATED, new_group);\n\t\t\t\tclientConnection.SendRequest(request);\n\t\t\t});\n\n\t\t\treturn new_group;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Permet à un utilisateur de rejoindre un groupe (si il n'est pas dejà dans un groupe et que le groupe est valide).\n\t * @param user Utilisateur voulant joindre le groupe\n\t * @param group Groupe à rejoindre\n * @return Les utilisateurs du groupe ainsi que l'historique des messages si l'utilisateur a effectivement rejoint le groupe (retourne null sinon)\n */\n\tpublic Pair<String[], List<Message>> JoinGroup(User user, Group group) {\n\t\tif(user != null && group != null) {\n\t\t\t// Add user to specified group if we can find it (we suppose user is correct)\n\t\t\tHashSet<User> group_users = m_groups.get(group);\n\t\t\tif(group_users != null)\n\t\t\t\tif(group_users.add(user)) {\n\t\t\t\t\tString[] usernames = new String[group_users.size()];\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor(User group_user : group_users) {\n\t\t\t\t\t\tusernames[i] = group_user.Name;\n\t\t\t\t\t\t++i;\n\n\t\t\t\t\t\t// Update group's user list for every users in this group\n\t\t\t\t\t\tServerRequest request = new ServerRequest(ServerRequest.Type.GROUP_USER_LIST_UPDATED, true, user.Name);\n\t\t\t\t\t\tm_client_connections.get(group_user.Id).SendRequest(request);\n\t\t\t\t\t}\n\t\t\t\t\treturn new Pair<>(usernames, m_messages.get(group));\n\t\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Permet à un utilisateur de quitter un groupe\n\t * @param user Utilisateur voulant quitter le groupe\n\t * @param group Groupe à quitter\n * @return Un booléen indiquant si le groupe a bien été quittté\n */\n\tpublic boolean QuitGroup(User user, Group group) {\n\t\tif(user != null && group != null) {\n\t\t\tHashSet<User> group_users = m_groups.get(group);\n\t\t\tif(group_users != null) {\n\t\t\t\tif (group_users.remove(user))\n\t\t\t\t{\n\t\t\t\t\t// Update group's user list for every users in this group\n\t\t\t\t\tfor (User group_user : group_users) {\n\t\t\t\t\t\tServerRequest request = new ServerRequest(ServerRequest.Type.GROUP_USER_LIST_UPDATED, false, user.Name);\n\t\t\t\t\t\tm_client_connections.get(group_user.Id).SendRequest(request);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Envoi un message donné en paramètre à tout les utilisateur d'un groupe (si possible et si l'auteur appartient bien au groupe).\n\t * @param user Utilisateur ayant envoyé le message\n\t * @param group Groupe dans lequel envoyer le message\n\t * @param message Message à envoyer\n */\n\tpublic void SendMessageToGroup(User user, Group group, Message message){\n\t\tServerRequest request = new ServerRequest(ServerRequest.Type.SEND_MESSAGE, message);\n\t\tHashSet<User> group_users = m_groups.get(group);\n\t\t\n\t\tif(!group_users.contains(user))\n\t\t\treturn; // TODO: user trying to send message to other groups (disconnect user?)\n\n\t\t// Store message to history\n\t\tm_messages.get(group).add(message);\n\t\tm_storage.AppendMessage(group, message);\n\n\t\t// Send message to every group users\n\t\tfor(User group_user : group_users) {\n\t\t\tClientConnection connection = m_client_connections.get(group_user.Id);\n\t\t\tif(connection != null)\n\t\t\t\tconnection.SendRequest(request);\n\t\t\t//else\n\t\t\t\t// TODO: uh oh ! (logout user ?)\n\t\t}\n\t}\n\n\t/**\n\t * Obtient la liste de tous les groupe crées\n\t * @return La liste de tous les groupe crées\n */\n\tpublic Group[] GetGroups() {\n\t\tGroup[] groups = new Group[m_groups.size()];\n\t\treturn m_groups.keySet().toArray(groups);\n\t}\n\n\tprivate HashMap<UUID, ClientConnection> m_client_connections;\n\tprivate HashMap<Group, List<Message>> m_messages;\n\tprivate HashMap<Group, HashSet<User>> m_groups;\n\tprivate HashMap<UUID, String> m_usernames;\n\n\tprivate final int m_port;\n\tprivate StorageDAL m_storage;\n\tprivate ServerSocket m_server_socket;\n}\n" }, { "alpha_fraction": 0.752109706401825, "alphanum_fraction": 0.7563291192054749, "avg_line_length": 36.91999816894531, "blob_id": "cab5047ec97e3e3b18bee5b5ba8b293d33feccf9", "content_id": "db0d63c181d3f7e1d2dcfef1572ef84f048daf88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 963, "license_type": "permissive", "max_line_length": 121, "num_lines": 25, "path": "/TP1_SI/Readme.md", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "WINDOWS-1252", "text": "COLLECT'IF\n========\n\n<img src=\"http://i.imgur.com/yPqRj5g.png\" alt=\"Collect'if Logo\" width=\"250\"/>\n\nDescription\n--------\n\nVous souhaitez faire une partie de tarot jeudi prochain ? Un match de volley le samedi de la \nsemaine prochaine ? COLLECT’IF, l'association évenementielle locale, vous trouve des \nco-équipiers et met à votre disposition un local pour votre rencontre. \n\nArchitechture générale du projet\n--------\n\n* Le répertoire contient un dossier GUI_Prototype regroupant les maquettes d'interface graphique Web (desktop et mobile).\n* Le fichier '_CollectifData.sql' contient des données d'exemple pour la base de donnée SQL\n* Le dossier 'Projet' contient le projet Maven constitué du code JAVA des services et de l'IHM sur console\n* Le dossier 'BDD' contient la base de données SQL utilisée pour la persistance des objets de l'application\n* Le dossier 'Docs' Contient une documentation plus détaillée du projet\n\nDocumentation\n--------\n\n...\n" }, { "alpha_fraction": 0.6934782862663269, "alphanum_fraction": 0.6934782862663269, "avg_line_length": 27.75, "blob_id": "53ae1402334a421e7c2659a3e69908d42707ccd3", "content_id": "0e91ab5068d5e7eb0a234e11613d361dac6bd479", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 920, "license_type": "permissive", "max_line_length": 77, "num_lines": 32, "path": "/TP2_SI/services/src/main/java/dao/LivreurCyclisteDao.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package dao;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport metier.modele.LivreurCycliste;\n\n/**\n * @author quentinvecchio\n */\npublic class LivreurCyclisteDao {\n\n public void create(LivreurCycliste livreur) throws Throwable {\n EntityManager em;\n em = JpaUtil.obtenirEntityManager();\n em.persist(livreur);\n }\n\n public LivreurCycliste update(LivreurCycliste livreur) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n livreur = em.merge(livreur);\n return livreur;\n }\n\n public List<LivreurCycliste> findAll() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n List<LivreurCycliste> livreurs = null;\n Query q = em.createQuery(\"SELECT l FROM Livreur l\");\n livreurs = (List<LivreurCycliste>) q.getResultList();\n return livreurs;\n }\n}\n" }, { "alpha_fraction": 0.586928129196167, "alphanum_fraction": 0.6047930121421814, "avg_line_length": 21.06730842590332, "blob_id": "b0d9fbd6f49276d070f1d94d2d87f2fb10c42e41", "content_id": "c800730329b581b8508cbb59675292c265354c14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2296, "license_type": "permissive", "max_line_length": 124, "num_lines": 104, "path": "/TP1_Probas/ProgrammeC/random_generation.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-3", "text": "#include \"random_generation.h\"\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <time.h>\n#include <math.h>\n#include <limits.h>\n#include <stdbool.h>\n\n#include \"mersenne_twister.h\"\n#include \"von_neumann.h\"\n#include \"aes.h\"\n\n//--------------------------------------------------------------------------- GENERATEURS ALEATOIRES\n\n// 4 higher bits of rand()\nint generate_rand_high()\n{\n\treturn (rand() >> (16 - 4 - 1)) & 0x0F;\n}\n\n// 4 lowers bits of rand()\nint generate_rand_low()\n{\n\treturn rand() & 0x0F;\n}\n\n// AES\nint generate_aes()\n{\n\tstatic u32 Kx[NK], Kex[NB*(NR + 1)], Px[NB]; // pour l'AES\n\tstatic int is_first_call = 1;\n\n\tif (is_first_call)\n\t{\n\t\tinit_rand(Kx, Px, NK, NB, 45);\n\t\tis_first_call = 0;\n\t}\n\n\tKeyExpansion(Kex, Kx);\t// AES : sous-clefs\n\t\t\t\t\t\t\t// Initialisation de la clé et du plaintext pour l'AES \n\treturn AES(Px, Kex); // AES\t\n}\n\n// Mersenne-Twister\nint generate_twister()\n{\n\tstruct mt19937p mt;\n\tint tmp = rand();\n\tsgenrand(time(NULL) + tmp, &mt);\n\treturn genrand(&mt);\n}\n\n// Von eumann\nint generate_neumann()\n{\n\tstatic word16 x = 1111; // nombre entre 1000 et 9999 pour Von Neumann\n\treturn Von_Neumann(&x); // Von Neumann\n}\n\n//---------------------------------------------------------------------------------- generator_array\n\n// Generates 'n' random values (of 'bit_count' used bits) from given 'random_generator' and store them \n// into a file named 'name' (returns data as a generator_array).\ngenerator_array GenerateRandomValues(unsigned int n, unsigned int bit_count, const char* name, int(*random_generator)(void))\n{\n\tFILE* fichier = fopen(name, \"w\");\n\tint* values = malloc(sizeof(int)*n);\n\n\tif (fichier != NULL)\n\t{\n\t\tfprintf(fichier, \"values\\n\");\n\t\tfor (unsigned int i = 0; i < n; ++i)\n\t\t{\n\t\t\tvalues[i] = random_generator();\n\t\t\tfprintf(fichier, \"%d\\n\", values[i]);\n\t\t}\n\n\t\tfclose(fichier);\n\t}\n\tgenerator_array data = { values, n, bit_count };\n\treturn data;\n}\n\nint get_bit(generator_array* data, size_t index)\n{\n\tsize_t val_idx = index / data->bit_count;\n\tsize_t bit_idx = index - val_idx * data->bit_count;\n\tint val = data->values[val_idx];\n\n\treturn (val & (1 << bit_idx)) != 0 ? 1 : 0;\n}\n\nsize_t size(generator_array* data)\n{\n\treturn data->bit_count * data->values_count;\n}\n\nvoid destroy(generator_array* data)\n{\n\tfree(data->values);\n}\n" }, { "alpha_fraction": 0.5716218948364258, "alphanum_fraction": 0.5834138989448547, "avg_line_length": 37.60447692871094, "blob_id": "2d25f9e541163d720736da9fdaf79875a355ac60", "content_id": "51bd24dc80caa78b9da32b2244faa60eefd3ff86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5179, "license_type": "permissive", "max_line_length": 165, "num_lines": 134, "path": "/TP2_cpp/sources/capteur_stat.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/********************************************************************************************\n\t\t\t\t\t\t\t\t\t\tcapteur_stat.cpp\n\t\t\t\t\t\t\t\t\t\t----------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n********************************************************************************************/\n\n//--------------------------------------------------------------------------- Include systeme\n#include <iostream>\n\n//------------------------------------------------------------------------- Include personnel\n#include \"capteur_stat.h\"\n#include \"utils.h\"\n\nnamespace TP2\n{\n\t//------------------------------------------------------------------------- Constructeurs\n\n\tcapteur_stat::capteur_stat(capteur_event initial_event)\n\t\t: capteur_stat()\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'capteur_stat::capteur_stat(capteur_event)'\" << endl;\n#endif\n\t\tm_stat_timestamp = initial_event;\n\t\tupdate(initial_event);\n\t}\n\n\tcapteur_stat::capteur_stat(const capteur_stat& other)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur de copie 'capteur_stat::capteur_stat(const capteur_stat&)'\" << endl;\n#endif\n\t\treinterpret_cast<sensor_t&>(m_stat_timestamp) = reinterpret_cast<const sensor_t&>(other.m_stat_timestamp);\n\n\t\tm_taffic_counts[0] = other.m_taffic_counts[0];\n\t\tm_taffic_counts[1] = other.m_taffic_counts[1];\n\t\tm_taffic_counts[2] = other.m_taffic_counts[2];\n\t\tm_taffic_counts[3] = other.m_taffic_counts[3];\n\t}\n\n\tcapteur_stat::capteur_stat(capteur_stat&& other) noexcept\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au move-constructeur 'capteur_stat::capteur_stat(capteur_stat&&)'\" << endl;\n#endif\n\t\tswap(*this, other);\n\t}\n\n\tcapteur_stat::~capteur_stat()\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au destructeur '~capteur_stat::capteur_stat()'\" << endl;\n#endif\n\t}\n\n\t//-------------------------------------------------------------------- Méthodes publiques\n\n\tvoid capteur_stat::update(capteur_event new_event)\n\t{\n\t\tif (m_stat_timestamp.id == new_event.id)\n\t\t{\n\t\t\tm_stat_timestamp = new_event;\n\t\t\tm_taffic_counts[new_event.traff]++;\n\t\t}\n\t}\n\n\tvoid capteur_stat::show_time_distribution() const\n\t{\n\t\tunsigned int total = 0;\n\t\tfor (size_t i = 0; i < capteur_event::TRAFFIC_CARDINALITY; ++i)\n\t\t\ttotal += m_taffic_counts[i];\n\n\t\tif (total != 0)\n\t\t\tstd::cout << traffic::vert << \" \" << static_cast<int>((100.0 * m_taffic_counts[to_taffic_count_idx(traffic::vert)]) / total + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::rouge << \" \" << static_cast<int>((100.0 * m_taffic_counts[to_taffic_count_idx(traffic::rouge)]) / total + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::orange << \" \" << static_cast<int>((100.0 * m_taffic_counts[to_taffic_count_idx(traffic::orange)]) / total + 0.5) << \"%\" << std::endl\n\t\t\t<< traffic::noir << \" \" << static_cast<int>((100.0 * m_taffic_counts[to_taffic_count_idx(traffic::noir)]) / total + 0.5) << \"%\" << std::endl;\n\t\telse\n\t\t\tstd::cout << traffic::vert << \" 0%\" << std::endl\n\t\t\t<< traffic::rouge << \" 0%\" << std::endl\n\t\t\t<< traffic::orange << \" 0%\" << std::endl\n\t\t\t<< traffic::noir << \" 0%\" << std::endl;\n\t}\n\n\tcapteur_stat::sensor_t capteur_stat::get_id() const { return m_stat_timestamp.id; }\n\tcapteur_stat::sensor_t capteur_stat::get_d7() const { return m_stat_timestamp.d7; }\n\tcapteur_stat::sensor_t capteur_stat::get_hour() const { return m_stat_timestamp.hour; }\n\tcapteur_stat::sensor_t capteur_stat::get_min() const { return m_stat_timestamp.min; }\n\n\t//---------------------------------------------------------------------- Méthodes privées\n\n\tinline size_t capteur_stat::to_taffic_count_idx(traffic state)\n\t{\n\t\tswitch (state)\n\t\t{\n\t\tcase traffic::vert: return 0;\n\t\tcase traffic::rouge: return 1;\n\t\tcase traffic::orange: return 2;\n\t\tcase traffic::noir: return 3;\n\t\t}\n\t\treturn 0; // impossible\n\t}\n\n\t//---------------------------------------------------------------- Surchages d'opérateurs\n\n\tvoid swap(capteur_stat& lhs, capteur_stat& rhs) noexcept\n\t{\n\t\t// if one of the following swap calls isn't noexcept, we raise a static_assert\n\t\t// Commenté car is_nothrow_swappable ne fonctionne pas avec gcc installé en IF\n\t\t//\t\tstatic_assert(is_nothrow_swappable<capteur_stat::sensor_t*, capteur_event>(), \"Swap function could throw and let 'capteur_stat' objects in incoherant state!\");\n\n\t\t// enable ADL (following lines will use custom implementation of swap or std::swap if there isn't custom implementation)\n\t\tusing std::swap;\n\n\t\tswap(lhs.m_stat_timestamp, rhs.m_stat_timestamp);\n\t\tswap(lhs.m_taffic_counts, rhs.m_taffic_counts);\n\t}\n\n\tconst capteur_stat& capteur_stat::operator=(capteur_stat other)\n\t{\n\t\t// Copy and swap idiom\n\t\tswap(*this, other);\n\t\treturn *this;\n\t}\n\n\tbool operator==(const capteur_stat& lhs, const capteur_stat& rhs) { return lhs.m_stat_timestamp == rhs.m_stat_timestamp; }\n\tbool operator!=(const capteur_stat& lhs, const capteur_stat& rhs) { return !(lhs == rhs); }\n\n\tbool operator<(const capteur_stat& lhs, const capteur_stat& rhs) { return lhs.m_stat_timestamp < rhs.m_stat_timestamp; }\n\tbool operator>(const capteur_stat& lhs, const capteur_stat& rhs) { return rhs < lhs; }\n\tbool operator<=(const capteur_stat& lhs, const capteur_stat& rhs) { return !(rhs < lhs); }\n\tbool operator>=(const capteur_stat& lhs, const capteur_stat& rhs) { return !(lhs < rhs); }\n}\n" }, { "alpha_fraction": 0.6006343960762024, "alphanum_fraction": 0.6303344964981079, "avg_line_length": 27.42622947692871, "blob_id": "ddf6244ed0e2d2469da218ee9d9407d45a2e08aa", "content_id": "2f0d132567f8b8d185c89b0ec7ad8f71806be6e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3477, "license_type": "permissive", "max_line_length": 138, "num_lines": 122, "path": "/TP4_cpp/src/Polygon.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "//\n// Polygone.cpp\n// \n//\n// Created by Victoire Chapelle on 14/01/2016.\n//\n//\n\n#include \"Polygon.h\"\n\n#include <math.h>\n#include <string>\n\n#include <boost/serialization/vector.hpp>\n\n#include \"Utils.h\"\n#include \"optional.h\"\n#include \"Segment.h\"\n\nnamespace TP4\n{\n\tstd::experimental::optional<Polygon> make_polygon(const std::vector<Point> vertices)\n\t{\n\t\tif (vertices.size() > 2)\n\t\t{\n\t\t\tPoint p1, p2;\n\n\t\t\tp1.first = vertices[0].first - vertices[vertices.size() - 1].first;\n\t\t\tp1.second = vertices[0].second - vertices[vertices.size() - 1].second;\n\t\t\tp2.first = vertices[1].first - vertices[0].first;\n\t\t\tp2.second = vertices[1].second - vertices[0].second;\n\n\t\t\tdouble det_value;\n\t\t\tdouble current_det_value;\n\n\t\t\tdet_value = p1.first * p2.second - p1.second * p2.first;\n\n\t\t\tfor (size_t i = 0; i < vertices.size(); ++i)\n\t\t\t{\n\t\t\t\tp1.first = vertices[mod(i + 1, vertices.size())].first - vertices[i].first;\n\t\t\t\tp1.second = vertices[mod(i + 1, vertices.size())].second - vertices[i].second;\n\t\t\t\tp2.first = vertices[mod(i + 2, vertices.size())].first - vertices[mod(i + 1, vertices.size())].first;\n\t\t\t\tp2.second = vertices[mod(i + 2, vertices.size())].second - vertices[mod(i + 1, vertices.size())].second;\n\n\t\t\t\tcurrent_det_value = p1.first * p2.second - p1.second * p2.first;\n\n\t\t\t\tif (det_value*current_det_value < 0 - 0.00001)\n\t\t\t\t\treturn std::experimental::nullopt;\n\t\t\t}\n\n\t\t\treturn std::experimental::optional<Polygon>(Polygon(std::move(vertices)));\n\t\t}\n\n\t\treturn std::experimental::nullopt;\n\t}\n\n\tPolygon Move(const Polygon& shape, coord_t dx, coord_t dy)\n\t{\n\t\tstd::vector<Point> new_vertices;\n\t\tnew_vertices.reserve(new_vertices.size());\n\n\t\tfor (const Point& p : shape.vertices)\n\t\t\tnew_vertices.emplace_back(p.first + dx, p.second + dy);\n\n\t\treturn Polygon(std::move(new_vertices));\n\t}\n\n\tinline double squared_distance(Point a, Point b)\n\t{\n\t\treturn (a.first - b.first) * (a.first - b.first) \n\t\t\t+ (a.second - b.second) * (a.second - b.second);\n\t}\n\n\tbool Is_contained(const Polygon& shape, Point point)\n\t{\n\t\tdouble sum = 0.0;\n\n\t\t// Calcul de la somme des cosinus que font les angles entre les sommets consécutifs et le point\n\t\tfor (size_t i = 0; i < shape.vertices.size(); ++i)\n\t\t{\n\t\t\tauto next_point = shape.vertices[mod(i + 1, shape.vertices.size())];\n\n\t\t\tdouble a2 = squared_distance(shape.vertices[i], point);\n\t\t\tdouble c2 = squared_distance(shape.vertices[i], next_point);\n\t\t\tdouble b2 = squared_distance(next_point, point);\n\n\t\t\tif (abs(a2) < 0.001 || abs(b2) < 0.001)\n\t\t\t\treturn true; // Le point est confondu avec un sommet\n\n\t\t\tauto seg = make_segment(shape.vertices[i], next_point);\n\t\t\tif(seg)\n\t\t\t\tif (Is_contained(*seg, point))\n\t\t\t\t\treturn true;\n\n\t\t\t// Formule d'al-kashi : cos(angle) = (a² + b² - c²) / (2*a*b)\n\t\t\tdouble cos = (a2 + b2 - c2) / (2.0*sqrt(a2)*sqrt(b2)); \n\t\t//\tdouble cos = c2 / (length_1 + length_3 - 2.0*sqrt(length_3)*sqrt(length_1));\n\n\t\t\tsum += acos(cos);\n\t\t}\n\n\t\t// Si la somme est 1 le point est à l'intérieur (somme des angles = 360°)\n\t\t// TODO: faire mieux?\n\t\tif (abs(mod(sum, 2.0*3.14159) < 0.001))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\tPolygon::Polygon(const std::vector<Point>&& vertices)\n\t\t: vertices(std::move(vertices))\n\t{ }\n\n\tstd::ostream& operator<<(std::ostream& flux, const Polygon& polygone)\n\t{\n\t\tflux << \"{ \";\n\t\tfor (size_t i = 0; i < polygone.vertices.size(); ++i)\n\t\t\tflux << \"(\" << polygone.vertices[i].first << \", \" << polygone.vertices[i].second << (i == polygone.vertices.size() - 1 ? \") \" : \"); \");\n\t\tflux << \"}\";\n\n\t\treturn flux;\n\t}\n}\n" }, { "alpha_fraction": 0.7340425252914429, "alphanum_fraction": 0.7340425252914429, "avg_line_length": 29.33333396911621, "blob_id": "9ca9c44f7a3a85ffa8ee2d5405d67ccf8a2be22e", "content_id": "c058c0821930c57e15ca57fa147f4aed7b913d0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 94, "license_type": "permissive", "max_line_length": 35, "num_lines": 3, "path": "/TP1_BDDI/script droits d'accés/grant.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": " SET SERVEROUTPUT ON;\n execute accessGrant('gsarnette');\n execute accessGrant('pesotir');\n\n" }, { "alpha_fraction": 0.6246334314346313, "alphanum_fraction": 0.6275659799575806, "avg_line_length": 41.402984619140625, "blob_id": "6a216dd120379c0540ba3523083d0cf89fdd1695", "content_id": "f96c2052b29479861e320b7ca07d482fb24bd955", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8581, "license_type": "permissive", "max_line_length": 193, "num_lines": 201, "path": "/TP3_cpp/includes/Graph.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "WINDOWS-1252", "text": "/*********************************************************************************\n\t\t\t\t\t\tGraph - A graph with template nodes\n\t\t\t\t\t\t------------------------------------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//-------------------- Interface de la classe template Graph<T> ------------------\n#ifndef GRAPH_H\n#define GRAPH_H\n\n//--------------------------------------------------------------- Includes systeme\n#include <memory>\n#include <unordered_map>\n#include <initializer_list>\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//---------------------------------------------------------------------- Types\n\n\t//! Classe représentant un graphe fait de noeuds contenant des données de type T\n\t//! et de liens orientés entre ces noeuds. Un noeud a nescessairement au moins un\n\t//! lien (noeuds ajoutés automatiquement lors de l'ajout de liens). Si un même lien\n\t//! est ajouté plusieurs fois, alors son nombre d'occurrences associé est incrémenté.\n\t//! @remarks\n\t//!\t\tL'utilisateur doit surcharger la fonction std::hash pour le type T si elle \n\t//!\t\tn'existe pas dejà.\n\ttemplate<typename T, typename Hash = std::hash<T>, typename KeyEqual = std::equal_to<T>, typename Allocator = std::allocator<T>>\n\tclass Graph\n\t{\n\t\t//----------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//----------------------------------------------- Types et alias publiques\n\t\t//! Alias pour le type permettant d'identifier un noeud\n\t\tusing node_id_t = unsigned int;\n\n\t\t//! Structure utilisée pour représenter la destination et le nombre d'occurrences d'un lien\n\t\tstruct Link_to\n\t\t{\n\t\t\tLink_to() = default;\n\t\t\tLink_to(const Link_to&) = default;\n\t\t\tLink_to& operator=(const Link_to&) = default;\n\t\t\tLink_to(Link_to&&) = default;\n\t\t\tLink_to& operator=(Link_to&&) = default;\n\n\t\t\texplicit Link_to(node_id_t dest) : occurrence(1), destination(dest) { };\n\n\t\t\tunsigned int occurrence = 0;\n\t\t\tnode_id_t destination;\n\t\t};\n\n\t\t//----------------------------------------------------- Méthodes publiques\n\n\t\t//! Ajoute un lien au graph\n\t\t//! @params source référence universelle vers la valeur du noeud source du lien\n\t\t//! @params destination référence universelle vers la valeur de la destination du lien\n\t\tvoid add_link(T&& source, T&& destination);\n\n\t\t//! Retourne une multimap non ordonée représentant les liens du graph et associant à l'identifiant\n\t\t//! d'un noeud source, une structure contenant l'id du noeud de destination et le nombre d'occurrences du lien.\n\t\tstd::unordered_multimap<node_id_t, Link_to>& get_links();\n\n\t\t//! Retourne une map non ordonée associant la valeur de chaque noeud à leur identifiant\n\t\tstd::unordered_map<T, node_id_t>& get_nodes();\n\n\t\t//! Vide le graphe de ses noeuds et liens\n\t\tvoid clear();\n\n\t\t//----------------------------------------------------- Méthodes spéciales\n\n\t\t//! Constructeur par défaut ou permettant de spécifier la fonction de hashage, l'opérateur\n\t\t//! d'égalité et l'allocateur pour le type T.\n\t\t//! Par defaut, std::Hash<T>(), std::equal_to<T>() et std::allocator<T>() sont utilisés.\n\t\texplicit Graph(const Hash& hash = Hash(),\n\t\t\t\t\t const KeyEqual& equal = KeyEqual(),\n\t\t\t\t\t const Allocator& alloc = Allocator());\n\n\t\t//! Constructeur permettant de spécifier une liste d'initialisation, la fonction de hashage,\n\t\t//! l'opérateur d'égalité et l'allocateur pour le type T.\n\t\t//! Par defaut, std::Hash<T>(), std::equal_to<T>() et std::allocator<T>() sont utilisés.\n\t\t//! @params init_list list d'initialisation contenant des paires représentant des liens \n\t\t//!\t\t(pair.fisrt est le noeud source et pair.second est la destination).\n\t\tGraph(std::initializer_list<std::pair<T, T>> init_list,\n\t\t\t const Hash& hash = Hash(),\n\t\t\t const KeyEqual& equal = KeyEqual(),\n\t\t\t const Allocator& alloc = Allocator());\n\n\t\t// On utilise l'implémentation par défaut du copy/move constructor et copy/move assignment operator\n\t\tGraph(const Graph&) = default;\n\t\tGraph& operator=(const Graph&) = default;\n\t\tGraph(Graph&&) = default;\n\t\tGraph& operator=(Graph&&) = default;\n\n\t\t//------------------------------------------------------------------ PRIVE\n\tprivate:\n\t\t//------------------------------------------------------- Attributs privés\n\n\t\t//! attribut contenant le prochain id attribué à un nouveau noeud (pas indispensable ici, mais est \n\t\t//! utile pour une implémenation future de méthodes de supression d'éléments)\n\t\tnode_id_t m_new_id = 0;\n\n\t\t//! multimap non ordonnée stockant tout les liens entre les nœuds du graphe (les clés sont les\n\t\t//! identifiants des nœuds source, les valeurs sont les destinations et leur nombre d'occurrences)\n\t\tstd::unordered_multimap<node_id_t, Link_to> m_links;\n\t\t\n\t\t//! map non ordonée contenant les noeuds (valeur et identifiant)\n\t\tstd::unordered_map<T, node_id_t> m_nodes;\n\t};\n\n\t//--------------------------------------------------------- Fonctions globales\n\n\t//! Fonction créant un fichier GraphViz à partir d'un objet de type Graph<T>\n\t//! @remarks utilise l'opérateur output stream (<<) sur le type T pour le serialiser\n\ttemplate<typename T>\n\tvoid serialize_graph(const std::string& output_filename, std::unique_ptr<Graph<T>> graph)\n\t{\n\t\tstd::string line;\n\t\tstd::ofstream outfile(output_filename, std::ios::trunc);\n\n\t\tif (!outfile.is_open())\n\t\t\tthrow std::invalid_argument(\"Invalid output file path or don't have modification right\");\n\n\t\toutfile << \"digraph {\" << std::endl;\n\n\t\t// Write nodes\n\t\tfor (const auto& node : graph->get_nodes())\n\t\t\toutfile << \"node\" << node.second << \" [label=\\\"\" << node.first << \"\\\"];\" << std::endl;\n\n\t\t// Write links\n\t\tfor (const auto& link : graph->get_links())\n\t\t\toutfile << \"node\" << link.first << \" -> \" << \"node\" << link.second.destination << \" [label=\\\"\" << link.second.occurrence << \"\\\"];\" << std::endl;\n\n\t\toutfile << \"}\" << std::endl;\n\n\t\toutfile.close();\n\t}\n\n\t//--------------- Implémentation de la classe template Graph<T> --------------\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tGraph<T, Hash, KeyEqual, Allocator>::Graph(const Hash& hash, const KeyEqual& equal, const Allocator& alloc)\n\t\t: m_links(), m_nodes(10, hash, equal, alloc) { }\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tGraph<T, Hash, KeyEqual, Allocator>::Graph(std::initializer_list<std::pair<T, T>> init_list, const Hash& hash, const KeyEqual& equal, const Allocator& alloc)\n\t\t: m_links(), m_nodes(10, hash, equal, alloc)\n\t{\n\t\tfor (const auto& link : init_list)\n\t\t\tadd_link(link.first, link.second);\n\t}\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tvoid Graph<T, Hash, KeyEqual, Allocator>::add_link(T&& source, T&& destination)\n\t{\n\t\tnode_id_t source_id, destination_id;\n\n\t\t// Add source node to m_nodes if not stored yet and get source id\n\t\tauto p = m_nodes.emplace(std::make_pair(std::forward<T>(source), m_new_id));\n\t\tsource_id = p.second ? m_new_id++ : p.first->second; // TODO: verifier les incrémentations\n\n\t\t// Add destination node to m_nodes if not stored yet and get destination id\n\t\tp = m_nodes.emplace(std::make_pair(std::forward<T>(destination), m_new_id));\n\t\tdestination_id = p.second ? m_new_id++ : p.first->second;\n\n\t\t// Find every links which have the same source\n\t\tauto range = m_links.equal_range(source_id);\n\n\t\t// Linear lookup on resulting range to find if we have already added a link with the same destination and source \n\t\tfor (auto it = range.first; it != range.second; ++it)\n\t\t{\n\t\t\tif (it->second.destination == destination_id)\n\t\t\t{\n\t\t\t\t++(it->second.occurrence); // increment link occurrence number\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Store new link otherwise\n\t\tm_links.emplace(source_id, Link_to(destination_id));\n\t}\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tinline std::unordered_multimap<typename Graph<T, Hash, KeyEqual, Allocator>::node_id_t, typename Graph<T, Hash, KeyEqual, Allocator>::Link_to>& Graph<T, Hash, KeyEqual, Allocator>::get_links()\n\t{ return m_links; }\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tinline std::unordered_map<T, typename Graph<T, Hash, KeyEqual, Allocator>::node_id_t>& Graph<T, Hash, KeyEqual, Allocator>::get_nodes()\n\t{ return m_nodes; }\n\n\ttemplate<typename T, typename Hash, typename KeyEqual, typename Allocator>\n\tinline void Graph<T, Hash, KeyEqual, Allocator>::clear()\n\t{\n\t\tm_links.clear();\n\t\tm_nodes.clear();\n\t\tm_new_id = 0;\n\t}\n}\n\n#endif // GRAPH_H\n\n\n" }, { "alpha_fraction": 0.5837028622627258, "alphanum_fraction": 0.5918329358100891, "avg_line_length": 32.20245361328125, "blob_id": "22fea79c045d243a6a284efe4c9e10c256de402f", "content_id": "bb6d08b75a9e745a888eae76f1b90f869eb6bc73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5427, "license_type": "permissive", "max_line_length": 102, "num_lines": 163, "path": "/TP1_Concurrency/source/gestionEntree.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tGestion entree - tache gerant les barrieres d'entree\n\t\t\t----------------------------------------------------\n\tdebut \t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//-- Realisaion de la tache <GESTION_ENTREE> (fichier gestionEntree.cpp) -\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//-------------------------------------------------------- Include système\n#include <unordered_map>\n#include <sys/wait.h>\n#include <sys/sem.h>\n#include <unistd.h>\n#include <utility>\n#include <string>\n#include <ctime>\n\n//------------------------------------------------------ Include personnel\n#include \"gestionEntree.h\"\n#include \"process_utils.h\"\n#include \"clavier.h\"\n#include \"Outils.h\"\n\n/////////////////////////////////////////////////////////////////// PRIVE\nnamespace\n{\n\t//------------------------------------------------ Variables statiques\n\t//! On utilise des variables statiques plutot que automatiques pour qu'elles\n\t//! soient accessibles depuis les handlers de signaux car ce sont des lambdas \n\t//! qui ne peuvent rien capturer de leur contexte pour qu'elles puissent être \n\t//! castés en pointeur de fonction C.\n\tipc_id_t car_message_queue_id;\n\tipc_id_t sem_id;\n\tshared_mem<parking> parking_state;\n\tshared_mem<waiting_cars> waiting;\n\tshared_mem<places> parking_places;\n\tstd::unordered_map<pid_t, car_info> car_parking_tasks;\n\n\t//-------------------------------------------------- Fonctions privées\n\tvoid quit_entree()\n\t{\n\t\t// On retire les handlers des signaux SIGCHLD et SIGUSR2\n\t\tunsubscribe_handler<SIGCHLD, SIGUSR2>();\n\n\t\t// On quitte tout les processus garant des voitures\n\t\tfor (const auto& parking_task : car_parking_tasks) {\n\t\t\tif (parking_task.first > 0)\n\t\t\t{\n\t\t\t\tkill(parking_task.first, SIGUSR2);\n\t\t\t\twaitpid(parking_task.first, nullptr, 0);\n\t\t\t}\n\t\t}\n\n\t\t// Detache 'parking_state' de la memoire partagée\n\t\tdetach_shared_memory(parking_state.data);\n\t\tdetach_shared_memory(waiting.data);\n\t\tdetach_shared_memory(parking_places.data);\n\n\t\t// On notifie la tache mère de la fin pour qu'elle quitte les autres taches\n\t\tkill(getppid(), SIGCHLD);\n\n\t\texit(EXIT_SUCCESS);\n\t}\n}\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//----------------------------------------------------- Fonctions publique\npid_t ActiverPorte(TypeBarriere type)\n{\n\t// Creation du processus fils\n\treturn fork([type]()\n\t{\n\t\t// Fonction lambda aidant a quitter en cas d'erreur\n\t\tauto quit_if_failed = [](bool condition) {\n\t\t\tif (!condition)\n\t\t\t\tquit_entree();\n\t\t};\n\n\t\t// On ajoute un handler pour le signal SIGUSR2 indiquant que la tache doit se terminer\n\t\tquit_if_failed(handle<SIGUSR2>([](signal_t sig) { quit_entree(); }));\n\n\t\t// Ouverture de la message queue utilisée pour recevoir les voitures\n\t\tquit_if_failed(open_message_queue(car_message_queue_id, 1));\n\n\t\t// Récuperation des semaphores\n\t\tsem_id = semget(ftok(\".\", 3), 4U, 0600);\n\t\tquit_if_failed(sem_id != -1);\n\n\t\t// Ouvre les memoires partagées\n\t\tparking_state = get_shared_memory<parking>(4);\n\t\tquit_if_failed(parking_state.data != nullptr);\n\t\twaiting = get_shared_memory<waiting_cars>(5);\n\t\tquit_if_failed(waiting.data != nullptr);\n\t\tparking_places = get_shared_memory<places>(6);\n\t\tquit_if_failed(parking_places.data != nullptr);\n\n\t\t// On ajoute un handler pour le signal SIGCHLD indiquant qu'une voiture s'est garée\n\t\tquit_if_failed(handle<SIGCHLD>([](signal_t sig)\n\t\t{\n\t\t\tint status;\n\t\t\tpid_t chld = waitpid(-1, &status, WNOHANG);\n\t\t\tif (chld > 0 && WIFEXITED(status))\n\t\t\t{\n\t\t\t\t// On affiche la place et on met à jour la memoire partagée\n\t\t\t\tauto car = car_parking_tasks[chld];\n\t\t\t\tauto place_num = WEXITSTATUS(status);\n\n\t\t\t\tlock(sem_id, 0, [&car, place_num]() {\n\t\t\t\t\tparking_places.data->places[place_num - 1] = car;\n\t\t\t\t});\n\n\t\t\t\tcar_parking_tasks.erase(chld);\n\t\t\t\tAfficherPlace(WEXITSTATUS(status), (TypeUsager)car.user_type, car.car_number, car.heure_arrivee);\n\t\t\t}\n\t\t}));\n\n\t\t// Phase moteur\n\t\twhile (true)\n\t\t{\n\t\t\t// On attend la reception d'un message de la tache clavier\n\t\t\tcar_incomming_msg message;\n\t\t\tquit_if_failed(read_message(car_message_queue_id, type, message));\n\n\t\t\tDessinerVoitureBarriere(type, message.type_usager);\n\t\t\tAfficherRequete(type, message.type_usager, time(nullptr));\n\n\t\t\tbool is_full = false;\n\t\t\tunsigned int next_car_id = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tquit_if_failed(lock(sem_id, 0, [&message, type, &is_full, &next_car_id]()\n\t\t\t\t{\n\t\t\t\t\t// On vérifie que le parking n'est pas (de nouveau) plein avant de laisser passer la voiture\n\t\t\t\t\tis_full = parking_state.data->is_full();\n\t\t\t\t\tif (!is_full) {\n\t\t\t\t\t\tnext_car_id = parking_state.data->next_car_id++;\n\t\t\t\t\t\tparking_state.data->car_count++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\twaiting.data->waiting_fences[type - 1] = { message.type_usager, time(nullptr) };\n\t\t\t\t}));\n\n\t\t\t\tif (is_full)\n\t\t\t\t\t// On attend qu'une place se libère\n\t\t\t\t\tsem_pv(sem_id, type, -1);\n\t\t\t} while (is_full);\n\n\t\t\tlock(sem_id, 0, [type]() {\n\t\t\t\twaiting.data->waiting_fences[type - 1] = { AUCUN, 0 };\n\t\t\t});\n\n\t\t\t// La barrière s'ouvre et on gare la voiture\n\t\t\tpid_t garage_pid = GarerVoiture(type);\n\t\t\tquit_if_failed(garage_pid);\n\t\t\tcar_parking_tasks.emplace(garage_pid, car_info{ next_car_id, message.type_usager, time(nullptr) });\n\n\t\t\tsleep(1); // Temps pour avancer...\n\t\t\tEffacer(static_cast<TypeZone>(REQUETE_R1 + type - 1));\n\t\t}\n\t});\n}\n" }, { "alpha_fraction": 0.42625001072883606, "alphanum_fraction": 0.5400000214576721, "avg_line_length": 14.075471878051758, "blob_id": "238f4dec0b55ac908fae785cd19a1fe9d52ca8e9", "content_id": "941e77cbfa31c0be6b120c0094fe5ad17d5d4251", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 800, "license_type": "permissive", "max_line_length": 32, "num_lines": 53, "path": "/TP2_Archi/tp2-2.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "\n#include <msp430fg4618.h>\n\n#define LED1 BIT2\n#define LED2 BIT1\n#define LED3 BIT1\n\n#define SW1 BIT0\n#define SW2 BIT1\n\nvolatile unsigned int i;\n\nint main(void)\n{\n\t// set P5.1 to output direction\n\tP5DIR = LED3;\n\t\n\tP2DIR = P2DIR | (LED1 | LED2);\n\tP1DIR = P1DIR & !SW1;\n\n\t\n\tfor(;;)\n\t{\n\t\t\n\t\t/* turn all LEDS off */\n\t\tP5OUT &= !LED3;\n\t\tP2OUT &= !(LED1 | LED2);\n\t\t\n\t\twhile ((P1IN & SW1) != 0x00);\n\t\twhile ((P1IN & SW1) == 0x00);\n\t\t\n\t\tP5OUT &= !LED3;\n\t\tP2OUT &= !LED2;\n\t\tP2OUT |= LED1;\n\t\t\n\t\twhile ((P1IN & SW1) != 0x00);\n\t\twhile ((P1IN & SW1) == 0x00);\n\t\t\n\t\tP5OUT &= !LED3;\n\t\tP2OUT &= !LED1;\n\t\tP2OUT |= LED2;\n\t\t\n\t\twhile ((P1IN & SW1) != 0x00);\n\t\twhile ((P1IN & SW1) == 0x00);\n\t\t\n\t\tP2OUT &= !(LED1 | LED2);\n\t\tP5OUT |= LED3;\n\t\t\n\t\twhile ((P1IN & SW1) != 0x00);\n\t\twhile ((P1IN & SW1) == 0x00);\n\t}\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.637806236743927, "alphanum_fraction": 0.6842984557151794, "avg_line_length": 68.07691955566406, "blob_id": "29a1c7940b16a37537209d5f523364e796d12874", "content_id": "072866360aca5a161dfb61eb299d3cb8201f7935", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3594, "license_type": "permissive", "max_line_length": 175, "num_lines": 52, "path": "/TP2_SI/services/src/main/java/test/testLivreur.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage test;\n\nimport com.google.maps.GeoApiContext;\nimport com.google.maps.GeocodingApi;\nimport com.google.maps.model.GeocodingResult;\nimport metier.modele.Drone;\nimport metier.modele.LivreurCycliste;\nimport metier.service.Service;\n\n/**\n *\n * @author quentinvecchio\n */\npublic class testLivreur {\n public static void main(String[] args) {\n Service service = new Service();\n GeoApiContext monGeoApi = new GeoApiContext().setApiKey(\"AIzaSyDcVVJjfmxsNdbdUYeg9MjQoJJ6THPuap4\");\n try {\n GeocodingResult[] results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n results = GeocodingApi.geocode(monGeoApi, \"129 Rue Servient, 69003 Lyon\").await();\n service.createDrone(new Drone(20.0, results[0].geometry.location.lat, results[0].geometry.location.lng, true, 2000, \"[email protected]\"));\n \n results = GeocodingApi.geocode(monGeoApi, \"26 Rue Louis Blanc, 69006 Lyon\").await();\n service.createLivreurCycliste(new LivreurCycliste(\"Quentn\", \"Vecchio\", \"[email protected]\", results[0].geometry.location.lat, results[0].geometry.location.lng, true, 6000));\n results = GeocodingApi.geocode(monGeoApi, \"38 Avenue Maréchal de Saxe, 69006 Lyon\").await();\n service.createLivreurCycliste(new LivreurCycliste(\"Henri\", \"Dupont\", \"[email protected]\", results[0].geometry.location.lat, results[0].geometry.location.lng, true, 6000));\n results = GeocodingApi.geocode(monGeoApi, \"20 Avenue Maréchal de Saxe, 69006 Lyon\").await();\n service.createLivreurCycliste(new LivreurCycliste(\"Martin\", \"Dupont\", \"[email protected]\", results[0].geometry.location.lat, results[0].geometry.location.lng, true, 6000));\n results = GeocodingApi.geocode(monGeoApi, \"5 Rue du Commandant Faurax, 69006 Lyon\").await();\n service.createLivreurCycliste(new LivreurCycliste(\"Louis\", \"Durant\", \"[email protected]\", results[0].geometry.location.lat, results[0].geometry.location.lng, true, 6000));\n results = GeocodingApi.geocode(monGeoApi, \"200 Quai Charles de Gaulle, 69006 Lyon\").await();\n service.createLivreurCycliste(new LivreurCycliste(\"Joseph\", \"Jacob\", \"[email protected]\", results[0].geometry.location.lat, results[0].geometry.location.lng, true, 6000));\n \n } catch(Exception e) {\n System.out.println(\"Erreur : \" + e.getMessage());\n }\n }\n}\n" }, { "alpha_fraction": 0.6904577016830444, "alphanum_fraction": 0.705197811126709, "avg_line_length": 24.780000686645508, "blob_id": "d9323ad033eb0525b5e988b34b5d21e3eac06aca", "content_id": "aa850a58bdd911000f8d221bddae45a146a2b190", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1310, "license_type": "permissive", "max_line_length": 133, "num_lines": 50, "path": "/TP1_Reseau/Shared/src/shared/User.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package shared;\n\nimport java.io.Serializable;\nimport java.util.UUID;\n\n/**\n * Classe représentant un utilisateur ayant un nom et un Id (mots de passe).\n * La classe est serialisable et peut gènerer un hash.\n */\npublic class User implements Serializable {\n\n\t/**\n\t * Constructeur créant un User à partir de son nom et de son Id (mots de passe).\n\t * @param id Mots de passe de l'utilisateur\n\t * @param name Nome de l'utilisateur\n\t */\n\tpublic User(UUID id, String name) {\n\t\tId = id;\n\t\tName = name;\n\t}\n\n\t/**\n\t * Génère un hash pour un instance de la classe User.\n\t * @return Un int pouvant être utilisé comme hash.\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Id.hashCode();\n\t}\n\n\t/**\n\t * Vérifie l'égalitée entre l'objet donné en paramètre et l'instance courante.\n\t * @param other L'objet avec le quel l'instance courante est comparée.\n\t * @return Un booléen indiquant l'égalité\n\t */\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif(other instanceof User)\n\t\t\treturn ((User)other).Id.equals(Id);\n\t\treturn false;\n\t}\n\n\tpublic final UUID Id;\n\tpublic String Name;\n\n\t/**\n\t * Numéro identifiant la classe lors de la serialization (utilisé pour verifier la présence de la classe lors de la déserialization)\n\t */\n\tprivate static final long serialVersionUID = 4900438272231148693L;\n}\n" }, { "alpha_fraction": 0.6782868504524231, "alphanum_fraction": 0.6782868504524231, "avg_line_length": 26.135135650634766, "blob_id": "8e9a3c51f9fb76434cc254deeebd4856b2f52288", "content_id": "24f697359ac01b1a6791546223b9e97c1b84cde5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1004, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/TP2_SI/services/src/main/java/dao/DroneDao.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage dao;\n\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport metier.modele.Drone;\n\n/**\n *\n * @author quentinvecchio\n */\npublic class DroneDao {\n\n public void create(Drone drone) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n em.persist(drone);\n }\n\n public Drone update(Drone drone) throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n drone = em.merge(drone);\n return drone;\n }\n\n public List<Drone> findAll() throws Throwable {\n EntityManager em = JpaUtil.obtenirEntityManager();\n List<Drone> livreurs = null;\n Query q = em.createQuery(\"SELECT l FROM Livreur l\");\n livreurs = (List<Drone>) q.getResultList();\n return livreurs;\n }\n}\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5849056839942932, "avg_line_length": 26.257143020629883, "blob_id": "600ae38fea39d2daba06fae7258e193ee33eb573", "content_id": "1aac50f69df3a4cff4d679af64504c730f3b3374", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1913, "license_type": "permissive", "max_line_length": 110, "num_lines": 70, "path": "/TP4_cpp/src/Segment.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tSegment\n\t\t\t\t\t\t\t\t\t-------\n*********************************************************************************/\n\n#ifndef SEGMENT_H\n#define SEGMENT_H\n\n#include <string>\n\n#include \"Utils.h\"\n#include \"Command.h\"\n#include \"optional.h\"\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\n\t//----------------------------------------------------------------------------\n\t//! Structure représentant un segment constitué de deux points distincts.\n\t//! La structure est serialisable grâce à boost::serialization.\n\t//----------------------------------------------------------------------------\n\tstruct Segment\n\t{\n\t\tSegment() = default;\n\t\tSegment& operator=(const Segment&) = delete;\n\n\t\tPoint Get_first_point() const\n\t\t{\n\t\t\treturn first_point;\n\t\t}\n\n\t\tPoint Get_second_point() const\n\t\t{\n\t\t\treturn second_point;\n\t\t}\n\n\n\tprivate:\n\t\tSegment(const Point&& first_point, const Point&& second_point);\n\n\t\tPoint first_point;\n\t\tPoint second_point;\n\n\t\tfriend std::ostream& operator<<(std::ostream &flux, const Segment& seg);\n\n\n\t\tfriend std::experimental::optional<Segment> make_segment(const Point first_point, const Point second_point);\n\n\t\tfriend Segment Move(const Segment& shape, coord_t dx, coord_t dy);\n\t\tfriend bool Is_contained(const Segment& shape, Point point);\n\n\t\tfriend class boost::serialization::access;\n\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\tar & boost::serialization::make_nvp(\"first_point\", first_point)\n\t\t\t\t& boost::serialization::make_nvp(\"second_point\", second_point);\n\t\t}\n\t};\n\n\tSegment Move(const Segment& shape, coord_t dx, coord_t dy);\n\tbool Is_contained(const Segment& shape, Point point);\n\n\tstd::experimental::optional<Segment> make_segment(const Point first_point, const Point second_point);\n}\n\n#endif //SEGMENT_H\n" }, { "alpha_fraction": 0.4885496199131012, "alphanum_fraction": 0.5496183037757874, "avg_line_length": 13.035714149475098, "blob_id": "670c4549a2469f7663d5013fabc5be74b18869c1", "content_id": "482220b4d1aba0387592c67df13fa7dbf4e14345", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 393, "license_type": "permissive", "max_line_length": 32, "num_lines": 28, "path": "/TP1_Probas/ProgrammeC/von_neumann.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"von_neumann.h\"\n\nint Dec_size(word32 e)\n{\n\tunsigned i = 0;\n\twhile (e != 0)\n\t{\n\t\t++i;\n\t\te = e / 10;\n\t}\n\treturn i;\n}\n\nword16 Von_Neumann(word16 *next)\n{\n\tword32 result;\n\tint pds, i;\n\tresult = (*next)*(*next);\n\tpds = Dec_size(result);\n\tpds = (pds - 4) / 2;\n\tfor (i = 0; i < pds; i++)\n\t{\n\t\tresult = (result) / 10;\n\t}\n\tresult = result % 10000;\n\t*next = result;\n\treturn ((word16)result);\n}\n" }, { "alpha_fraction": 0.7511415481567383, "alphanum_fraction": 0.7557077407836914, "avg_line_length": 28.22222137451172, "blob_id": "727ba49fba457ae37cc62830da9f97c3be692a50", "content_id": "608cfd588e43e51b3a6f6ed31243391554169492", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1323, "license_type": "permissive", "max_line_length": 115, "num_lines": 45, "path": "/TP1_Probas/ProgrammeC/file_attente.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "#ifndef FILE_ATTENTE_H\n#define FILE_ATTENTE_H\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#define ARRAY_MAX_SIZE 1000\n\ntypedef struct\n{\n\tdouble arrivee[ARRAY_MAX_SIZE];\n\tsize_t size_arrivee;\n\tdouble depart[ARRAY_MAX_SIZE];\n\tsize_t size_depart;\n} file_attente;\n\n\ntypedef struct\n{\n\tdouble temps[ARRAY_MAX_SIZE];\n\tint nombre[ARRAY_MAX_SIZE];\n\tsize_t size;\n} evolution;\n\nvoid init(file_attente* fa);\nvoid init_evol(evolution* evol);\n\n// Création de la file d'attente MM1 en fonction des paramètres des deux distributions exponentielles et du temps D\nfile_attente FileMM1(double lambda, double mu, double D);\n// Création de la file d'attente MMN en fonction des paramètres des deux distributions exponentielles et du temps D\nfile_attente FileMMN(double lambda, double mu, double D, size_t n);\n// Calcul de l'évolution de la file d'attente\nevolution get_evolution(file_attente* fa, double D);\n\n// Serialisation de la file d'attente\nvoid fprint(file_attente* data, const char* filename);\n// Sérialisation de l'évolution de la file d'attente\nvoid fprint_evol(evolution* data, const char* filename);\n\n// Temps moyen de présence d'un client (attente + service)\ndouble get_time_mean(file_attente* fa, evolution* evol);\n// Nombre moyen de clients dans le système\ndouble get_number_mean(evolution* evol);\n\n#endif // FILE_ATTENTE_H" }, { "alpha_fraction": 0.5232148766517639, "alphanum_fraction": 0.5296189785003662, "avg_line_length": 29.617647171020508, "blob_id": "5abaef056eb5625ff64a36451277d1bd4754af85", "content_id": "945afb5dccc686d94e8607894798de79829cf3fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3131, "license_type": "permissive", "max_line_length": 129, "num_lines": 102, "path": "/TP1_Concurrency/source/clavier.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\t\t\tClavier - tache gerant l'entree clavier\n\t\t\t\t\t-----------------------------------------\n\tdebut : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//---------- Realisation du module <CLAVIER> (fichier clavier.cpp) -------\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//-------------------------------------------------------- Include système\n#include <string>\n#include <errno.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <sys/ipc.h>\n#include <sys/msg.h>\n#include <functional>\n#include <sys/types.h>\n\n//------------------------------------------------------ Include personnel\n#include \"process_utils.h\"\n#include \"clavier.h\"\n#include \"Outils.h\"\n#include \"Menu.h\"\n\n/////////////////////////////////////////////////////////////////// PRIVE\nnamespace\n{\n\t//------------------------------------------------ Variables statiques\n\tstatic ipc_id_t incomming_car_mq_id;\n\tstatic ipc_id_t car_exit_mq_id;\n\n\t//-------------------------------------------------- Fonctions privees\n\t//! Termine la tache gèrant l'interface console\n\tvoid quit_clavier()\n\t{\n\t\t// On retire le handler du signal SIGUSR2\n\t\tunsubscribe_handler<SIGUSR2>();\n\n\t\t// On notifie la tache mère de la fin pour qu'elle quitte les autres taches\n\t\tkill(getppid(), SIGCHLD);\n\n\t\texit(EXIT_SUCCESS);\n\t}\n}\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//---------------------------------------------------- Fonctions publiques\npid_t activer_clavier()\n{\n\t// Creation de la tache clavier\n\treturn fork([]()\n\t{\n\t\t// On ajoute un handler pour le signal SIGUSR2 indiquant que la tache doit se terminer\n\t\tif (!(handle<SIGUSR2>([](signal_t sig) { quit_clavier(); })))\n\t\t\tquit_clavier();\n\n\t\t// Ouverture de la 'message queue' utilisée pour communiquer avec les taches des barrières\n\t\tif (!open_message_queue(incomming_car_mq_id, 1))\n\t\t\tquit_clavier();\n\n\t\t// Ouverture de la 'message queue' utilisée pour communiquer avec la tache de sortie\n\t\tif (!open_message_queue(car_exit_mq_id, 2))\n\t\t\tquit_clavier();\n\n\t\t// Execute la phase moteur (interface console)\n\t\twhile (true)\n\t\t\tMenu();\n\t});\n}\n\nvoid Commande(char code, unsigned int valeur)\n{\n\tswitch (code)\n\t{\n\tcase 'e':\n\tcase 'E':\n\t\tquit_clavier();\n\t\tbreak;\n\tcase 'p':\n\tcase 'P':\n\t\t// On notifie la tache gerant la barriere de l'arrivee de la voiture\n\t\tif (!send_message(incomming_car_mq_id, car_incomming_msg{ (valeur == 1 ? PROF_BLAISE_PASCAL : ENTREE_GASTON_BERGER), PROF }))\n\t\t\tquit_clavier();\n\t\tbreak;\n\tcase 'a':\n\tcase 'A':\n\t\t// On notifie la tache gerant la barriere de l'arrivee de la voiture\n\t\tif (!send_message(incomming_car_mq_id, car_incomming_msg{ (valeur == 1 ? AUTRE_BLAISE_PASCAL : ENTREE_GASTON_BERGER), AUTRE }))\n\t\t\tquit_clavier();\n\t\tbreak;\n\tcase 's':\n\tcase 'S':\n\t\t// On notifie la tache gerant la sortie qu'une place doit être liberée (si il y a une voiture)\n\t\tif (!send_message(car_exit_mq_id, car_exit_msg{ valeur }))\n\t\t\tquit_clavier();\n\t\tbreak;\n\t}\n}\n" }, { "alpha_fraction": 0.7262079119682312, "alphanum_fraction": 0.7262079119682312, "avg_line_length": 21.766666412353516, "blob_id": "242fbc813c04842ccce3590bb138b13e62a449e6", "content_id": "c64f49ddba15bfc85d3096da4b79e1159b634d6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 683, "license_type": "permissive", "max_line_length": 81, "num_lines": 30, "path": "/TD4_ALG/hash_table.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef HASH_TABLE_H\n#define HASH_TABLE_H\n\ntypedef enum { empty, used, deleted } status;\n\ntypedef struct\n{\n\tstatus state;\n\tchar* key;\n\tchar* value;\n} cell;\n\ntypedef struct\n{\n\tunsigned int m;\n\tcell* array;\n\tunsigned int array_step;\n\tunsigned int array_size;\n\tunsigned int deleted_count;\n\tunsigned int used_count;\n} hash_table;\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, unsigned int m);\nvoid destr_hash_table(hash_table* table);\nvoid show_stats(hash_table* table);\nvoid insert_to_table(hash_table* table, char* key, char* value);\nvoid remove_from_table(hash_table* table, char* key);\nvoid find_in_table(hash_table* table, char* key);\n\n#endif /* HASH_TABLE_H */\n" }, { "alpha_fraction": 0.5328046083450317, "alphanum_fraction": 0.6027397513389587, "avg_line_length": 23.33333396911621, "blob_id": "a32ab3ac3320812d04ba0a2768fe3c18253ecf08", "content_id": "faede2e8db62cdd9152529d977572245aa3dec84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1392, "license_type": "permissive", "max_line_length": 110, "num_lines": 57, "path": "/TP1_Probas/ProgrammeC/lois_distributions.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "#include \"lois_distributions.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <time.h>\n#include <math.h>\n#include <limits.h>\n#include <stdbool.h>\n\n#include \"random_generation.h\"\n\n//----------------------------------------------------------------------------- LOIS DE DISTRIBUTION\n\n// Loi uniforme\ndouble Alea()\n{\n\tstatic double n = 4294967296; // 2^32\n\treturn 1 / 2.0 + generate_aes() / n;\n}\n\ndouble Exponentielle(double lambda)\n{\n\treturn -log(1 - Alea()) / lambda;\n}\n\ndouble Gauss(double sigma, double m)\n{\n\tstatic double n = 4294967296; // 2^32\n\tstatic double Pi = 3.14159265359;\n\tdouble U = 1 / 2.0 + generate_aes() / n;\n\tdouble V = 1 / 2.0 + generate_twister() / n;\n\treturn m + sigma * sqrt(-log(U)) * cos(2 * Pi * V);\n}\n\ndouble f_inversion()\n{\n\treturn exp(sqrt(Alea()) * log(2)) - 1;\n}\n\ndouble f_rejet()\n{\n\tstatic double n = 4294967296; // 2^32\n\tstatic double c = 2.0 / 0.48045301391820139; // 2/log(2)^2\n\n\tdouble U, Y; // Deux variables issues de deux lois de probabilitées uniformes indépendantes\n\tdouble f;\n\tdo\n\t{\n\t\tU = 1 / 2.0 + generate_aes() / n;\n\t\tY = 1 / 2.0 + generate_twister() / n;\n\n\t\tf = c * log(1 + Y) / (1 + Y); // Calcul de f(Y), avec Y toujours compris entre 0 et 1\n\t} while (U <= f / (c * Y)); // On tire de nouvelles valeures tant que la condition n'est pas vérifiée (rejet)\n\n\treturn Y; // Y suit alors la loi de probabilitées decrite par f\n}\n" }, { "alpha_fraction": 0.620050311088562, "alphanum_fraction": 0.621307373046875, "avg_line_length": 29.30476188659668, "blob_id": "4b057aa13f652509257795edadfa9021b82569f5", "content_id": "3f4b00d819e22ce5a058e27260f27e2cb29b2526", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3191, "license_type": "permissive", "max_line_length": 302, "num_lines": 105, "path": "/TP4_cpp/src/Group.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tGroup\n\t\t\t\t\t\t\t\t\t------\n*********************************************************************************/\n\n#ifndef GROUP_H\n#define GROUP_H\n\n#include <string>\n\n#include \"Serializable_shape_history.h\"\n#include \"Utils.h\"\n\n// TODO: it might be desired to suppress the tracking of objects as it is known a priori that the application in question can never create duplicate objects. Serialization of pointers can be \"fine tuned\" via the specification of Class Serialization Traits as described in another section of this manual\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\t//----------------------------------------------------------------------------\n\t//! Classe représentant une intersection ou une union de formes. Le paramètre \n\t//! template 'is_union' est un booléen indiquant si il s'agit d'une union ou \n\t//! d'une intersection de fomres géomètriques.\n\t//! La classe est serialisable grâce à boost::serialization.\n\t//----------------------------------------------------------------------------\n\ttemplate<bool is_union>\n\tstruct Group\n\t{\n\t\tusing shape_vec_t = std::vector<History_shape>;\n\n\t\tGroup() = default;\n\t\tGroup(shape_vec_t&& shapes);\n\t\tGroup(Group&&) = default;\n\t\tGroup& operator=(Group&&) = default;\n\t\tGroup(const Group&);\n\t\tGroup& operator=(const Group&) = delete;\n\n\tprivate:\n\t\tshape_vec_t shapes;\n\n\t\ttemplate<bool is_u>\n\t\tfriend std::ostream& operator<<(std::ostream& flux, const Group<is_u>& shape);\n\n\t\ttemplate<bool is_u>\n\t\tfriend Group<is_u> Move(const Group<is_u>& group, coord_t dx, coord_t dy);\n\n\t\ttemplate<bool is_u>\n\t\tfriend bool Is_contained(const Group<is_u>& group, Point point);\n\n\t\tfriend class boost::serialization::access;\n\n\t\ttemplate<typename Archive>\n\t\tvoid serialize(Archive& ar, const unsigned int version)\n\t\t{\n\t\t\tar & boost::serialization::make_nvp(\"shapes\", shapes);\n\t\t}\n\t};\n\n\tusing Shape_union = Group<true>;\n\tusing Shape_intersection = Group<false>; \n\n\ttemplate<bool is_union>\n\tGroup<is_union>::Group(shape_vec_t&& shapes)\n\t\t: shapes(std::move(shapes))\n\t{ }\n\n\ttemplate<bool is_union>\n\tGroup<is_union>::Group(const Group& g)\n\t{\n\t\tshapes.reserve(g.shapes.size());\n\t\tfor (const auto& shape : g.shapes)\n\t\t\tshapes.emplace_back(shape.clone());\n\t}\n\n\ttemplate<bool is_union>\n\tstd::ostream& operator<<(std::ostream& os, const Group<is_union>& shape)\n\t{\n\t\tos << (is_union ? \"Union de \" : \"Intersection de \" )<< shape.shapes.size() << \" formes\";\n\t\treturn os;\n\t}\n\n\n\ttemplate<bool is_union>\n\tGroup<is_union> Move(const Group<is_union>& group, coord_t dx, coord_t dy)\n\t{\n\t\ttypename Group<is_union>::shape_vec_t new_shapes;\n\t\tnew_shapes.reserve(group.shapes.size());\n\t\tfor (auto& shape : group.shapes)\n\t\t\tnew_shapes.emplace_back(Move(shape, dx, dy)); // les formes étants immutables 'TP4::Move' retourne une nouvelle forme\n\n\t\treturn Group<is_union>(std::move(new_shapes));\n\t}\n\n\ttemplate<bool is_union>\n\tbool Is_contained(const Group<is_union>& group, Point point)\n\t{\n\t\tfor (auto& shape : group.shapes)\n\t\t\tif ((!is_union) ^ Is_contained(shape, point))\n\t\t\t\treturn is_union;\n\t\treturn !is_union;\n\t}\n\n}\n\n#endif // !GROUP_H\n" }, { "alpha_fraction": 0.6103603839874268, "alphanum_fraction": 0.6126126050949097, "avg_line_length": 28.399999618530273, "blob_id": "158b8011b46a19fb42313d4ccd8bb62d5b1c832c", "content_id": "35e21a3fabd9d9e35c3256b124f079e5576d2332", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 445, "license_type": "permissive", "max_line_length": 89, "num_lines": 15, "path": "/TP1_BDDI/script droits d'accés/accessGrant.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "WINDOWS-1252", "text": "CREATE OR REPLACE PROCEDURE accessGrant\n ( userTarget IN varchar2 )\nis\n -- curseur pour parcourir toutes les tables\n cursor tableU is ( SELECT *\n FROM user_tables\n );\nBEGIN\n for t in tableU \n loop \n EXECUTE IMMEDIATE 'GRANT SELECT ON ' || t.table_name || ' TO ' || userTarget;\n end loop;\n \n DBMS_OUTPUT.PUT_LINE('droits sur toutes les tables à l utilisateur : ' || userTarget) ;\nend;\n\n\n\n" }, { "alpha_fraction": 0.6019476652145386, "alphanum_fraction": 0.6189896464347839, "avg_line_length": 15.257425308227539, "blob_id": "f3d7993096785372e1124a3c899c7071fa0d222a", "content_id": "cb044285ca54bbcd31cde9fbfec055fc86a7b009", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1643, "license_type": "permissive", "max_line_length": 68, "num_lines": 101, "path": "/TP2_Concurrency/question7.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <pthread.h>\n\n#define MAX_FACTORS 20\n\nstatic pthread_mutex_t mutexRead;\nstatic pthread_mutex_t mutexWrite;\n\n\nint get_prime_factors(uint64_t n, uint64_t* dest)\n{\n uint64_t i = 0;\n int cpt = 0;\n uint64_t nPrime = n;\n for( i = 2 ; i <= nPrime;)\n {\n\t\tif(nPrime % i == 0)\n\t\t{\n\t\t\tif(cpt < MAX_FACTORS)\n\t\t\t{\n\t\t\t\tdest[cpt++] = i;\n\t\t\t}\n\t\t\tnPrime = nPrime/i;\n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\ti++;\n\t\t\n\t}\n\treturn cpt;\n}\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t factors[MAX_FACTORS];\n\tint j,k;\n\tk=get_prime_factors(n,factors);\n\tpthread_mutex_lock(&mutexWrite);\n\tprintf(\"%ju: \",n);\n\tfor(j=0; j<k; j++)\n\t{\n\t\tprintf(\"%ju \",factors[j]);\n\t}\n\tprintf(\"\\n\");\n\tpthread_mutex_unlock(&mutexWrite);\n}\n\nvoid decompo_task(FILE* file)\n{\n\tchar line[60];\n\t\n\twhile(1)\n\t{\n\t\tpthread_mutex_lock(&mutexRead);\n\t\tif(fgets(line, 60, file) == NULL)\n\t\t{\n\t\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\tbreak;\n\t\t}\n\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\n\t\tprint_prime_factors(atoll(line));\n\t\n\t}\n}\n\nvoid* print_prime_factors_thread(void* n)\n{\n\tFILE* x = ((FILE*)n);\n\tdecompo_task(x);\n\treturn NULL;\n}\n\nint main(void)\n{\n\tFILE* primeList;\n\tprimeList = fopen(\"primes2.txt\", \"r\");\n\t\n\tpthread_t ta;\n\tpthread_t tb;\n\t\n\tif(primeList == NULL)\n\t{\n\t\tperror(\"erreur ouverture fichier\");\n\t\texit(-1);\n\t}\n\t\n\tpthread_mutex_init(&mutexRead, NULL);\n\tpthread_mutex_init(&mutexWrite, NULL);\n\tpthread_create (&ta, NULL, &print_prime_factors_thread, primeList);\n\tpthread_create (&tb, NULL, &print_prime_factors_thread, primeList);\n\tpthread_join (ta, NULL);\n\tpthread_join (tb, NULL);\n\t\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5064433217048645, "alphanum_fraction": 0.6284364461898804, "avg_line_length": 25.74712562561035, "blob_id": "b078ecd076bc21fdbff678eb964d3f63d7ebc242", "content_id": "100696189cf4bf9e698a9640791bb812214cf036", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2328, "license_type": "permissive", "max_line_length": 75, "num_lines": 87, "path": "/TP2_Archi/lcd__.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"msp430fg4618.h\"\n#include \"lcd.h\"\n\n/* Initialize the LCD_A controller\n \n claims P5.2-P5.4, P8, P9, and P10.0-P10.5\n assumes ACLK to be default 32khz (LFXT1)\n*/\nvoid lcd_init()\n{\n // our LCD screen is a SBLCDA4 => 4-mux operation (cf motherboard.pdf p6)\n \n // 4-mux operation needs all 4 common lines (COM0-COM3). COM0 has\n // its dedicated pin (pin 52, cf datasheet.pdf p3), so let's claim the\n // other three.\n P5DIR |= (BIT4 | BIT3 | BIT2); // pins are output direction\n P5SEL |= (BIT4 | BIT3 | BIT2); // select 'peripheral' function (VS GPIO)\n \n // Configure LCD controller (cf msp430.pdf page 750)\n LCDACTL = 0b00011101;\n // bit 0 turns on the LCD_A module\n // bit 1 unused\n // bit 2 enables LCD segments\n // bits 3-4 set LCD mux rate: 4-mux\n // bits 5-7 set LCD frequency\n \n // Configure port pins\n //\n // mappings are detailed on motherboard.pdf p19: our screen has 22\n // segments, wired to MCU pins S4 to S25 (shared with GPIO P8, P9,\n // and P10.0 to P10.5)\n LCDAPCTL0 = 0b01111110;\n // bit 0: MCU S0-S3 => not connected to the screen\n // bit 1: MCU S4-S7 => screen pins S0-S3 (P$14-P$11)\n // bit 2: MCU S8-S11 => screen pins S4-S7 (P$10-P$7)\n // bit 3: MCU S12-S15 => screen pins S8-S11 (P$6 -P$3)\n // bit 4: MCU S16-S19 => screen pins S12-S15 (P$2, P$1, P$19, P$20)\n // bit 5: MCU S20-S23 => screen pins S16-S19 (P$21-P$24)\n // bit 6: MCU S24-S25 => screen pins S20-21 (P$25, P$26)\n // bit 7: MCU S28-S31 => not connected to the screen\n \n LCDAPCTL1 = 0 ; // MCU S32-S39 => not connected to the screen\n \n\ttbNumber[0] = 0b01011111;\n\ttbNumber[1] = 0b00000110;\n\ttbNumber[2] = 0b01101011;\n\ttbNumber[3] = 0b00101111;\n\ttbNumber[4] = 0b00110110;\n\ttbNumber[5] = 0b00111101;\n\ttbNumber[6] = 0b01111100;\n\ttbNumber[7] = 0b00000111;\n\ttbNumber[8] = 0b01111111;\n\ttbNumber[9] = 0b00110111;\n}\n\nstatic void lcd_setall(unsigned char value)\n{\n\tfor(unsigned char* i = LCD_START; i <= LCD_END; ++i)\n\t\t*i = value;\n}\n\nvoid lcd_display_number(int number)\n{\n\tunsigned char* ptr;\n\tint n = number;\n\tfor(size_t i = 0; i < (size_t) log (number); ++i)\n\t{\n\t\t\n\t\tptr = (unsigned char*)(0x93 + i);\n\t\t*ptr = tbNumber[n % 10];\n\t\tn /= 10;\n\t}\n}\n\nvoid lcd_clear()\n{\n\tlcd_setall(0x00);\n}\n\nvoid lcd_fill()\n{\n\tlcd_setall(0xFF);\n}\n\n" }, { "alpha_fraction": 0.6005257964134216, "alphanum_fraction": 0.6089663505554199, "avg_line_length": 34.95024871826172, "blob_id": "0589530350f234724263294c21c1e18c1b81fcaf", "content_id": "177bf3b7ce1d208d8af9eccf850c1768e766453e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7260, "license_type": "permissive", "max_line_length": 164, "num_lines": 201, "path": "/TP2_cpp/sources/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "\n/********************************************************************************************\n\t\t\t\t\t\t\t\t\t\tmain.cpp\n\t\t\t\t\t\t\t\t\t\t--------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n********************************************************************************************/\n\n//----------------------------------------------------------------------------------- INCLUDE\n//--------------------------------------------------------------------------- Include système\n#include <iostream>\n#include <string>\n#include <type_traits>\t// std::underlying_type\n#include <limits>\t\t// std::numeric_limits\n#include <stdexcept>\t// std::range_error\n\n//------------------------------------------------------------------------- Include personnel\n#include \"capteur_event.h\"\n#include \"capteur_stat.h\"\n#include \"ville.h\"\n\n//------------------------------------------------------------------------------------ Usings\n//using namespace std::string_literals; // enables s-suffix for std::string literals\n\n\n\n//----------------------------------------------------------------- Enumération des commandes\n// Equivalent à 'enum class cmd : std::string {...};' (underlying type non intégral)\nenum class cmd { ADD, STATS_C, JAM_DH, STATS_D7, OPT, EXIT };\nnamespace { // Namespace anonyme permettant de rendre 'CMDS' et 'cmd_ut' locals\n\tusing cmd_ut = std::underlying_type<cmd>::type;\n\tconst std::string CMDS[] = { std::string(\"ADD\"), std::string(\"STATS_C\"), std::string(\"JAM_DH\"), std::string(\"STATS_D7\"), std::string(\"OPT\"), std::string(\"EXIT\") };\n}\nstd::string underlying(cmd command) { return CMDS[static_cast<cmd_ut>(command)]; }\ncmd overlying(const std::string& name) {\n\tfor (cmd_ut i = 0; i <= static_cast<cmd_ut>(cmd::EXIT); ++i)\n\t{\n\t\tif (name == CMDS[i])\n\t\t\treturn static_cast<cmd>(i);\n\t}\n\tthrow std::range_error(\"Given string out of 'cmd' enumeration range.\");\n}\n\n/// <summary> Trouve le premier mots d'une chaine de charactères </summary>\n/// <param name='str'> Chaine de charactères </param>\n/// <param name='begin_pos'> position à partir de la quelle faire la recherche </param>\n/// <param name='sep'> Charactère utilisé comme séparateur entre les mots </param>\n/// <returns> Le mots trouvé </returns>\nstatic inline std::string find_first_word(const std::string &str, size_t begin_pos)\n{\n\tsize_t word_end_pos = str.find_first_of(\" \\n\", begin_pos);\n\treturn str.substr(begin_pos, word_end_pos - begin_pos);\n}\n\nstatic inline TP2::capteur_stat::sensor_t read_integer_from_buffer(const std::string& buffer, size_t& begin_pos)\n{\n\tauto word = find_first_word(buffer, begin_pos);\n\tbegin_pos += word.length() + 1;\n\treturn static_cast<TP2::capteur_stat::sensor_t>(std::stoi(word));\n}\n\nstatic inline void next_buffer_word(const std::string& buffer, size_t& begin_pos)\n{\n\tauto word = find_first_word(buffer, begin_pos);\n\tbegin_pos += word.length() + 1;\n}\n\n/// <summary> Parse et execute la commande donnée en entrée </summary>\n/// <param name='town'> Commande à executer </param>\n/// <param name='command'> Commande à executer </param>\n/// <returns> Un booléen indiquant si la commande 'cmd::EXIT' a été reçue </returns>\nstatic inline bool process_command(TP2::ville& town, const std::string& buffer, size_t begin_pos, size_t end_pos)\n{\n\t// Determine la commande reçue\n\tauto word = find_first_word(buffer, begin_pos);\n\tcmd command = overlying(word);\n\tbegin_pos += word.length() + 1;\n\n\tswitch (command)\n\t{\n\tcase cmd::ADD:\n\t{\n\t\t// Id\n\t\tauto id = read_integer_from_buffer(buffer, begin_pos); // hour\n\n\t\t// Timestamp\n\t\tnext_buffer_word(buffer, begin_pos); // year (ignored)\n\t\tnext_buffer_word(buffer, begin_pos); // month (ignored)\n\t\tnext_buffer_word(buffer, begin_pos); // day (ignored)\n\t\tauto hour = read_integer_from_buffer(buffer, begin_pos); // hour\n\t\tauto min = read_integer_from_buffer(buffer, begin_pos); // minute\n\t\tauto d7 = read_integer_from_buffer(buffer, begin_pos); // day of week\n\n\t\t// Traffic\n\t\tTP2::traffic state = static_cast<TP2::traffic>(buffer[begin_pos]);\n\n\t\ttown.add_sensor(TP2::capteur_event(id, d7, hour, min, state));\n\t}\n\tbreak;\n\tcase cmd::STATS_C:\n\t{\n\t\tauto id = read_integer_from_buffer(buffer, begin_pos); // Id\n\n\t\tauto sens = town.get_sensor_stat_by_id(id);\n\t\tif (sens != nullptr)\n\t\t\tsens->show_time_distribution();\n\t}\n\tbreak;\n\tcase cmd::JAM_DH:\n\t{\n\t\tauto d7 = read_integer_from_buffer(buffer, begin_pos); // d7\n\t\ttown.show_day_traffic_by_hour(d7);\n\t}\n\tbreak;\n\tcase cmd::STATS_D7:\n\t{\n\t\tauto d7 = read_integer_from_buffer(buffer, begin_pos); // d7\n\t\ttown.show_day_traffic(d7);\n\t}\n\tbreak;\n\tcase cmd::OPT:\n\t{\n\t\tauto d7 = read_integer_from_buffer(buffer, begin_pos); // d7\n\t\tauto h_start = read_integer_from_buffer(buffer, begin_pos); // H start\n\t\tauto h_end = read_integer_from_buffer(buffer, begin_pos); // H end\n\t\tsize_t seg_count = static_cast<size_t>(read_integer_from_buffer(buffer, begin_pos)); // Seg count\n\n\t\t// Segments/Capteurs IDs\n\t\tTP2::vec<TP2::capteur_stat::sensor_t> seg_ids(seg_count, seg_count);\n\t\tfor (size_t i = 0; i < seg_count; ++i)\n\t\t\tseg_ids.add(read_integer_from_buffer(buffer, begin_pos));\n\n\t\ttown.show_optimal_timestamp(d7, h_start, h_end, seg_ids);\n\t}\n\tbreak;\n\tcase cmd::EXIT:\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n//-------------------------------------------------------------------------------------- MAIN\nint main()\n{\n\tTP2::ville lyon;\n\n\t// Buffer contenant une partie de l'entrée issue de stdin\n\tconst size_t BUFFER_SIZE = 2 * 2 * 2 * 131072;\n\tstd::string buffer(BUFFER_SIZE, ' ');\n\n\t// Positions de début et fin d'une commande dans le buffer\n\tsize_t cmd_begin_pos = 0;\n\tsize_t cmd_end_pos = 0;\n\n\t// Lit l'entrée par blocs en utilisant stdin pour des raisons de performances\n\tsize_t buffer_used_size = std::numeric_limits<size_t>::max();\n\tauto cut_cmd_beg = static_cast<std::string>(\"\"); // String contenant le début des commandes à cheval entre deux buffers\n\twhile (buffer_used_size >= BUFFER_SIZE)\n\t{\n\t\t// Lie une block issu de stdin\n\t\tbuffer_used_size = fread(&buffer[0], sizeof(char), BUFFER_SIZE, stdin);\n\n\t\t// Gère le cas des commandes à cheval entre deux buffers\n\t\tif (cmd_end_pos == std::string::npos)\n\t\t{\n\t\t\t// Recompose la commande\n\t\t\tcmd_end_pos = buffer.find_first_of('\\n', 0);\n\t\t\tcut_cmd_beg = cut_cmd_beg + buffer.substr(0, cmd_end_pos);\n\n\t\t\t// Parse et execute la commande\n\t\t\tif (process_command(lyon, cut_cmd_beg, 0, cut_cmd_beg.length()))\n\t\t\t\treturn EXIT_SUCCESS; // Commande 'EXIT' reçue\n\n\t\t\tcmd_begin_pos = cmd_end_pos + 1;\n\t\t}\n\t\telse\n\t\t\tcmd_begin_pos = 0;\n\n\t\tcmd_end_pos = 0;\n\t\twhile (cmd_end_pos != std::string::npos && cmd_begin_pos < buffer_used_size)\n\t\t{\n\t\t\t// Determine la position de fin de la commande dans le buffer\n\t\t\tcmd_end_pos = buffer.find_first_of('\\n', cmd_begin_pos);\n\n\t\t\t// Si la commande est entièrement contenue dans le buffer...\n\t\t\tif (cmd_end_pos != std::string::npos)\n\t\t\t{\n\t\t\t\t// Parse et execute la commande\n\t\t\t\tif (process_command(lyon, buffer, cmd_begin_pos, cmd_end_pos))\n\t\t\t\t\treturn EXIT_SUCCESS; // Commande 'EXIT' reçue\n\n\t\t\t\t// Determine la position de début de la prochaine commande dans le buffer\n\t\t\t\tcmd_begin_pos = cmd_end_pos + 1;\n\t\t\t}\n\t\t\telse\n\t\t\t\t// On retient le début de la commande à cheval entre deux buffers\n\t\t\t\tcut_cmd_beg = buffer.substr(cmd_begin_pos, buffer_used_size - cmd_begin_pos);\n\t\t}\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6379363536834717, "alphanum_fraction": 0.6379363536834717, "avg_line_length": 37.53571319580078, "blob_id": "c73f4b80a82aee7865a01a102ee643c3225a5f19", "content_id": "a0f6b0956e5d348f5519ebdc5263b9a88ce87130", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3254, "license_type": "permissive", "max_line_length": 178, "num_lines": 84, "path": "/TP1_Reseau/Client/src/Client/controller/Login_controller.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package Client.controller;\n\nimport Client.Navigator;\nimport Client.RMI_DAL;\nimport javafx.application.Platform;\nimport javafx.fxml.FXML;\nimport javafx.event.ActionEvent;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.TextField;\n\n/**\n * Controlleur correspondant à la vue Login_view.fxml.\n * Cette classe utilise le DAL pour permettre à l'utilisateur de se connecter.\n * Ce controlleur vérifie, grâce au DAL, si le mots de passe ou le nom d'utilisateur est correct et déclenche l'affichage d'un message d'erreur dans ce cas.\n * Si l'utilisateur parvient a se connecter, ce controlleur navige vers la vue Groups_view et si l'utilisateur veux créer un nouveau compte, il navige vers la vue NewAccountView.\n */\npublic class Login_controller {\n\n /**\n * Fournit le DAL et le navigateur qui seront utilisés par le controlleur.\n * @param nav L'objet de type Navigator permettant de naviger facilement d'une vue à l'autre\n * @param dal Le DAL que le controlleur utilisera pour comuniquer avec le serveur\n */\n public void init(Navigator nav, RMI_DAL dal) {\n m_navigator = nav;\n\n if(dal == null) {\n m_dal = new RMI_DAL(\"localhost\", (Exception e) -> {\n // TODO: show popup with connection retry\n });\n\n m_dal.open();\n }\n else {\n m_dal = dal;\n }\n }\n\n @FXML protected void FocusOnPasswordTextField(ActionEvent event) {\n //TODO: focus on password text field\n }\n\n /**\n * Méthode appelée par la vue pour essayer de se connecter avec le nom d'utilisateur et le mots de passe donnés dans les TextBox correspondantes.\n * Cette méthode est appelée lorsque l'utilisateur appuie sur le boutton 'Login' ou appuie sur 'Enter' pendent que le focus est sur la TextBox du mots de passe.\n */\n @FXML protected void SubmitCredentials(ActionEvent event) {\n String password = PasswordTextField.getText();\n String username = UsernameTextField.getText();\n\n if(!username.equals(\"\") && !password.equals(\"\"))\n ErrorMessageLabel.setVisible(false);\n\n m_dal.SubmitCredentials(username, password, user -> {\n Platform.runLater(() -> {\n if(user != null) {\n // Goto Groups_view\n ErrorMessageLabel.setVisible(false);\n m_dal.setErrorCallback(null);\n m_navigator.showGroupsPage(m_dal, user);\n }\n else\n // Show error message\n ErrorMessageLabel.setVisible(true);\n });\n });\n }\n\n /**\n * Méthode appelée par la vue pour naviger vers la vue NewAccount_view.\n * Cette méthode est appelée lorsque l'utilisateur appuie sur le boutton 'Create new account'.\n */\n @FXML protected void CreateNewAccount(ActionEvent event) {\n m_dal.setErrorCallback(null);\n m_navigator.showNewAccountPage(m_dal);\n }\n\n @FXML protected TextField UsernameTextField;\n @FXML protected TextField PasswordTextField;\n @FXML protected Label ErrorMessageLabel;\n\n private Navigator m_navigator = null;\n private RMI_DAL m_dal;\n}\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5424836874008179, "avg_line_length": 10.769230842590332, "blob_id": "f6409b752fe4a13c836b46c79479f777abe822d7", "content_id": "b5ae500451db219b16abf5ab7016d99c0491bbf7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 153, "license_type": "permissive", "max_line_length": 30, "num_lines": 13, "path": "/TD_Archi_cache/TD_cache_ex1.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"N.h\"\n\nint main()\n{\n\tdouble v[N];\n\tdouble sum = 0;\n\n\tfor(size_t i = 0; i < N; i++)\n\t\tsum += v[i];\n\t\n\treturn EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5869038105010986, "alphanum_fraction": 0.590945839881897, "avg_line_length": 24.494844436645508, "blob_id": "c26decdf8ba1e07481eed60e0e970254690f2ad7", "content_id": "6df02bbb1376e705e1865c3bd1438b4657054d8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2480, "license_type": "permissive", "max_line_length": 92, "num_lines": 97, "path": "/TP4_cpp/makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-16", "text": "############################################################################################\n################################## GENERIC MAKEFILE ########################################\n############################################################################################\n# TODO: gĂrer les sous-dossiers / fichiers ayants le mĂȘmes noms dans des dossiers diffĂ©rts\n# TODO: gĂrer les extentions .hpp, .cxx, ...\n\n# Debug mode (comment this line to build project in release mode)\n#DEBUG = true\n\n# Compiler\nCC = g++\n# Command used to remove files\nRM = rm -f\n# Compiler and pre-processor options\nCPPFLAGS = -Wall -std=c++11 -Ofast\n# Debug flags\nDEBUGFLAGS = -g\n# Resulting program file name\nEXE_NAME = geometry\n# The source file extentions\nSRC_EXT = cpp\n# The header file types\n# TODO allow .hpp header files\nHDR_EXT = h\n\nTEST_SCRIPT = ./tests/mktest.sh ./tests\n\n# Source directory\nSRCDIR = src\n# Headers directory\nINCDIR = src\n# Main output directory\nOUTPUT_DIR = bin\n# Release output directory\nRELEASEDIR = release\n# Debug output directory\nDEBUGDIR = debug\n# Dependency files directory\nDEPDIR = dep\n# Libraries paths\nLIB_DIRS = -L /mingw64/lib\n# Library file names (e.g. '-lboost_serialization-mt')\nLIBS = -lboost_serialization-mt\n# List of include paths\nINCLUDES = ./$(INCDIR) #\"/c/Program Files (x86)/boost_1_60_0\"\n\nifdef DEBUG\nBUILD_PATH = ./$(OUTPUT_DIR)/$(DEBUGDIR)\nelse\nDEBUGFLAGS = \nBUILD_PATH = ./$(OUTPUT_DIR)/$(RELEASEDIR)\nendif\n# Source directory path\nSRC_PATH = ./$(SRCDIR)\n# Dependencies path\nDEP_PATH = ./$(BUILD_PATH)/$(DEPDIR)\n\n# List of source files\nSOURCES = $(wildcard $(SRC_PATH)/*.$(SRC_EXT))\n# List of object files\nOBJS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(BUILD_PATH)/%.o)\n# List of dependency files\nDEPS = $(SOURCES:$(SRC_PATH)/%.$(SRC_EXT)=$(DEP_PATH)/%.d)\n\n.PHONY: all clean rebuild help test\n\nall: $(BUILD_PATH)/$(EXE_NAME)\n\nclean:\n\t$(RM) $(BUILD_PATH)/*.o\n\t$(RM) $(BUILD_PATH)/$(EXE_NAME)\n\t$(RM) $(DEP_PATH)/*.d\n\t\nrebuild: clean all\n\nhelp:\n\t@echo '\t\t\t\t### MAKEFILE HELP ###'\n\t@echo 'PHONY TARGETS:'\n\t@echo '\tall \t...'\n\t@echo '\tclean \t...'\n\t@echo '\trebuild ...'\n\t@echo '\thelp\t...'\n\ntest:\n\t@cd tests/\n\t$(TEST_SCRIPT)\n\n# Build object files\n$(BUILD_PATH)/%.o: $(SRC_PATH)/%.$(SRC_EXT)\n\t@mkdir -p $(DEP_PATH)\n\t$(CC) $(CPPFLAGS) $(DEBUGFLAGS) -I $(INCLUDES) -MMD -MP -MF $(DEP_PATH)/$*.d -c $< -o $@\n\n# Build main target\n$(BUILD_PATH)/$(EXE_NAME): $(OBJS)\n\t$(CC) $(LIB_DIRS) -o $(BUILD_PATH)/$(EXE_NAME) $(OBJS) $(LIBS)\n\n# -lboost_serialization\n\n" }, { "alpha_fraction": 0.6660499572753906, "alphanum_fraction": 0.6679000854492188, "avg_line_length": 24.435293197631836, "blob_id": "06c5f5c3dffecc6d74432fdd559b2f98fc300e82", "content_id": "bbe8a1cd95a73b26eb6c1650942c39c36d11bfda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4324, "license_type": "permissive", "max_line_length": 99, "num_lines": 170, "path": "/TP4_cpp/src/Scene.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"Scene.h\"\n\n#include <fstream>\n#include <tuple>\n\n#include \"Group.h\"\n#include \"Segment.h\"\n#include \"Polygon.h\"\n#include \"rectangle.h\"\n#include \"Serializable_shape_history.h\"\n\nnamespace TP4\n{\n\tvoid Scene::Add_segment(name_t name, Point x, Point y)\n\t{\n\t\tm_shapes.commit();\n\t\tauto segment = make_segment(x, y);\n\t\tif (!segment)\n\t\t\tthrow std::invalid_argument(\"Invalid segment\");\n\n\t\tbool inserted;\n\t\tstd::tie(std::ignore, inserted) = m_shapes.current().emplace(std::move(name), segment.value());\n\t\tif (!inserted)\n\t\t\tthrow std::invalid_argument(\"Shape name already existing\");\n\t}\n\n\tvoid Scene::Add_rectangle(name_t name, Point x, Point y)\n\t{\n\t\tm_shapes.commit();\n\t\tauto rectangle = make_rectangle(x, y);\n\t\tif (!rectangle)\n\t\t\tthrow std::invalid_argument(\"Invalid rectangle\");\n\n\t\tbool inserted;\n\t\tstd::tie(std::ignore, inserted) = m_shapes.current().emplace(std::move(name), rectangle.value());\n\t\tif (!inserted)\n\t\t\tthrow std::invalid_argument(\"Shape name already existing\");\n\t}\n\n\tvoid Scene::Add_polygon(name_t name, const std::vector<Point>& vertices)\n\t{\n\t\tm_shapes.commit();\n\t\tauto polygon = make_polygon(vertices);\n\t\tif (!polygon)\n\t\t\tthrow std::invalid_argument(\"Invalid polygon\");\n\n\t\tbool inserted;\n\t\tstd::tie(std::ignore, inserted) = m_shapes.current().emplace(std::move(name), polygon.value());\n\t\tif (!inserted)\n\t\t\tthrow std::invalid_argument(\"Shape name already existing\");\n\t}\n\n\tvoid Scene::Delete(const std::vector<name_t>& shapes_names)\n\t{\n\t\tm_shapes.commit();\n\t\tusing it_t = History_state::const_iterator;\n\t\tauto& current_shapes = m_shapes.current();\n\n\t\tstd::vector<it_t> shape_iterators;\n\n\t\tfor (const auto& shape_name : shapes_names)\n\t\t{\n\t\t\tit_t it = current_shapes.find(shape_name);\n\t\t\tif (it == std::end(current_shapes)) // C++ 14: std::cend\n\t\t\t\tthrow std::invalid_argument(\"One or more shape name is invalid\");\n\t\t\tshape_iterators.push_back(it);\n\t\t}\n\n\t\tfor (auto& it : shape_iterators)\n\t\t\tcurrent_shapes.erase(it);\n\t}\n\n\tvoid Scene::Union(name_t union_name, const std::unordered_set<name_t>& shapes_names)\n\t{\n\t\tCreate_group<Shape_union>(union_name, shapes_names);\n\t}\n\n\tvoid Scene::Intersect(name_t inter_name, const std::unordered_set<name_t>& shapes_names)\n\t{\n\t\tCreate_group<Shape_intersection>(inter_name, shapes_names);\n\t}\n\n\tbool Scene::Is_point_contained_by(Point point, name_t shape_name) const\n\t{\n\t\tconst auto& current_shapes = m_shapes.current();\n\t\tauto it = current_shapes.find(shape_name);\n\t\tif (it == std::end(current_shapes)) // C++ 14: std::cend\n\t\t\tthrow std::invalid_argument(\"Invalid shape name\");\n\n\t\treturn Is_contained(it->second, point);\n\t}\n\n\tvoid Scene::Move_shape(name_t shape_name, coord_t dx, coord_t dy)\n\t{\n\t\tm_shapes.commit();\n\t\tauto& current_shapes = m_shapes.current();\n\t\tauto it = current_shapes.find(shape_name);\n\t\tif (it == std::end(current_shapes)) // C++ 14: std::cend\n\t\t\tthrow std::invalid_argument(\"Invalid shape name\");\n\n\t\tit->second = Move(it->second, dx, dy);\n\t}\n\n\tvoid Scene::ClearAll()\n\t{\n\t\tm_shapes.clear();\n\t}\n\n\tvoid Scene::ClearCurrentState()\n\t{\n\t\tm_shapes.commit();\n\t\tm_shapes.current().clear();\n\t}\n\n\tvoid Scene::Undo()\n\t{\n\t\tm_shapes.undo();\n\t}\n\n\tvoid Scene::Redo()\n\t{\n\t\tm_shapes.redo();\n\t}\n\n\tvoid Scene::List()\n\t{\n\t\tif (m_shapes.current().size() == 0)\n\t\t\tstd::cout << \"Aucunes formes\" << std::endl;\n\t\telse\n\t\t{\n\t\t\tfor (const auto& shape : m_shapes.current())\n\t\t\t{\n\t\t\t\tstd::cout << \"* \" << shape.first << \" :\\t\";\n\t\t\t\tPrint(shape.second);\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Scene::Load(std::string filename)\n\t{\n\t\tstd::ifstream in_fstream;\n\t\tin_fstream.open(filename);\n\t\tif (!in_fstream.is_open())\n\t\t\tthrow std::invalid_argument(\"Wrong file name\");\n\n\t\tboost::archive::xml_iarchive archive(in_fstream);\n\n\t\tm_shapes.commit();\n\t\tauto& current_shapes = m_shapes.current();\n\t\tcurrent_shapes.clear();\n\n\t\tarchive >> boost::serialization::make_nvp(\"shapes\", current_shapes);\n\t\t// archive and stream are closed when destructors are called\n\t}\n\n\tvoid Scene::Save(std::string filename)\n\t{\n\t\tconst auto& current_shapes = m_shapes.current();\n\n\t\tstd::ofstream out_fstream;\n\t\tout_fstream.open(filename);\n\t\tif (!out_fstream.is_open())\n\t\t\tthrow std::invalid_argument(\"Wrong file name\");\n\n\t\tboost::archive::xml_oarchive archive(out_fstream);\n\t\tarchive << boost::serialization::make_nvp(\"shapes\", current_shapes);\n\t\t// archive and stream are closed when destructors are called\n\t}\n}\n" }, { "alpha_fraction": 0.5355687141418457, "alphanum_fraction": 0.5500185489654541, "avg_line_length": 34.03895950317383, "blob_id": "ac3ce9f66fc96433beaedb99bf2f5fdec492872d", "content_id": "17b8343e7041a54b2fefb7d3f4faa6cf30374284", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5404, "license_type": "permissive", "max_line_length": 181, "num_lines": 154, "path": "/TP4_cpp/src/Benchmark.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tBenchmark\n\t\t\t\t\t\t\t\t\t---------\n*********************************************************************************/\n\n#ifndef BENCHMARK_H\n#define BENCHMARK_H\n\n#include <chrono>\n#include <iostream>\n#include <functional>\n\n#include \"Scene.h\"\n\nnamespace TP4\n{\n\tnamespace\n\t{\n\t\t//! Focntion permmetant la mesure du temps d'execution d'une fonction donnée en paramètre.\n\t\t//! On assume que la fonction répéte une action élémentaire 'repeat_count' fois.\n\t\tvoid benchmark(const std::string& bench_name, unsigned int repeat_count, std::function<void(void)> benchmark_func);\n\t}\n\n\t//! Execute tous les benchmarks en manipulant une'TP4::Scene'\n\tinline void execute_benchmarks(TP4::Scene& geometry_scene, unsigned int repetition_count)\n\t{\n\t\tstd::cout << \"\\x1b[33m\" << std::endl\n\t\t\t<< R\"( _____ ___ _ _ ___ _ _ ___ ___ _ _ ___ _ _ __ __ _ ___ _ _____ _ _ ___ )\" << std::endl\n\t\t\t<< R\"( |_ _| _ \\ | | / __|| |_ _| |_ ___ | _ ) __| \\| |/ __| || | \\/ | /_\\ | _ \\ |/ /_ _| \\| |/ __|)\" << std::endl\n\t\t\t<< R\"( | | | _/_ _| | (_|_ _|_ _| |___| | _ \\ _|| .` | (__| __ | |\\/| |/ _ \\| / ' < | || .` | (_ |)\" << std::endl\n\t\t\t<< R\"( |_| |_| |_| \\___||_| |_| |___/___|_|\\_|\\___|_||_|_| |_/_/ \\_\\_|_\\_|\\_\\___|_|\\_|\\___|)\" << std::endl << \"\\x1b[0m\" << std::endl;\n\n\t\tgeometry_scene.ClearAll();\n\n\t\t// Creation of 'repetition_count' rectangles\n\t\tbenchmark(\"Rectangle creation\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tstatic const TP4::Point p1{ 1, 8 };\n\t\t\tstatic const TP4::Point p2{ 4, 2 };\n\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t\tgeometry_scene.Add_rectangle(\"rect\" + std::to_string(i), p1, p2);\n\t\t});\n\n\t\tgeometry_scene.ClearAll();\n\n\t\t// Creation of 'repetition_count' rectangles and undoing them\n\t\tbenchmark(\"Rectangle creation with undo\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tstatic const TP4::Point p1{ 1, 8 };\n\t\t\tstatic const TP4::Point p2{ 4, 2 };\n\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t{\n\t\t\t\tgeometry_scene.Add_rectangle(\"rect\" + std::to_string(i), p1, p2);\n\t\t\t\tgeometry_scene.Undo();\n\t\t\t}\n\t\t});\n\n\t\tgeometry_scene.ClearAll();\n\n\t\t// Creation of 'repetition_count' rectangles and undoing/redoing them\n\t\tbenchmark(\"Rectangle creation with undo/redo\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tstatic const TP4::Point p1{ 1, 8 };\n\t\t\tstatic const TP4::Point p2{ 4, 2 };\n\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t{\n\t\t\t\tgeometry_scene.Add_rectangle(\"rect\" + std::to_string(i), p1, p2);\n\t\t\t\tgeometry_scene.Undo();\n\t\t\t\tgeometry_scene.Redo();\n\t\t\t}\n\t\t});\n\n\t\tgeometry_scene.ClearAll();\n\n\t\t// Creation of 'repetition_count' polygons of 4 vertices\n\t\tbenchmark(\"Polygon creation\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tstatic const std::vector<TP4::Point> vertices{ { 0, 0 },{ 0, 1 },{ 1, 1 },{ 1, 0 } };\n\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t\tgeometry_scene.Add_polygon(\"poly\" + std::to_string(i), vertices);\n\t\t});\n\n\t\tgeometry_scene.ClearAll();\n\n\t\t// Creation of 'repetition_count' intersections of rectangles and segments\n\t\tbenchmark(\"Intersection creation\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tstatic const TP4::Point p1{ 1, 8 };\n\t\t\tstatic const TP4::Point p2{ 4, 2 };\n\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t{\n\t\t\t\tauto i_str = std::to_string(i);\n\t\t\t\tgeometry_scene.Add_segment(\"seg\" + i_str, p1, p2);\n\t\t\t\tgeometry_scene.Add_rectangle(\"rect\" + i_str, p1, p2);\n\t\t\t\tgeometry_scene.Intersect(\"inter\" + i_str, { \"seg\" + i_str, \"rect\" + i_str });\n\t\t\t}\n\t\t});\n\n\t\t// Save and load 'repetition_count/40' XML files\n\t\trepetition_count /= 40;\n\t\tbenchmark(\"XML serialisation of \" + std::to_string(40 * repetition_count) + \" intersections\", repetition_count, [&geometry_scene, repetition_count]()\n\t\t{\n\t\t\tunsigned int i = repetition_count + 1;\n\t\t\twhile (--i)\n\t\t\t{\n\t\t\t\tgeometry_scene.Save(\"test.xml\");\n\t\t\t\tgeometry_scene.ClearCurrentState();\n\t\t\t\tgeometry_scene.Load(\"test.xml\");\n\t\t\t}\n\t\t});\n\n\t\tgeometry_scene.ClearAll();\n\n\t\tstd::cout << std::endl << std::endl << \"Press ENTER to continue...\";\n\t\tstd::cin.get();\n\t}\n\n\tnamespace\n\t{\n\t\tvoid benchmark(const std::string& bench_name, unsigned int repeat_count, std::function<void(void)> benchmark_func)\n\t\t{\n\t\t\tstatic unsigned bench_count = 0;\n\n\t\t\tif (bench_name.empty())\n\t\t\t\tstd::cout << std::endl << std::endl << std::endl << \"############# BENCHMARK \" << ++bench_count << \" #############\" << std::endl << std::endl;\n\t\t\telse\n\t\t\t\tstd::cout << std::endl << std::endl << \"############# BENCHMARK \" << ++bench_count << \" (\" << bench_name << \") #############\" << std::endl;\n\n\t\t\tauto start = std::chrono::steady_clock::now();\n\n\t\t\tbenchmark_func();\n\n\t\t\tauto end = std::chrono::steady_clock::now();\n\t\t\tauto diff = end - start;\n\n\t\t\tstd::cout << \"Executed benchmark \" << repeat_count << \" times\" << std::endl;\n\t\t\tstd::cout << \"Total execution time : \" << std::chrono::duration<double, std::milli>(diff).count() << \" ms\" << std::endl;\n\t\t\tstd::cout << \"Execution mean time : \\x1b[32m\" << std::chrono::duration<double, std::micro>(diff / repeat_count).count() << \" us \\x1b[0m(micro seconds)\" << std::endl << std::endl;\n\t\t\tstd::cout << \"############################################################\";\n\t\t}\n\t}\n}\n\n#endif // !BENCHMARK_H\n\n\n" }, { "alpha_fraction": 0.7147790193557739, "alphanum_fraction": 0.7279005646705627, "avg_line_length": 26.846153259277344, "blob_id": "a44924e69b830d4296e15ced8b34544647d2bc6b", "content_id": "1f6df3d3dda0c9730f96e717cf00d637ec6fa6e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1472, "license_type": "permissive", "max_line_length": 133, "num_lines": 52, "path": "/TP1_TP2_Reseau_rendu/VersionRMI (inachevée)/Shared/src/shared/Group.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package shared;\n\nimport java.io.Serializable;\nimport java.util.*;\n\n/**\n * Classe représentant un groupe ou une room ayant un nom et une date de création.\n * Un groupe est une room regroupant des utilisateurs pouvant chatter ensembles.\n * La classe est serialisable et peut gènerer un hash.\n */\npublic class Group implements Serializable {\n\n\t/**\n\t * Constructeur créant un Group à partir de son nom et de sa date de création.\n\t * @param creation Date de création\n\t * @param groupName Nom du groupe\n\t */\n\tpublic Group(Date creation, String groupName)\n\t{\n\t\tthis.creation = creation;\n\t\tthis.groupName = groupName;\n\t}\n\n\t/**\n\t * Génère un hash pour un instance de la classe Group.\n\t * @return Un int pouvant être utilisé comme hash.\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\treturn groupName.hashCode();\n\t}\n\n\t/**\n\t * Vérifie l'égalitée entre l'objet donné en paramètre et l'instance courante.\n\t * @param other L'objet avec le quel l'instance courante est comparée.\n\t * @return Un booléen indiquant l'égalité\n\t */\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif(other instanceof Group)\n\t\t\treturn ((Group)other).groupName.equals(groupName);\n\t\treturn false;\n\t}\n\t\n\tpublic final Date creation;\n\tpublic final String groupName;\n\n\t/**\n\t * Numéro identifiant la classe lors de la serialization (utilisé pour verifier la présence de la classe lors de la déserialization)\n\t */\n\tprivate static final long serialVersionUID = 4964625258033421772L;\n}\n" }, { "alpha_fraction": 0.39345991611480713, "alphanum_fraction": 0.40084388852119446, "avg_line_length": 41.13333511352539, "blob_id": "5c5353ebee1cfc70390ac673fcbb79265a00c940", "content_id": "76ba502f08ec7ea3d09b5b6ff9fd2431e3cefea3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1901, "license_type": "permissive", "max_line_length": 74, "num_lines": 45, "path": "/TP1_Concurrency/include/Heure.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\t\t\t\t Heure.h - description\n\t\t\t\t\t\t\t -------------------\n\tdébut : Mercredi 03 février 2016\n\tcopyright : (C) 2016 par Mathieu Maranzana\n\te-mail : [email protected]\n*************************************************************************/\n\n//---------- Interface de la tache <Heure> (fichier Heure.h) -------------\n#ifndef HEURE_H\n#define HEURE_H\n\n//------------------------------------------------------------------------\n// Rôle de la tache <Heure>\n// Cette tache est chargee de l'affichage periodique (toutes les\n// <PERIODE> secondes (on pose <PERIODE> = 1 seconde)) de l'heure\n// courante dans la zone adequate de l'ecran du TP (en haut, a droite).\n// La fin de la tache <Heure> est declenchee a la reception du\n// signal <SIGUSR2>.\n//------------------------------------------------------------------------\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//--------------------------------------------------- Interfaces utilisees\n\n//------------------------------------------------------------- Constantes\n\n//------------------------------------------------------------------ Types\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//---------------------------------------------------- Fonctions publiques\npid_t ActiverHeure(void);\n// Mode d'emploi :\n// - cette fonction lance une tache fille <Heure> chargee de\n// l'affichage periodique (toutes les <PERIODE> secondes) de l'heure\n// courante dans la zone <HEURE> de l'ecran du TP\n// - la fin de la tache <Heure> est declenchee à la reception du\n// signal <SIGUSR2>\n// - renvoie le PID de la tache <Heure>, si sa creation se passe bien\n// - renvoie -1 en cas d'echec à la creation de la tache <Heure>\n//\n// Contrat : aucun\n//\n\n\n#endif // HEURE_H\n" }, { "alpha_fraction": 0.5619062185287476, "alphanum_fraction": 0.5706276297569275, "avg_line_length": 19.70967674255371, "blob_id": "7aff7e2bef9b533aebd33aed419d961d3dcd6081", "content_id": "c7622fc1ac29e026d11a8cc3e87d64a7c699c144", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6421, "license_type": "permissive", "max_line_length": 91, "num_lines": 310, "path": "/TD4_ALG/all_in_one_fucking_file_with_shitty_old_c_0AC_code_(only_fucking_way_to_compile_using_domjudge_ice_age__compiler_!!).c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#define HASH_TABLE_REPETITION 1\n//#define DEFAULT_HASH_TABLE_SIZE 100\n\ntypedef enum { empty, used, deleted } status;\n\ntypedef struct\n{\n\tstatus state;\n\tchar* key;\n\tchar* value;\n} cell;\n\ntypedef struct\n{\n\tunsigned int m;\n\tcell* array;\n\tunsigned int array_step;\n\tunsigned int array_size;\n\tunsigned int deleted_count;\n\tunsigned int used_count;\n} hash_table;\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, unsigned int m);\nvoid destr_hash_table(hash_table* table);\nvoid show_stats(hash_table* table);\nvoid insert_to_table(hash_table* table, char* key, char* value);\nvoid remove_from_table(hash_table* table, char* key);\nvoid find_in_table(hash_table* table, char* key);\n\nstatic unsigned int hash(char* chaine, unsigned int m);\nstatic unsigned int shift_rotate(unsigned int val, unsigned int n);\nstatic unsigned int find_index_of(hash_table* table, char* key, unsigned int h);\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, unsigned int m)\n{\n\tif (table != NULL)\n\t{\n\t\ttable->m = m;\n\t\ttable->array_size = repetition*m;\n\t\ttable->array_step = repetition;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\n\t\ttable->array = (cell*)malloc(table->array_size*sizeof(cell));\n\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tc->state = empty;\n\t\t\tc->key = NULL;\n\t\t\tc->value = NULL;\n\t\t}\n\t}\n}\n\nvoid destr_hash_table(hash_table* table)\n{\n\tif (table != NULL)\n\t{\n\t\t// Free all allocated strings\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tif (c != NULL)\n\t\t\t{\n\t\t\t\tif(c->key != NULL)\n\t\t\t\t\tfree(c->key);\n\t\t\t\tif (c->value != NULL)\n\t\t\t\t\tfree(c->value);\n\t\t\t}\n\t\t}\n\n\t\t// Free table of cells\n\t\tfree(table->array);\n\t\ttable->array = NULL;\n\n\t\ttable->array_size = 0;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\t}\n}\n\nvoid show_stats(hash_table* table)\n{\n\tif (table != NULL)\n\t{\n\t\tprintf(\"size : %d\\r\\n\", table->array_size);\n\t\tprintf(\"empty : %d\\r\\n\", table->array_size - table->used_count - table->deleted_count);\n\t\tprintf(\"deleted : %d\\r\\n\", table->deleted_count);\n\t\tprintf(\"used : %d\\r\\n\", table->used_count);\n\t}\n}\n\nvoid insert_to_table(hash_table* table, char* key, char* value)\n{\n\tif (table != NULL && key != NULL && value != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\t// update cell value\n\t\t\tcell* c = &table->array[idx];\n\t\t\tfree(c->value);\n\t\t\tc->value = value;\n\n\t\t\tfree(key);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tunsigned int i;\n\t\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t\t{\n\t\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\t\tif (c->state == deleted)\n\t\t\t\t{\n\t\t\t\t\tif (strcmp(c->key, key) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tc->state = used;\n\t\t\t\t\t\ttable->used_count++;\n\t\t\t\t\t\tc->value = value;\n\n\t\t\t\t\t\tfree(key);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (c->state == empty)\n\t\t\t\t{\n\t\t\t\t\tc->state = used;\n\t\t\t\t\ttable->used_count++;\n\t\t\t\t\tfree(c->key);\n\t\t\t\t\tc->key = key;\n\t\t\t\t\tfree(c->value);\n\t\t\t\t\tc->value = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(key);\n\tfree(value);\n}\n\nvoid remove_from_table(hash_table* table, char* key)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\tcell* c = &table->array[idx];\n\t\t\tif (c->state == used) // TODO: useless if ?\n\t\t\t{\n\t\t\t\ttable->used_count--;\n\t\t\t\tc->state = deleted;\n\t\t\t\ttable->deleted_count++;\n\n\t\t\t\tfree(c->value);\n\t\t\t\tc->value = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(key);\n}\n\nvoid find_in_table(hash_table* table, char* key)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\t\tfree(key);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\tprintf(\"%s\\r\\n\", table->array[idx].value);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprintf(\"Not found\\r\\n\");\n}\n\nstatic unsigned int find_index_of(hash_table* table, char* key, unsigned int h)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int i;\n\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\tif (c->state == used)\n\t\t\t{\n\t\t\t\tif (strcmp(c->key, key) == 0)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn 65535;\n}\n\n/* encodage d'une chaine de caracteres sous la forme d'un entier non signe */\nstatic unsigned int shift_rotate(unsigned int val, unsigned int n)\n{\n\tn = n % (sizeof(unsigned int) * 8);\n\treturn (val << n) | (val >> (sizeof(unsigned int) * 8 - n));\n}\n\n/* fonction de hachage d'une chaine de caracteres */\nstatic unsigned int hash(char* chaine, unsigned int m)\n{\n\tunsigned int i;\n\tunsigned int h = 0;\n\tfor (i = 0; i < strlen(chaine); i++)\n\t{\n\t\th = h + shift_rotate(chaine[i], i * 7);\n\t}\n\treturn h % m;\n}\n\nvoid error(void);\n\nint main(void) \n{\n int size;\n char lecture[100];\n \n char * key;\n char * val;\n hash_table table;\n\n if (fscanf(stdin,\"%99s\", lecture)!=1)\n error();\n while (strcmp(lecture,\"bye\")!=0)\n {\n if (strcmp(lecture,\"init\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n size = atoi(lecture);\n\t\t \n // code d'initialisation\n\t\t init_hash_table(&table, HASH_TABLE_REPETITION, size);\n }\n else if (strcmp(lecture,\"insert\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n val = strdup(lecture);\n\t\t \n // insertion\n\t\t insert_to_table(&table, key, val);\n }\n else if (strcmp(lecture,\"delete\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n\t\t \n // suppression\n\t\t remove_from_table(&table, key); \n }\n else if (strcmp(lecture,\"query\")==0)\n {\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n key = strdup(lecture);\n\t\t\t\n // recherche et affiche le resultat\n\t\t find_in_table(&table, key);\t\t \n }\n else if (strcmp(lecture,\"destroy\")==0)\n {\n // destruction\n\t\t destr_hash_table(&table);\n }\n else if (strcmp(lecture,\"stats\")==0)\n {\n // statistiques\n\t\t show_stats(&table);\n }\n\n if (fscanf(stdin,\"%99s\",lecture)!=1)\n error();\n }\n return 0;\n}\n\nvoid error(void)\n{\n printf(\"input error\\r\\n\");\n exit(0);\n}\n\n" }, { "alpha_fraction": 0.7091357111930847, "alphanum_fraction": 0.756157636642456, "avg_line_length": 23.80555534362793, "blob_id": "25a3aef5a74f1a879c6726490668850e2f39fd24", "content_id": "13d5c0d486a9d3bfbd265eb4c3d72b20f0018b8b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 4466, "license_type": "permissive", "max_line_length": 67, "num_lines": 180, "path": "/TP1_SQL/mondial-schema_a_distribuer.sql", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "\nALTER SESSION SET NLS_DATE_FORMAT = 'DD MM SYYYY';\n-- SYYYY means 4-digit-year, S prefixes BC years with \"-\"\n\nCREATE TABLE Country\n(Name VARCHAR2(32),\n Code VARCHAR2(4) CONSTRAINT CountryKey PRIMARY KEY,\n Capital VARCHAR2(35),\n Province VARCHAR2(32),\n Area NUMBER ,\n Population NUMBER );\n\nCREATE TABLE City\n(Name VARCHAR2(35),\n Country VARCHAR2(4),\n Province VARCHAR2(32),\n Population NUMBER, \n Longitude NUMBER, \n Latitude NUMBER ,\n CONSTRAINT CityKey PRIMARY KEY (Name, Country, Province));\n\nCREATE TABLE Province\n(Name VARCHAR2(32) ,\n Country VARCHAR2(4) ,\n Population NUMBER ,\n Area NUMBER ,\n Capital VARCHAR2(35),\n CapProv VARCHAR2(32),\n CONSTRAINT PrKey PRIMARY KEY (Name, Country));\n\nCREATE TABLE Economy\n(Country VARCHAR2(4) CONSTRAINT EconomyKey PRIMARY KEY,\n GDP NUMBER ,\n Agriculture NUMBER,\n Service NUMBER,\n Industry NUMBER,\n Inflation NUMBER);\n\nCREATE TABLE Population\n(Country VARCHAR2(4) CONSTRAINT PopKey PRIMARY KEY,\n Population_Growth NUMBER,\n Infant_Mortality NUMBER);\n\nCREATE TABLE Politics\n(Country VARCHAR2(4) CONSTRAINT PoliticsKey PRIMARY KEY,\n Independence DATE,\n Government VARCHAR2(120));\n\nCREATE TABLE Language\n(Country VARCHAR2(4),\n Name VARCHAR2(50),\n Percentage NUMBER ,\n CONSTRAINT LanguageKey PRIMARY KEY (Name, Country));\n\nCREATE TABLE Religion\n(Country VARCHAR2(4),\n Name VARCHAR2(50),\n Percentage NUMBER ,\n CONSTRAINT ReligionKey PRIMARY KEY (Name, Country));\n\nCREATE TABLE Ethnic_Group\n(Country VARCHAR2(4),\n Name VARCHAR2(50),\n Percentage NUMBER ,\n CONSTRAINT EthnicKey PRIMARY KEY (Name, Country));\n\nCREATE TABLE Continent\n(Name VARCHAR2(20) CONSTRAINT ContinentKey PRIMARY KEY,\n Area NUMBER(10));\n\nCREATE TABLE Borders\n(Country1 VARCHAR2(4),\n Country2 VARCHAR2(4),\n Length NUMBER );\n\nCREATE TABLE encompasses\n(Country VARCHAR2(4) NOT NULL,\n Continent VARCHAR2(20) NOT NULL,\n Percentage NUMBER,\n CONSTRAINT EncompassesKey PRIMARY KEY (Country,Continent));\n\nCREATE TABLE Organization\n(Abbreviation VARCHAR2(12) PRIMARY KEY,\n Name VARCHAR2(80) NOT NULL,\n City VARCHAR2(35) ,\n Country VARCHAR2(4) , \n Province VARCHAR2(32) ,\n Established DATE,\n CONSTRAINT OrgNameUnique UNIQUE (Name));\n\nCREATE TABLE is_member\n(Country VARCHAR2(4),\n Organization VARCHAR2(12),\n Type VARCHAR2(30) DEFAULT 'member',\n CONSTRAINT MemberKey PRIMARY KEY (Country,Organization) );\n\nCREATE OR REPLACE TYPE GeoCoord AS OBJECT\n(Longitude NUMBER,\n Latitude NUMBER);\n/\n\nCREATE TABLE Mountain\n(Name VARCHAR2(20) CONSTRAINT MountainKey PRIMARY KEY,\n Height NUMBER CONSTRAINT MountainHeight\n CHECK (Height >= 0),\n Coordinates GeoCoord );\n\nCREATE TABLE Desert\n(Name VARCHAR2(25) CONSTRAINT DesertKey PRIMARY KEY,\n Area NUMBER);\n\nCREATE TABLE Island\n(Name VARCHAR2(25) CONSTRAINT IslandKey PRIMARY KEY,\n Islands VARCHAR2(25),\n Area NUMBER CONSTRAINT IslandAr\n check ((Area >= 0) and (Area <= 2175600)) ,\n Coordinates GeoCoord );\n\nCREATE TABLE Lake\n(Name VARCHAR2(25) CONSTRAINT LakeKey PRIMARY KEY,\n Area NUMBER CONSTRAINT LakeAr CHECK (Area >= 0));\n\nCREATE TABLE Sea\n(Name VARCHAR2(25) CONSTRAINT SeaKey PRIMARY KEY,\n Depth NUMBER CONSTRAINT SeaDepth CHECK (Depth >= 0));\n\nCREATE TABLE River\n(Name VARCHAR2(20) CONSTRAINT RiverKey PRIMARY KEY,\n River VARCHAR2(20),\n Lake VARCHAR2(20),\n Sea VARCHAR2(25),\n Length NUMBER );\n\nCREATE TABLE geo_Mountain\n(Mountain VARCHAR2(20) ,\n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GMountainKey PRIMARY KEY (Province,Country,Mountain) );\n\nCREATE TABLE geo_Desert\n(Desert VARCHAR2(25) ,\n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GDesertKey PRIMARY KEY (Province, Country, Desert) );\n\nCREATE TABLE geo_Island\n(Island VARCHAR2(25) , \n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GIslandKey PRIMARY KEY (Province, Country, Island) );\n\nCREATE TABLE geo_River\n(River VARCHAR2(20) , \n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );\n\nCREATE TABLE geo_Sea\n(Sea VARCHAR2(25) ,\n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GSeaKey PRIMARY KEY (Province, Country, Sea) );\n\nCREATE TABLE geo_Lake\n(Lake VARCHAR2(25) ,\n Country VARCHAR2(4) ,\n Province VARCHAR2(32) ,\n CONSTRAINT GLakeKey PRIMARY KEY (Province, Country, Lake) );\n\nCREATE TABLE merges_with\n(Sea1 VARCHAR2(25) ,\n Sea2 VARCHAR2(25) ,\n CONSTRAINT MergesWithKey PRIMARY KEY (Sea1,Sea2) );\n\nCREATE TABLE located\n(City VARCHAR2(35) ,\n Province VARCHAR2(32) ,\n Country VARCHAR2(4) ,\n River VARCHAR2(20),\n Lake VARCHAR2(25),\n Sea VARCHAR2(25));\n" }, { "alpha_fraction": 0.4842105209827423, "alphanum_fraction": 0.5754386186599731, "avg_line_length": 16.8125, "blob_id": "96225802fcc5603addfcefa99591ff2ce3a511a4", "content_id": "e056914ba2fee21c72dc88d301867aad6374f293", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 285, "license_type": "permissive", "max_line_length": 69, "num_lines": 16, "path": "/TP3_Archi/Q1-7/sum.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"lcd.h\"\n\nint sum_eight(int a, int b, int c, int d, int e, int f, int g, int h)\n{\n\tint x= a + b + c + d + e + f + g + h;\n\treturn x;\n}\nint main(void)\n{\n\tvolatile int x=0;\n\tlcd_init();\n\tx=sum_eight(100,200,300,400,500,600,700,800);\n\tlcd_display_number(x);\n\tfor(;;);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7013825178146362, "alphanum_fraction": 0.7059907913208008, "avg_line_length": 29.13888931274414, "blob_id": "8ad84f2e29553c8a8013c1a70576e48d4eb2bede", "content_id": "d5795adf18f09e2c4070104c6bbc4d5d097ae549", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1085, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/TP2_SI/services/src/main/java/test/testCommande.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage test;\n\nimport java.sql.Date;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport metier.modele.Client;\nimport metier.modele.Commande;\nimport metier.modele.Produit;\nimport metier.modele.ProduitCommande;\nimport metier.modele.Restaurant;\nimport metier.service.Service;\n\n/**\n *\n * @author quentinvecchio\n */\npublic class testCommande {\n public static void main(String[] args) {\n Service service = new Service();\n Client c = service.connectClient(\"qvecchio\", \"qvecchio\");\n Restaurant r = service.findRestaurantById(new Long(1));\n List<ProduitCommande> contenues = new ArrayList<>();\n System.out.println(c);\n System.out.println(r);\n contenues.add(new ProduitCommande(r.getProduits().get(0),1));\n Commande c1 = new Commande(c, r, contenues);\n service.createCommande(c1);\n }\n}\n" }, { "alpha_fraction": 0.6278586387634277, "alphanum_fraction": 0.6299376487731934, "avg_line_length": 33.35714340209961, "blob_id": "f3604bc1a659f64fe1db217f88a4f2757dd10cf7", "content_id": "55dfe317d0fbf8ab5dcc1dd1bc39e14dff6d595f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 962, "license_type": "permissive", "max_line_length": 187, "num_lines": 28, "path": "/TP4_cpp/src/Command.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include \"Command.h\"\n\n#include <string>\n#include <tuple>\n\nnamespace TP4\n{\n\tnamespace\n\t{\n\t\tusing cmd_ut = std::underlying_type<command_type>::type;\n\t\tconst std::string CMDS[] = { std::string(\"S\"), std::string(\"R\"), std::string(\"PC\"), std::string(\"OR\"), std::string(\"OI\"), std::string(\"HIT\"), std::string(\"DELETE\"), std::string(\"MOVE\"),\n\t\t\t\t\t\t\t\t\t std::string(\"LIST\"), std::string(\"UNDO\"), std::string(\"REDO\"), std::string(\"LOAD\"), std::string(\"SAVE\"), std::string(\"CLEAR\"), std::string(\"EN_ERROR_MESS\"),\n\t\t\t\t\t\t\t\t\t std::string(\"DIS_ERROR_MESS\"), std::string(\"BENCHMARK\"), std::string(\"EXIT\") };\n\t}\n\n\tstd::string underlying(command_type command)\n\t{\n\t\treturn CMDS[static_cast<cmd_ut>(command)];\n\t}\n\n\tcommand_type overlying(const std::string& name)\n\t{\n\t\tfor (cmd_ut i = 0; i <= static_cast<cmd_ut>(command_type::EXIT); ++i)\n\t\t\tif (name == CMDS[i])\n\t\t\t\treturn static_cast<command_type>(i);\n\t\tthrow std::range_error(\"Given string out of 'cmd' enumeration range.\");\n\t}\n}\n" }, { "alpha_fraction": 0.5203843712806702, "alphanum_fraction": 0.5279557108879089, "avg_line_length": 24.25, "blob_id": "4abf30b256bb517ba79f9bd3c836e7dd05b29367", "content_id": "9010ae1507374da5bbc73a9bbc9fdaa01f27e35d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6877, "license_type": "permissive", "max_line_length": 147, "num_lines": 272, "path": "/TP1_cpp_gcc/source/collection.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*************************************************************************************\n\t\t\t\t\t\tcollection - A collection of dogs\n\t\t\t\t\t\t-----------------------------------\ndate : 10/2015\ncopyright : (C) 2015 by B3311\n*************************************************************************************/\n\n//--------- Réalisation de la classe <collection.h> (fichier collection.cpp) ---------\n\n//---------------------------------------------------------------------------- INCLUDE\n\n//-------------------------------------------------------------------- Include système\n#include <iostream>\n\n//------------------------------------------------------------------ Include personnel\n#include \"collection.h\"\n\nnamespace TP1\n{\n\t//------------------------------------------------------------------------- PUBLIC\n\tvoid collection::afficher() const\n\t{\n\t\tif (m_size > 0)\n\t\t{\n\t\t\tstd::cout << \"({ \";\n\n\t\t\tfor (size_t i = 0; i < m_size; ++i)\n\t\t\t\tstd::cout << m_dogs[i]->age << ((i < m_size - 1) ? \", \" : \" }, \");\n\n\t\t\tstd::cout << m_capacity << \")\";\n\t\t}\n\t\telse\n\t\t\tstd::cout << \"({ }, \" << m_capacity << \")\";\n\t}\n\n\tvoid collection::ajouter(const dog& dog_to_add)\n\t{\n\t\t// Copy given dog\n\t\tdog* new_dog = new dog(dog_to_add);\n\n\t\t// Reallocate memory if we don't have free space anymore\n\t\tif (m_size == m_capacity)\n\t\t{\n\t\t\t// Double capacity at each new allocations\n\t\t\tajuster(m_size > 0 ? 2 * m_size : INITIAL_ALLOCATION_SIZE);\n\t\t}\n\n\t\t// Append new dog value\n\t\tm_dogs[m_size++] = new_dog;\n\t}\n\n\tbool collection::retirer(const dog dogs_to_remove[], size_t size)\n\t{\n\t\tif (dogs_to_remove == nullptr || size == 0 || m_dogs == nullptr)\n\t\t{\n\t\t\tajuster(m_size); // As specified, we always allocate the shorter amount of memory possible (m_size == m_capacity) after 'retirer(...)' is called\n\t\t\treturn false;\n\t\t}\n\n\t\t// Find the number of dog to remove and get the index of the first one\n\t\tunsigned int removes_todo_count = find_all_of(dogs_to_remove, size);\n\n\t\tif (removes_todo_count == 0)\n\t\t{\n\t\t\t// There isn't any dog to remove\n\t\t\tajuster(m_size); // As specified, we always allocate the shorter amount of memory possible (m_size == m_capacity) after 'retirer(...)' is called\n\t\t\treturn false;\n\t\t}\n\n\t\tif (removes_todo_count >= m_size)\n\t\t\tdisposeDogs(); // We remove all dogs\n\t\telse\n\t\t{\n\t\t\tsize_t new_size = m_size - removes_todo_count;\n\t\t\tdog** new_dogs = new dog*[new_size];\n\n\t\t\t// Copy 'm_dogs' dogs in 'new_dogs' except those present in 'dogs_to_remove'\n\t\t\tsize_t removes_count = 0;\n\t\t\tfor (size_t i = 0; i < m_size; ++i)\n\t\t\t{\n\t\t\t\tauto dog = m_dogs[i];\n\n\t\t\t\t// Check if 'm_dogs[i]' is in 'dogs_to_remove'\n\t\t\t\tbool is_to_copy = true;\n\t\t\t\tfor (size_t j = 0; j < size && removes_count < removes_todo_count; ++j)\n\t\t\t\t{\n\t\t\t\t\tif (dogs_to_remove[j] == *(dog))\n\t\t\t\t\t{\n\t\t\t\t\t\t++removes_count;\n\t\t\t\t\t\tis_to_copy = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (is_to_copy)\n\t\t\t\t\tnew_dogs[i - removes_count] = dog;\n\t\t\t}\n\n\t\t\tdelete[] m_dogs;\n\t\t\tm_dogs = new_dogs;\n\t\t\tm_size = new_size;\n\t\t\tm_capacity = new_size;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool collection::retirer(const dog& old_dog)\n\t{\n\t\treturn retirer(&old_dog, 1);\n\t}\n\n\tbool collection::ajuster(size_t new_capacity)\n\t{\n\t\tif (new_capacity < m_size || new_capacity == m_capacity)\n\t\t\treturn false; // We forbid any dog removal during an 'collection::ajuster' call\n\n\t\tif (new_capacity == 0)\n\t\t{\n\t\t\t// We know that 'm_size == 0', 'm_capacity > 0' and 'm_dogs != nullptr' \n\t\t\t// We free all pre-allocated memory:\n\t\t\tdelete[] m_dogs;\n\t\t\tm_dogs = nullptr;\n\t\t\tm_capacity = 0;\n\t\t\treturn true;\n\t\t}\n\n\t\t// Allocate a new array of dog pointers\n\t\tdog** new_dogs = new dog*[new_capacity];\n\n\t\t// If this collection have any dog pointers, we copy them to 'new_dogs' and we delete 'm_dogs'\n\t\tif (m_dogs != nullptr)\n\t\t{\n\t\t\tfor (size_t i = 0; i < m_size; i++)\n\t\t\t\tnew_dogs[i] = m_dogs[i];\n\n\t\t\tdelete[] m_dogs;\n\t\t}\n\n\t\t// Assign the new array to 'm_dogs' and update 'm_capacity'\n\t\tm_dogs = new_dogs;\n\t\tm_capacity = new_capacity;\n\n\t\treturn true;\n\t}\n\n\tbool collection::reunir(const collection& other)\n\t{\n\t\tif (other.m_size == 0 || other.m_dogs == nullptr)\n\t\t\treturn false; // We don't have any dogs to append\n\n\t\tif (m_capacity - m_size >= other.m_size)\n\t\t{\n\t\t\t// We have enought free allocated space to store other.m_dogs in m_dogs\n\t\t\tfor (size_t i = 0; i < other.m_size; ++i)\n\t\t\t\tm_dogs[m_size + i] = new dog(*(other.m_dogs[i]));\n\n\t\t\tm_size += other.m_size;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Allocate a new array of dog pointers\n\t\t\tdog** new_dogs = new dog*[2 * (m_size + other.m_size)];\n\n\t\t\t// Copy other.m_dogs to new_dogs\n\t\t\tfor (size_t i = 0; i < other.m_size; i++)\n\t\t\t\tnew_dogs[i + m_size] = new dog(*(other.m_dogs[i]));\n\n\t\t\tif (m_dogs != nullptr)\n\t\t\t{\n\t\t\t\t// Copy m_dogs pointers to new_dogs\n\t\t\t\tfor (size_t i = 0; i < m_size; ++i)\n\t\t\t\t\tnew_dogs[i] = m_dogs[i];\n\n\t\t\t\tdelete[] m_dogs;\n\t\t\t}\n\n\t\t\t// Assign the new array to 'm_dogs' and update 'm_capacity' and 'm_size'\n\t\t\tm_dogs = new_dogs;\n\t\t\tm_size += other.m_size;\n\t\t\tm_capacity = 2 * m_size;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t//---------------------------------------------------- Constructeurs - destructeur\n\tcollection::collection(size_t capacity)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'collection::collection(size_t)'\" << endl;\n#endif\n\n\t\tif (capacity > 0)\n\t\t\tm_dogs = new dog*[capacity];\n\t\telse\n\t\t\tm_dogs = nullptr;\n\t\tm_capacity = capacity;\n\t}\n\n\tcollection::collection(const dog dogs[], size_t size)\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au constructeur 'collection::collection(const dog[], size_t)'\" << endl;\n#endif\n\n\t\tif (size > 0 && dogs != nullptr)\n\t\t{\n\t\t\tm_capacity = size;\n\t\t\tm_size = size;\n\n\t\t\t// Create a new array of dog pointers\n\t\t\tm_dogs = new dog*[size];\n\n\t\t\t// Copy given dogs\n\t\t\tfor (size_t i = 0; i < size; ++i)\n\t\t\t\tm_dogs[i] = new dog(dogs[i]);\n\t\t}\n\t}\n\n\tcollection::~collection()\n\t{\n#ifdef MAP\n\t\tcout << \"Appel au destructeur de 'collection'\" << endl;\n#endif\n\t\t// On désalloue la mémoire allouée pour le tableau de pointeur de dog et pour les dogs eux-même\n\t\tdisposeDogs();\n\t} //----- Fin de ~collection{file_base}\n\n\t//-------------------------------------------------------------------------- PRIVE\n\n\t//------------------------------------------------------------- Méthodes protégées\n\tunsigned int collection::find_all_of(const dog dogs_to_find[], size_t size) const\n\t{\n\t\tunsigned int matches_count = 0;\n\n\t\tif (size > 0 && dogs_to_find != nullptr && m_size > 0)\n\t\t{\n\t\t\tfor (size_t idx = m_size - 1; idx < m_size; --idx)\n\t\t\t{\n\t\t\t\tfor (size_t idx2 = 0; idx2 < size; ++idx2)\n\t\t\t\t{\n\t\t\t\t\tif (*(m_dogs[idx]) == dogs_to_find[idx2])\n\t\t\t\t\t{\n\t\t\t\t\t\t++matches_count;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn matches_count;\n\t}\n\n\tvoid collection::disposeDogs()\n\t{\n\t\tif (m_dogs != nullptr)\n\t\t{\n\t\t\tfor (size_t i = 0; i < m_size; ++i)\n\t\t\t{\n\t\t\t\tdog* dog_ptr = m_dogs[i];\n\t\t\t\tif (dog_ptr != nullptr)\n\t\t\t\t\tdelete dog_ptr;\n\t\t\t\tm_dogs[i] = nullptr;\n\t\t\t}\n\t\t\tdelete[] m_dogs;\n\t\t\tm_dogs = nullptr;\n\n\t\t\tm_size = 0;\n\t\t\tm_capacity = 0;\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.7354260087013245, "alphanum_fraction": 0.7354260087013245, "avg_line_length": 19.272727966308594, "blob_id": "0466edf79a01c76654ca41c854b7ee1cfeeec2ea", "content_id": "b1855f0638bc4f3989d1e4a59b18aa94bccc3849", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 223, "license_type": "permissive", "max_line_length": 45, "num_lines": 11, "path": "/TP4_Archi/lcd.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#ifndef LCD_H\n#define LCD_H\n\nvoid lcd_init();\nvoid lcd_clear();\nvoid lcd_fill();\nvoid lcd_display_digit(int pos, int digit);\nvoid lcd_display_number(unsigned int number);\nvoid lcd_display_hexa(unsigned int number);\n\n#endif\n" }, { "alpha_fraction": 0.5735465288162231, "alphanum_fraction": 0.5738372206687927, "avg_line_length": 34.83333206176758, "blob_id": "c38138e870c177653eac398f7c7b591d463a89b3", "content_id": "afba4ec4d7bac1dd0f68e98eddcd013d815acd18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3443, "license_type": "permissive", "max_line_length": 107, "num_lines": 96, "path": "/TP2_SI/services/src/main/java/vue/RestaurantView.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage vue;\n\nimport java.sql.Date;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Scanner;\nimport metier.modele.Client;\nimport metier.modele.Commande;\nimport metier.modele.Produit;\nimport metier.modele.ProduitCommande;\nimport metier.modele.Restaurant;\nimport metier.service.Service;\n\n/**\n *\n * @author qvecchio\n */\npublic class RestaurantView {\n private Service service = new Service();\n private Scanner sc = new Scanner(System.in);\n \n public RestaurantView() {\n \n }\n \n public Restaurant chooseRestaurant() {\n Restaurant r = null;\n do {\n System.out.println(\"Liste des restaurants : \");\n List<Restaurant> restaurants = service.findAllRestaurant();\n if(restaurants == null)\n System.out.println(\"\");\n for(Restaurant res : restaurants) {\n System.out.println(res.getId() + \" - \" + res.getDenomination());\n System.out.println(\"\\t\" + res.getDescription());\n }\n System.out.println(\"Choix restaurant (id) : \");\n long id = sc.nextLong();\n if(id < 0)\n break;\n r = service.findRestaurantById(id);\n }while(r == null);\n return r;\n }\n \n public Commande chooseProduct(Client client, Restaurant restaurant) {\n Commande c = new Commande();\n c.setClient(client);\n c.setRestaurant(restaurant);\n List<ProduitCommande> contenues = new ArrayList<>();\n String cmd = null;\n do {\n sc = new Scanner(System.in);\n System.out.println(\"Liste des produits du restaurant \" + restaurant.getDenomination() + \" : \");\n for(Produit prod : restaurant.getProduits()) {\n System.out.println(prod.getId() + \" - \" + prod.getDenomination());\n System.out.println(\"\\t\" + prod.getDescription());\n }\n System.out.println(\"Choix produit (id) (f pour finaliser la commande) : \");\n cmd = sc.nextLine();\n try {\n Produit p = service.findProduitById(Long.parseLong(cmd));\n System.out.println(p.getId() + \" - \" + p.getDenomination());\n System.out.println(\"\\t\" + p.getDescription());\n System.out.println(\"Quantité : \");\n int qt = sc.nextInt();\n contenues.add(new ProduitCommande(p, qt));\n } catch (Exception e) {\n if(cmd.equals(\"f\") == false)\n System.out.println(\"Cet id n'est pas bon\" + cmd);\n } \n }while(!cmd.equals(\"f\") && !cmd.equals(\"q\"));\n if(cmd.equals(\"q\"))\n return null;\n System.out.println(\"Récapitulatif : \");\n for(ProduitCommande p : contenues)\n {\n System.out.println(\"\\t\" + p.getProduit().getDenomination() + \"\\t\" + p.getQuantite());\n } \n c.setContenues(contenues);\n c.setClient(client);\n if(service.createCommande(c) == false)\n System.out.println(\"Votre commande ne peut être prise en charge pour le moment.\");\n else\n System.out.println(\"Votre commande est bien prise en charge.\");\n return c; \n }\n \n}\n" }, { "alpha_fraction": 0.5910184383392334, "alphanum_fraction": 0.6078588366508484, "avg_line_length": 15.181818008422852, "blob_id": "f386e27fd975173725b714f4f07b755abb830fd2", "content_id": "8b1c1a71f99de23505a0bce5b4f648bce7273996", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1247, "license_type": "permissive", "max_line_length": 68, "num_lines": 77, "path": "/TP2_Concurrency/question5.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <pthread.h>\n\n\nstatic pthread_mutex_t mutexRead;\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t i = 0;\n uint64_t nPrime = n;\n printf(\"%ju: \", n);\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime%i == 0)\n\t\t{\n\t\t\tnPrime = nPrime/i;\n\t\t\tprintf(\"%ju \", i);\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\r\\n\");\n}\n\nvoid decompo_task(FILE* file)\n{\n\tchar line[60];\n\t\n\twhile(1)\n\t{\n\t\tpthread_mutex_lock(&mutexRead);\n\t\tif(fgets(line, 60, file) == NULL)\n\t\t{\n\t\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\tbreak;\n\t\t}\n\t\tpthread_mutex_unlock(&mutexRead);\n\t\t\n\t\tuint64_t value=atoll(line);\n\t\tprint_prime_factors(value);\n\t\n\t}\n}\n\nvoid* print_prime_factors_thread(void* n)\n{\n\tFILE* x = ((FILE*)n);\n\tdecompo_task(x);\n\treturn NULL;\n}\n\nint main(void)\n{\n\tFILE* primeList;\n\tprimeList = fopen(\"primes2.txt\", \"r\");\n\t\n\tpthread_t ta;\n\tpthread_t tb;\n\t\n\tif(primeList == NULL)\n\t{\n\t\tperror(\"erreur ouverture fichier\");\n\t\texit(-1);\n\t}\n\tpthread_mutex_init(&mutexRead, NULL);\n\tpthread_create (&ta, NULL, &print_prime_factors_thread, primeList);\n\tpthread_create (&tb, NULL, &print_prime_factors_thread, primeList);\n\tpthread_join (ta, NULL);\n\tpthread_join (tb, NULL);\n\t\n return 0;\n}\n\n" }, { "alpha_fraction": 0.43560606241226196, "alphanum_fraction": 0.4469696879386902, "avg_line_length": 14.529411315917969, "blob_id": "3a7c0425312518816a7a262dd14f0ec626643a87", "content_id": "688b7929985910cba4fbd63eba1aa37e5985a8d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 264, "license_type": "permissive", "max_line_length": 33, "num_lines": 17, "path": "/TD_Archi_cache/cache_ex9_v5.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"N.h\"\n\ndouble A[N][N], B[N][N], C[N][N];\n\nint main()\n{\n\tfor(size_t k = 0; k<N; k++) {\n\t\tfor(size_t i = 0; i < N; i++) {\n\t\t\tdouble r = A[i][k];\n\t\t\tfor(size_t j = 0; j < N; j++)\n\t\t\t\tC[i][j] += B[k][j]*r;\n\t\t}\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5723905563354492, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 19.086956024169922, "blob_id": "50be12b6c87d793bd6c5a3291ad8a4ee16680eec", "content_id": "ec8c73c597845002f50b5e38f2769257d3f0778c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4158, "license_type": "permissive", "max_line_length": 91, "num_lines": 207, "path": "/TD4_ALG/hash_table.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <limits.h>\n\n#include \"hash_table.h\"\n\nstatic unsigned int hash(char* chaine, unsigned int m);\nstatic unsigned int shift_rotate(unsigned int val, unsigned int n);\nstatic unsigned int find_index_of(hash_table* table, char* key, unsigned int h);\n\nvoid init_hash_table(hash_table* table, unsigned int repetition, unsigned int m)\n{\n\tif (table != NULL)\n\t{\n\t\ttable->m = m;\n\t\ttable->array_size = repetition*m;\n\t\ttable->array_step = repetition;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\n\t\ttable->array = (cell*)malloc(table->array_size*sizeof(cell));\n\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tc->state = empty;\n\t\t\tc->key = NULL;\n\t\t\tc->value = NULL;\n\t\t}\n\t}\n}\n\nvoid destr_hash_table(hash_table* table)\n{\n\tif (table != NULL)\n\t{\n\t\t// Free all allocated strings\n\t\tunsigned int i;\n\t\tfor (i = 0; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[i];\n\t\t\tif (c != NULL)\n\t\t\t{\n\t\t\t\tif(c->key != NULL)\n\t\t\t\t\tfree(c->key);\n\t\t\t\tif (c->value != NULL)\n\t\t\t\t\tfree(c->value);\n\t\t\t}\n\t\t}\n\n\t\t// Free table of cells\n\t\tfree(table->array);\n\t\ttable->array = NULL;\n\n\t\ttable->array_size = 0;\n\t\ttable->used_count = 0;\n\t\ttable->deleted_count = 0;\n\t}\n}\n\nvoid show_stats(hash_table* table)\n{\n\tif (table != NULL)\n\t{\n\t\tprintf(\"size : %d\\r\\n\", table->array_size);\n\t\tprintf(\"empty : %d\\r\\n\", table->array_size - table->used_count - table->deleted_count);\n\t\tprintf(\"deleted : %d\\r\\n\", table->deleted_count);\n\t\tprintf(\"used : %d\\r\\n\", table->used_count);\n\t}\n}\n\nvoid insert_to_table(hash_table* table, char* key, char* value)\n{\n\tif (table != NULL && key != NULL && value != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\t// update cell value\n\t\t\tcell* c = &table->array[idx];\n\t\t\tfree(c->value);\n\t\t\tc->value = value;\n\n\t\t\tfree(key);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tunsigned int i;\n\t\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t\t{\n\t\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\t\tif (c->state == deleted)\n\t\t\t\t{\n\t\t\t\t\tif (strcmp(c->key, key) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tc->state = used;\n\t\t\t\t\t\ttable->used_count++;\n\t\t\t\t\t\tc->value = value;\n\n\t\t\t\t\t\tfree(key);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (c->state == empty)\n\t\t\t\t{\n\t\t\t\t\tc->state = used;\n\t\t\t\t\ttable->used_count++;\n\t\t\t\t\tfree(c->key);\n\t\t\t\t\tc->key = key;\n\t\t\t\t\tfree(c->value);\n\t\t\t\t\tc->value = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(key);\n\tfree(value);\n}\n\nvoid remove_from_table(hash_table* table, char* key)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\tcell* c = &table->array[idx];\n\t\t\tif (c->state == used) // TODO: useless if ?\n\t\t\t{\n\t\t\t\ttable->used_count--;\n\t\t\t\tc->state = deleted;\n\t\t\t\ttable->deleted_count++;\n\n\t\t\t\tfree(c->value);\n\t\t\t\tc->value = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(key);\n}\n\nvoid find_in_table(hash_table* table, char* key)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int h = hash(key, table->m);\n\t\tunsigned int idx = find_index_of(table, key, h);\n\t\tfree(key);\n\n\t\tif (idx < table->array_size)\n\t\t{\n\t\t\tprintf(\"%s\\r\\n\", table->array[idx].value);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprintf(\"Not found\\r\\n\");\n}\n\nstatic unsigned int find_index_of(hash_table* table, char* key, unsigned int h)\n{\n\tif (table != NULL && key != NULL)\n\t{\n\t\tunsigned int i;\n\t\tfor (i = table->array_step * h; i < table->array_size; ++i)\n\t\t{\n\t\t\tcell* c = &table->array[table->array_step * h];\n\n\t\t\tif (c->state == used)\n\t\t\t{\n\t\t\t\tif (strcmp(c->key, key) == 0)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn UINT_MAX;\n}\n\n/* encodage d'une chaine de caracteres sous la forme d'un entier non signe */\nstatic unsigned int shift_rotate(unsigned int val, unsigned int n)\n{\n\tn = n % (sizeof(unsigned int) * 8);\n\treturn (val << n) | (val >> (sizeof(unsigned int) * 8 - n));\n}\n\n/* fonction de hachage d'une chaine de caracteres */\nstatic unsigned int hash(char* chaine, unsigned int m)\n{\n\tunsigned int i;\n\tunsigned int h = 0;\n\tfor (i = 0; i < strlen(chaine); i++)\n\t{\n\t\th = h + shift_rotate(chaine[i], i * 7);\n\t}\n\treturn h % m;\n}\n" }, { "alpha_fraction": 0.6132493019104004, "alphanum_fraction": 0.6234673261642456, "avg_line_length": 34.37349319458008, "blob_id": "3d37e031b93fb87f0e663bbfa50ae669fcef7b2a", "content_id": "25cd52edf8546eb0e92fc6d5e692388a0f558f35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5890, "license_type": "permissive", "max_line_length": 124, "num_lines": 166, "path": "/TP1_Concurrency/source/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\t\tMain - Tache mere de l'application\n\t\t\t\t----------------------------------\n\tdebut \t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//------------------------------------------------------- Include systeme\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/sem.h>\n#include <sys/ipc.h>\n#include <sys/wait.h> \n#include <sys/types.h>\n\n//------------------------------------------------------ Include personnel\n#include \"process_utils.h\"\n#include \"gestionSortie.h\"\n#include \"gestionEntree.h\"\n#include \"clavier.h\"\n#include \"Outils.h\"\n#include \"Heure.h\"\n\n/////////////////////////////////////////////////////////////////// PRIVE\nnamespace\n{\n\t//-------------------------------------------------------------- Types\n\t//! Structure regroupant les pid des processus fils et les outils de \n\t//! communication entre processus.\n\tstruct\n\t{\n\t\tpid_t heure_pid = -1;\n\t\tpid_t clavier_pid = -1;\n\t\tpid_t porte_gb_pid = -1;\n\t\tpid_t porte_bp_autres_pid = -1;\n\t\tpid_t porte_bp_profs_pid = -1;\n\t\tpid_t porte_sortie_pid = -1;\n\n\t\tipc_id_t parking_state_id = 0;\n\t\tipc_id_t waiters_id = 0;\n\t\tipc_id_t parking_places_id = 0;\n\t\tipc_id_t entrance_mqid = -1;\n\t\tipc_id_t exit_mqid = -1;\n\t\tipc_id_t semaphores_id = -1;\n\t} ressources;\n\n\t//-------------------------------------------------- Fonctions privees\n\t//! Termine la tache mère et ses taches filles\n\tvoid quit_app()\n\t{\n\t\t// Fonction lambda utilisée pour terminer une tache\n\t\tauto kill_task = [](pid_t task, const std::string& message, signal_t sig = SIGUSR2)\n\t\t{\n\t\t\tif (task >= 0)\n\t\t\t{\n\t\t\t\tkill(task, sig);\n\t\t\t\tEffacer(MESSAGE);\n\t\t\t\tAfficher(MESSAGE, message.data());\n\t\t\t\twaitpid(task, nullptr, 0);\n\t\t\t}\n\t\t};\n\n\t\t// Delete application tasks\n\t\tkill_task(ressources.porte_bp_profs_pid, \"FIN porte bp profs\");\n\t\tkill_task(ressources.porte_bp_autres_pid, \"FIN porte bp autres\");\n\t\tkill_task(ressources.porte_gb_pid, \"FIN porte gb\");\n\t\tkill_task(ressources.porte_sortie_pid, \"FIN porte sortie\");\n\t\tkill_task(ressources.clavier_pid, \"FIN clavier\");\n\t\tkill_task(ressources.heure_pid, \"FIN heure\");\n\n\t\t// Suppression des message queues\n\t\tdelete_message_queue(ressources.entrance_mqid);\n\t\tdelete_message_queue(ressources.exit_mqid);\n\n\t\t// Suppression de la memoire partagée\n\t\tdelete_shared_memory(ressources.parking_state_id);\n\t\tdelete_shared_memory(ressources.waiters_id);\n\t\tdelete_shared_memory(ressources.parking_places_id);\n\n\t\t// Suppression des semaphores\n\t\tsemctl(ressources.semaphores_id, 0, IPC_RMID, 0);\n\n\t\t// On retire le handler deu signal SIGCHLD\n\t\tunsubscribe_handler<SIGCHLD>();\n\n\t\tTerminerApplication();\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\t//! Crée les taches filles et les ressources pour l'ipc\n\tvoid init()\n\t{\n\t\t// Fonction lambda utilisée pour quitter en cas d'erreur\n\t\tauto quit_if_failed = [](bool condition) {\n\t\t\tif (!condition)\n\t\t\t\tquit_app();\n\t\t};\n\n\t\tInitialiserApplication(XTERM);\n\n\t\t// On ajoute un handler pour le signal SIGCHLD indiquant qu'une tache fille s'est terminée\n\t\tquit_if_failed(handle<SIGCHLD>([](signal_t sig) {\n\t\t\tquit_app(); // On quitte proprement\n\t\t}));\n\n\t\t// Création de la 'message queue' utilisée pour communiquer entre le clavier et les barrières\n\t\tquit_if_failed(create_message_queue(ressources.entrance_mqid, 1));\n\n\t\t// Création de la 'message queue' utilisée pour communiquer entre le clavier et la sortie\n\t\tquit_if_failed(create_message_queue(ressources.exit_mqid, 2));\n\n\t\t// Création de la mémoire partagée (utilisée par les barrieres)\n\t\tressources.parking_state_id = create_detached_shared_mem<parking>(4);\n\t\tquit_if_failed(ressources.parking_state_id != -1);\n\t\tressources.waiters_id = create_detached_shared_mem<waiting_cars>(5);\n\t\tquit_if_failed(ressources.waiters_id != -1);\n\t\tressources.parking_places_id = create_detached_shared_mem<places>(6);\n\t\tquit_if_failed(ressources.parking_places_id != -1);\n\n\t\t// Creation des semaphores pour l'acces a la memoire partagée et l'attente au niveau des barrières en cas de parking plein\n\t\tressources.semaphores_id = semget(ftok(\".\", 3), 4U, IPC_CREAT | 0600);\n\t\tquit_if_failed(ressources.semaphores_id != -1);\n\t\tquit_if_failed(semctl(ressources.semaphores_id, 0, SETVAL, 1) != -1);\n\t\tquit_if_failed(semctl(ressources.semaphores_id, PROF_BLAISE_PASCAL, SETVAL, 0) != -1);\n\t\tquit_if_failed(semctl(ressources.semaphores_id, AUTRE_BLAISE_PASCAL, SETVAL, 0) != -1);\n\t\tquit_if_failed(semctl(ressources.semaphores_id, ENTREE_GASTON_BERGER, SETVAL, 0) != -1);\n\n\t\t// Creation de la tache 'heure'\n\t\tressources.heure_pid = ActiverHeure();\n\t\tquit_if_failed(ressources.heure_pid != -1);\n\n\t\t// Creation de la tache 'clavier'\n\t\tressources.clavier_pid = activer_clavier();\n\t\tquit_if_failed(ressources.clavier_pid != -1);\n\n\t\t// Creation des taches 'gestionEntree' pour chaque barrieres a l'entree\n\t\tressources.porte_gb_pid = ActiverPorte(ENTREE_GASTON_BERGER);\n\t\tquit_if_failed(ressources.porte_gb_pid != -1);\n\t\tressources.porte_bp_profs_pid = ActiverPorte(PROF_BLAISE_PASCAL);\n\t\tquit_if_failed(ressources.porte_bp_profs_pid != -1);\n\t\tressources.porte_bp_autres_pid = ActiverPorte(AUTRE_BLAISE_PASCAL);\n\t\tquit_if_failed(ressources.porte_bp_autres_pid != -1);\n\n\t\t// Creation de la tache 'gestionSortie'\n\t\tressources.porte_sortie_pid = ActiverPorteSortie();\n\t\tquit_if_failed(ressources.porte_sortie_pid != -1);\n\t}\n}\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//----------------------------------------------------- Fonctions publique\n//! Tache mère\nint main(int argc, char* argv[])\n{\n\t// Creation des taches filles et des ressources pour l'ipc\n\tinit();\n\n\t// Attente de la fin de la tache clavier\n\twaitpid(ressources.clavier_pid, nullptr, 0);\n\n\t// Destruction de la tache mere\n\tquit_app();\n}\n" }, { "alpha_fraction": 0.5524079203605652, "alphanum_fraction": 0.55524080991745, "avg_line_length": 29.257143020629883, "blob_id": "f3ba82864d7a68d9a06662cfca0ce22508061409", "content_id": "f2dad9d20c0321e18ade455aa8809b2607524013", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1061, "license_type": "permissive", "max_line_length": 203, "num_lines": 35, "path": "/TP4_cpp/src/Command.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tCommand\n\t\t\t\t\t\t\t\t\t-------\n*********************************************************************************/\n\n#ifndef COMMAND_H\n#define COMMAND_H\n\n#include <tuple>\n#include <string>\n#include <unordered_set>\n\n#include \"Utils.h\"\n\n//! \\namespace TP4\n//! espace de nommage regroupant le code crée pour le TP4 de C++\nnamespace TP4\n{\n\t//----------------------------------------- Enumération des types de commandes\n\tenum class command_type { ADD_SEGMENT, ADD_RECTANGLE, ADD_POLYGON, UNION, INTER, HIT, DELETE, MOVE, LIST, UNDO, REDO, LOAD, SAVE, CLEAR, ENABLE_ERROR_MESSAGES, DISABLE_ERROR_MESSAGES, BENCHMARK, EXIT };\n\tstd::string underlying(command_type command);\n\tcommand_type overlying(const std::string& name);\n\n\tusing name_t = std::string;\n\tusing coord_t = int;\n\tusing Point = std::pair<coord_t, coord_t>;\n\n\ttemplate<typename String>\n\tinline coord_t move_str_to_coord_t(String&& str)\n\t{\n\t\treturn std::stoi(static_cast<std::string&&>((str)));\n\t}\n}\n\n#endif // !COMMAND_H\n" }, { "alpha_fraction": 0.5540160536766052, "alphanum_fraction": 0.5640562176704407, "avg_line_length": 33.33793258666992, "blob_id": "8034b3c82627a8246ab68bc4c8cedb4a4ae865cb", "content_id": "90c7da53bf35e049c2fb38e580d907fbd2f75d69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4990, "license_type": "permissive", "max_line_length": 147, "num_lines": 145, "path": "/TP3_cpp/sources/main.cpp", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "ISO-8859-1", "text": "/*********************************************************************************\n\t\t\t\t\t\t\t\t\tmain.cpp\n\t\t\t\t\t\t\t\t\t--------\ndate : 12/2015\ncopyright : (C) 2015 by B3311\n*********************************************************************************/\n\n//----------------------------------------------------------------------- INCLUDES\n//-------------------------------------------------------------- Includes systèmes\n#include <array>\n#include <string>\n#include <fstream>\n#include <utility>\n#include <iterator>\n#include <iostream>\n#include <algorithm>\n\n//------------------------------------------------------------ Includes personnels\n#include \"Graph.h\"\n#include \"Help_txt.h\"\n#include \"Log_parser.h\"\n#include \"Typed_main_binding.h\"\n\n//! \\namespace TP3\n//! espace de nommage regroupant le code crée pour le TP3 de C++\nnamespace TP3\n{\n\t//------------------------------------------------------------ COMMAND OPTIONS\n\n\t//! @remarks valide le concept de 'option_with_value'\n\tstruct input_log_file_option\n\t{ std::string value; };\n\n\t//! @remarks valide le concept de 'option_with_tags' et 'option_with_value'\n\tstruct output_graph_file_option\n\t{\n\t\tstd::string value;\n\t\tstatic tags_t<3> get_option_tags() noexcept { return tags_t<3>{{ \"-g\", \"-G\", \"--graph\" }}; /* C++11/14: \"return { \"-g\", \"-G\", \"--graph\" };\" */ } \n\t};\n\n\t//! @remarks valide le concept de 'option_with_tags' et 'option_with_value'\n\tstruct hour_option\n\t{\n\t\tunsigned short value;\n\t\tstatic tags_t<3> get_option_tags() noexcept { return tags_t<3>{{ \"-t\", \"-T\", \"--hour\" }}; }\n\t};\n\n\t//! @remarks valide le concept de 'option_with_tags' et 'option_with_value'\n\tstruct list_option\n\t{\n\t\tsize_t value;\n\t\tstatic const size_t default_value = 10;\n\t\tstatic tags_t<3> get_option_tags() noexcept { return tags_t<3>{ { \"-l\", \"-L\", \"--listCount\" }}; }\n\t};\n\n\t//! @remarks valide le concept de 'option_with_tags'\n\tstruct exclusion_option\n\t{ static tags_t<3> get_option_tags() noexcept { return tags_t<3>{ { \"-e\", \"-E\", \"--excludeMedias\"}}; } };\n\n\t//! @remarks valide le concept de 'option_with_tags'\n\tstruct help_option\n\t{ static tags_t<1> get_option_tags() noexcept { return tags_t<1>{ { \"-h\" }}; } };\n\n\tusing std::experimental::optional;\n\n\t//----------------------------------------------------------- STATIC FUNCTIONS\n\n\t//! \"Main typé\" appellé par un objet de type 'Typed_main_binding<Args...>'\n\tstatic void typed_main(optional<input_log_file_option> input_log, // input_log is actually mandatory (tagless option)\n\t\t\t\t\toptional<output_graph_file_option> output_graph,\n\t\t\t\t\toptional<hour_option> hour_opt,\n\t\t\t\t\toptional<list_option> list_count_opt,\n\t\t\t\t\toptional<exclusion_option> excl_opt,\n\t\t\t\t\toptional<help_option> help)\n\t{\n\t\tif (!help)\n\t\t{\n\t\t\tLog_parser parser;\n\n\t\t\tif (hour_opt)\n\t\t\t{\n\t\t\t\tif (hour_opt->value < 0 || hour_opt->value >= 24)\n\t\t\t\t\tthrow std::out_of_range(\"Hour must be in [[0,23]]\");\n\t\t\t\tparser.enable_hour_filter(hour_opt->value);\n\t\t\t}\n\t\t\tif (excl_opt)\n\t\t\t\tparser.enable_exclusion();\n\n\t\t\tif (output_graph)\n\t\t\t{\n\t\t\t\t// Parse and serialize graph\n\t\t\t\tserialize_graph(output_graph->value, parser.parse_graph(input_log->value));\n\t\t\t\tstd::cout << \"Dot-file \" << output_graph->value << \" generated.\" << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Parse log to obtain the URLs with their respective occurrence number (unordered_multimap)\n\t\t\t\tauto urls = parser.parse_urllist(input_log->value);\n\n\t\t\t\t// Determine URLs toplist size\n\t\t\t\tauto toplist_count = list_count_opt ? list_count_opt->value : list_option::default_value;\n\t\t\t\tif (toplist_count < 1)\n\t\t\t\t\tthrow std::out_of_range(\"URLs toplist size must be greater than 0\");\n\n\t\t\t\t// Get top URL listS from unordered multimap '*urls' (partial sort by URL occurrence number)\n\t\t\t\tusing url_score_t = std::pair<std::string, unsigned int>;\n\t\t\t\tstd::vector<url_score_t> topten(std::min(toplist_count, urls->size()));\n\t\t\t\tstd::partial_sort_copy(std::begin(*urls), std::end(*urls), std::begin(topten), std::end(topten), [](const url_score_t& a, const url_score_t& b)\n\t\t\t\t{ return b.second < a.second; });\n\n\t\t\t\t// Display the URLs top 10\n\t\t\t\tfor (const auto& score : topten)\n\t\t\t\t\tstd::cout << '\"' << score.first << \"\\\" :\\t\" << score.second << \" occurrences\" << std::endl;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tstd::cout << Help_txt();\n\t}\n}\n\n\n//--------------------------------------------------------------------------- MAIN\n\n//! Fonction main utilisant simplement un binding vers le main typé\nint main(int argc, char* argv[])\n{\n\t// On traite le cas où seul '-h' est spécifié à part car le binding considère le nom du fichier log comme obligatoire\n\tif (argc == 2)\n\t\tif (argv[1] == std::string(\"-h\")/* C++14: \"-h\"s*/)\n\t\t{\n\t\t\tstd::cout << TP3::Help_txt();\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\n\tauto main_binding = TP3::make_typed_main_binding(&TP3::typed_main);\n\n\ttry\n\t{\n\t\tmain_binding.exec(argc, argv);\n\t}\n\tcatch (std::invalid_argument e) { std::cout << \"ERROR: \" << e.what() << std::endl; }\n\tcatch (std::out_of_range e) { std::cout << \"ERROR: \" << e.what() << std::endl; }\n\n\treturn EXIT_SUCCESS;\n}\n\n" }, { "alpha_fraction": 0.4576757550239563, "alphanum_fraction": 0.5781922340393066, "avg_line_length": 14.466666221618652, "blob_id": "1bc463cc679b60c8df0cd6ac491493ad07214ed4", "content_id": "458cdb036c9d2f7824697278d5e19a91f501dd23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 697, "license_type": "permissive", "max_line_length": 57, "num_lines": 45, "path": "/TP2_Archi/tp2.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "\n#include <msp430fg4618.h>\n\n//#define P5OUT ( *((volatile unsigned char*) 0x31) )\n//#define P5DIR ( *((volatile unsigned char*) 0x32) )\n\n#define LED1 0x04\n#define LED2 0x02\n#define LED3 0x02\n\n#define SW1 0x01 \n#define SW2 0x02\n\nvolatile unsigned int i;\n\nint main(void)\n{\n\t// set P5.1 to output direction\n\tP5DIR = LED3;\n\t\n\tP2DIR = P2DIR | (LED1 | LED2);\n\tP1DIR = P1DIR & !(SW1 | SW2);\n\t\n\t// turn LEDs on\n\tP5OUT = LED3;\n\tP2OUT = LED1 | LED2;\n\t\n\twhile((P1IN & SW1) != 0x00 && (P1IN & SW2) != 0x00);\n\t\n\tfor(;;)\n\t{\n\t\tfor(i=0;i<20000;i++);\n\t\t\n\t\t// turn LEDs off\n\t\tP5OUT = 0;\n\t\tP2OUT = 0;\n\t\t\n\t\tfor(i=0;i<20000;i++);\n\t\t\n\t\t// turn LEDs on\n\t\tP5OUT = LED3;\n\t\tP2OUT = LED1 | LED2;\n\t}\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6102027297019958, "alphanum_fraction": 0.6690647602081299, "avg_line_length": 19.092105865478516, "blob_id": "3b7b810204c70f98fbf3f8efeff1b9776d1d83bd", "content_id": "e379d6942ea3560431656a9c4770a6ac2679fc9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1529, "license_type": "permissive", "max_line_length": 105, "num_lines": 76, "path": "/TP2_Concurrency/Makefile", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "default: help\n\nhelp:\n\t@echo Useful targets:\n\t@echo \" small.txt medium.txt large.txt many.txt: generate some input files \"\n\t@echo \" question1 question2 question3: compile your programs\"\n\t@echo \" run1 run2: run your programs through the 'time' utility\"\n\t@echo \" clean: delete all generated files\"\n\n#########################\n# workload generation\n\ntiny.txt:\n\t./generator.cs 20 20 0 > $@\n\nsmall.txt:\n\t./generator.cs 20 32 50 > $@\n\nmedium.txt:\n\t./generator.cs 20 50 50 > $@\n\nlarge.txt:\n\t./generator.cs 20 64 50 > $@\n\nmany.txt:\n\t./generator.cs 1000 50 75 > $@\n\n#########################\n## program compilation\n\nquestion1: question1.c\n\tgcc -Wall -pthread -g -o question1 question1.c \n\nquestion2: question2.c\n\tgcc -Wall -pthread -o question2 question2.c \n\nquestion3: question3.c\n\tgcc -Wall -pthread -g -o question3 question3.c \t\n\t\nquestion5: question5.c\n\tgcc -Wall -pthread -g -o question5 question5.c \t\n\t\nquestion7: question7.c\n\tgcc -Wall -pthread -g -o question7 question7.c \t\n\t\nquestion10: question10.c\n\tgcc -Wall -pthread -g -o question10 question10.c \t\n\n# add your own rules when you create new programs\n\n#########################\n## program execution\n\nrun1: question1\n\ttime ./question1\n\nrun2: question2\n\ttime ./question2\n\t\nrun3: question3\n\ttime ./question3\n\t\nrun5: question5\n\ttime ./question5\n\t\nrun7: question7\n\ttime ./question7\n\t\nrun10: question10\n\ttime ./question10\n\n#########################\n## utilities\n\nclean:\n\trm -f question1 question2 question3 question5 question7 tiny.txt small.txt medium.txt large.txt many.txt \n\n" }, { "alpha_fraction": 0.4072052538394928, "alphanum_fraction": 0.4213973879814148, "avg_line_length": 38.826087951660156, "blob_id": "5d140083368b76ca5c67bae1eb670f5b74173723", "content_id": "a28f93a1c5c993539bb98ebe34ace6cd63e08b36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 917, "license_type": "permissive", "max_line_length": 74, "num_lines": 23, "path": "/TP1_Concurrency/include/gestionSortie.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tGestion sortie - tache gerant les barrieres de sortie\n\t\t\t-----------------------------------------------------\n\tdebut \t\t\t : 18/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n//-- Interface de la tache <GESTION_SORTIE> (fichier gestionSortie.h) ----\n#ifndef GESTION_SORTIE_H\n#define GESTION_SORTIE_H\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//--------------------------------------------------- Interfaces utilisées\n#include \"process_utils.h\"\n#include \"gestionEntree.h\"\n\n//---------------------------------------------------- Fonctions publiques\n\n//! Demare la tache gestionSortie pour permettre aux voitures de sortir\n//! Retourne le PID du processus fils ou -1 en cas d'echec.\npid_t ActiverPorteSortie();\n\n#endif // GESTION_SORTIE_H\n" }, { "alpha_fraction": 0.5978593230247498, "alphanum_fraction": 0.5978593230247498, "avg_line_length": 23.259260177612305, "blob_id": "97ef9759b2dcbf594d10740cbe6cfd7a5fd7ce31", "content_id": "93d704a96ca1709d441e1e12a5a095e003071f10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 656, "license_type": "permissive", "max_line_length": 84, "num_lines": 27, "path": "/TP1_TP2_Reseau_rendu/VersionSocket/Shared/src/shared/Pair.java", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "package shared;\n\n/**\n * Classe générique regroupant deux objets de type 'L' et 'R' pour former une paire.\n */\npublic class Pair<L,R> {\n\n public Pair(L left, R right) {\n this.first = left;\n this.second = right;\n }\n\n @Override\n public int hashCode() { return first.hashCode() ^ second.hashCode(); }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Pair))\n return false;\n Pair other = (Pair)obj;\n // TODO: if first or sencond == null...\n return first.equals(other.first) && second.equals(other.second);\n }\n\n public final L first;\n public final R second;\n}" }, { "alpha_fraction": 0.6624798774719238, "alphanum_fraction": 0.6700160503387451, "avg_line_length": 39.78688430786133, "blob_id": "d1ec0cb84017c0a1b0123532587b77057c17b21b", "content_id": "e1efd7f0ab28b044332b578f1cc90574ecad4764", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9995, "license_type": "permissive", "max_line_length": 143, "num_lines": 244, "path": "/TP1_Concurrency/include/process_utils.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*************************************************************************\n\t\t\tProcess utils - aide � la manipulation de processus\n\t\t\t---------------------------------------------------\n\tdebut \t\t\t : 20/03/2016\n\tbinome : B3330\n*************************************************************************/\n\n#ifndef PROCESS_UTILS_H\n#define PROCESS_UTILS_H\n\n///////////////////////////////////////////////////////////////// INCLUDE\n//-------------------------------------------------- Interfaces utilis�es\n#include <array>\n#include <signal.h>\n#include <sys/ipc.h>\n#include <sys/shm.h>\n#include <sys/msg.h>\n#include <algorithm>\n#include <functional>\n#include <sys/types.h>\n\n//----------------------------------------------------------------- Types\nusing signal_t = int;\nusing handler_t = void(*)(signal_t);\nusing sa_falg_t = int;\nusing ipc_id_t = int;\n\ntemplate<typename T>\nstruct shared_mem\n{\n\tipc_id_t id;\n\tT* data;\n};\n\n////////////////////////////////////////////////////////////////// PUBLIC\n//---------------------------------------------------- Fonctions publiques\n\n//! Permet de creer un processus fils executant la fonction 'code_fils'.\n//! Le parametre optionnel 'code_pere' permet de specifier du code specifique\n//! au processus pere (avec pour parametre le pid du processus fils).\n//! La fonction retourne le pid du processus fils.\npid_t fork(const std::function<void(void)>& code_fils, const std::function<void(pid_t)>& code_pere = [](pid_t) {});\n\n//! Permet de gerer la reception de signaux. Les signaux qui seront geres\n//! sont specifies sous la forme d'arguments template (variadic template).\n//! La reception d'un des signaux specifies declanchera l'appel de la \n//! donnee en parametre 'handler'.\n//! Le parametre optionnel 'flags' permet de specifier les flags qui \n//! seront donnes aux appels a 'sigaction'.\n//! La fonction retourne true si tout les handlers pu etre inscrit à un signal.\n//!\tExemple pour gerer les signaux SIGUSR1 et SIGINT :\n//!\t\tbool success = handle<SIGUSR1, SIGINT>([](signal_t sig)\n//!\t\t{ \n//!\t\t\t/* code a executer lors de la reception d'un signal */ \n//!\t\t});\ntemplate<signal_t... signals>\nbool handle(handler_t handler, sa_falg_t falgs = SA_RESTART)\n{\n\tif (handler != nullptr)\n\t{\n\t\tstruct sigaction action;\n\t\taction.sa_handler = handler;\n\t\tsigemptyset(&action.sa_mask);\n\t\taction.sa_flags = falgs;\n\n\t\t// On execute sigaction pour recouvrir chaque signals en recuperant la valeur retournee\n\t\tstd::array<int, sizeof...(signals)> return_codes{{ sigaction(signals, &action, nullptr)... }};\n\n\t\t// On verifie si des appels a sigaction on retournes '-1' (erreur)\n\t\tif (std::find(std::begin(return_codes), std::end(return_codes), -1) != std::end(return_codes)) // C++ 14: cbegin, cend\n\t\t\t//TODO: lancer une exception avec plus de details qu'un booleen et annuler tout les handlers des autre signaux\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n//! Permet de remettre le comportement par defaut à la reception des signaux 'signals...'.\n//! Les signaux concernés sont specifies sous la forme d'arguments template (variadic template).\n//! La fonction retourne true si tout les signaux ont été desinscrits.\ntemplate<signal_t... signals>\nbool unsubscribe_handler()\n{\n\t// Sigaction permettant de remettre le comportement par defaut\n\tstruct sigaction unsub_action;\n\tunsub_action.sa_handler = SIG_DFL;\n\tsigemptyset(&unsub_action.sa_mask);\n\tunsub_action.sa_flags = 0;\n\n\t// On execute sigaction pour chaque signal donné en paramètre template\n\tstd::array<int, sizeof...(signals)> return_codes{{ sigaction(signals, &unsub_action, nullptr)... }};\n\n\t// On verifie si des appels à sigaction on retournés '-1' (erreur)\n\tif (std::find(std::begin(return_codes), std::end(return_codes), -1) != std::end(return_codes)) // C++ 14: cbegin, cend\n\t\t//TODO: lancer une exception avec plus de details qu'un booleen et annuler tout les handlers des autre signaux\n\t\treturn false;\n\treturn true;\n}\n\n//! Envoie un message sur la 'message queue' dont l'id est donne en parametre.\n//! Le type 'Buffer' est le type du message envoye devant etre conigue et contenir\n//! un attribut 'long mtype' identifiant le type du message.\ntemplate<typename Buffer>\nbool send_message(ipc_id_t msqid, const Buffer& message)\n{\n\treturn msgsnd(msqid, &message, sizeof(message) - sizeof(long), 0) != -1;\n}\n\n//! Recoit un message issu de la 'message queue' dont l'id est donne en parametre.\n//! Le message recut est ecrit dans 'qbuf'.\n//! Les messages recus sont filtres en fonction de leur types (parametre 'type').\n//! Si la lecture a echouee, la fonction renvoie 'false'.\n//! Un appel a cette fonction est bloquant (appel systeme bloquant).\ntemplate<typename Buffer>\nbool read_message(ipc_id_t msqid, long type, Buffer& qbuf)\n{\n\tint rslt = 0;\n\tdo\n\t{\n\t\trslt = msgrcv(msqid, &qbuf, sizeof(Buffer) - sizeof(long), type, 0);\n\t} while (rslt == -1 && errno == EINTR);\n\treturn rslt >= 0;\n}\n\n//! Ouvre une 'message queue' dont l'id sera donne dans 'msquid'.\n//! La message queue est identifiee par les parametres 'id' et 'path' permettant\n//! de creer une cle (ftok).\n//! Le parametre 'permission' permet de specifier les autorisation d'acces a la\n//! 'message queue' (600 par defaut).\nbool open_message_queue(ipc_id_t& msqid, int id, int permission = 0600, std::string path = std::string(\".\"));\n\n//! Crée une 'message queue' dont l'id sera donne dans 'msquid'.\n//! La message queue est identifiee par les parametres 'id' et 'path' permettant\n//! de creer une cle (ftok).\n//! Le parametre 'permission' permet de specifier les autorisation d'acces a la\n//! 'message queue' (600 par defaut).\n//! Le parametre optionnel 'fail_if_exist' permet de choisir si la creation doit \n//! echouer si la message_queue existe deja ('false' par defaut).\nbool create_message_queue(ipc_id_t& msqid, int id, int permission = 0600, std::string path = std::string(\".\"), bool fail_if_exist = false);\n\n//! Supprime la 'message_queue' dont l'id est donne en parametre.\n//! Retourne 'true' si la suppression a bien eut lieu.\nbool delete_message_queue(ipc_id_t msqid);\n\nnamespace\n{\n\ttemplate<typename T>\n\tshared_mem<T> get_or_create_shared_memory(ipc_id_t id, int permisssion, std::string path, bool fail_if_exist, bool create, bool attach = true)\n\t{\n\t\t// Cree une cle identifiant la memoire partagee\n\t\tkey_t key = ftok(path.data(), id);\n\t\tif (key == -1)\n\t\t\treturn{ -1, nullptr };\n\n\t\t// Cree ou ouvre la memoire partagee\n\t\tint flags = permisssion;\n\t\tif (create)\n\t\t\tflags |= IPC_CREAT;\n\t\tif (fail_if_exist)\n\t\t\tflags |= IPC_EXCL;\n\t\tauto shmid = shmget(key, sizeof(T), flags);\n\t\tif (shmid == -1)\n\t\t\treturn{ -1, nullptr };\n\n\t\tif (attach)\n\t\t{\n\t\t\t// Recupere un pointeur vers la memoire partagee\n\t\t\tT* data = reinterpret_cast<T*>(shmat(shmid, nullptr, 0));\n\t\t\tif (data == reinterpret_cast<T*>(-1))\n\t\t\t\treturn{ -1, nullptr };\n\n\t\t\t// Execute le constructeur du type 'T' a l'adresse allouee\n\t\t\tif (create)\n\t\t\t\tnew (data) T();\n\n\t\t\treturn{ shmid, data };\n\t\t}\n\t\treturn{ shmid, nullptr };\n\t}\n}\n\n//! Ouvre une memoire partagée pour un objet de type 'T'.\n//! La memoire partagée est identifiee par les parametres 'id' et 'path' permettant\n//! de creer une cle (ftok).\n//! Le parametre 'permission' permet de specifier les autorisation d'acces a la\n//! memoire partagée (600 par defaut).\n//! Le type 'T' doit disposer d'un constructeur par defaut.\ntemplate<typename T>\nshared_mem<T> get_shared_memory(ipc_id_t id, int permisssion = 0600, std::string path = \".\")\n{\n\treturn get_or_create_shared_memory<T>(id, permisssion, path, false, false);\n}\n\n//! Crée une memoire partagée pour un objet de type 'T'.\n//! La memoire partagée est identifiee par les parametres 'id' et 'path' permettant\n//! de creer une cle (ftok).\n//! Le parametre 'permission' permet de specifier les autorisation d'acces a la\n//! memoire partagée (600 par defaut).\n//! Le parametre optionnel 'fail_if_exist' permet de choisir si la creation doit \n//! echouer si la memoire partagée existe deja ('false' par defaut).\n//! Le type 'T' doit disposer d'un constructeur par defaut.\ntemplate<typename T>\nshared_mem<T> create_shared_memory(ipc_id_t id, int permisssion = 0600, std::string path = \".\", bool fail_if_exist = false)\n{\n\treturn get_or_create_shared_memory<T>(id, permisssion, path, fail_if_exist, true);\n}\n\n//! Detache l'objet de type 'T' de la mémoire partagée\n//! Retourne 'true' si l'operation a eut lieu sans erreurs.\ntemplate<typename T>\nbool detach_shared_memory(T& shared_data)\n{\n\treturn (shmdt(&shared_data) != -1);\n}\n\n//! Crée une memoire partagée pour un objet de type 'T' sans l'attacher au processus courant.\n//! La memoire partagée est identifiee par les parametres 'id' et 'path' permettant\n//! de creer une cle (ftok).\n//! Le parametre 'permission' permet de specifier les autorisation d'acces a la\n//! memoire partagée (600 par defaut).\n//! Le parametre optionnel 'fail_if_exist' permet de choisir si la creation doit \n//! echouer si la memoire partagée existe deja ('false' par defaut).\n//! Le type 'T' doit disposer d'un constructeur par defaut.\n//! Retourne l'id de la mémoire partagée ou -1 en cas d'erreur \ntemplate<typename T>\nipc_id_t create_detached_shared_mem(ipc_id_t id, int permisssion = 0600, std::string path = \".\", bool fail_if_exist = false)\n{\n\tauto memory = get_or_create_shared_memory<T>(id, permisssion, path, fail_if_exist, true, false);\n\treturn memory.id;\n}\n\n//! Détruit la mémoire partagée identifiée par sont id donné en paramètre.\n//! Retourne 'true' si la suppression a bien eut lieu.\nbool delete_shared_memory(ipc_id_t id);\n\n//! Ajoute la valeur 'num_to_add' à la 'sem_num'-ème semaphore du tableau de\n//! semaphores 'sems_id' (ajoute 1 par defaut).\nbool sem_pv(ipc_id_t sems_id, short unsigned int sem_num, short num_to_add = 1);\n\n//! Protège/execute la fonction 'func' donnée en paramètre avec la 'sem_num'-ème\n//! semaphore du tableau de semaphores 'sems_id'.\nbool lock(ipc_id_t sems_id, short unsigned int sem_num, const std::function<void(void)>& func);\n\n#endif // PROCESS_UTILS_H\n" }, { "alpha_fraction": 0.44006308913230896, "alphanum_fraction": 0.5552050471305847, "avg_line_length": 17.114286422729492, "blob_id": "69fad08dbbae6e1e71cd3e946e4b323094de970e", "content_id": "e40e4362e14e28817823f8ff3d59f4007c0fc818", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 634, "license_type": "permissive", "max_line_length": 62, "num_lines": 35, "path": "/TP2_Concurrency/question1.c", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdint.h>\n\nvoid print_prime_factors(uint64_t n)\n{\n uint64_t i = 0;\n uint64_t nPrime = n;\n printf(\"%ju : \", n);\n for( i = 2 ; i <= nPrime ; i ++)\n {\n\t\tif(nPrime%i == 0)\n\t\t{\n\t\t\tnPrime = nPrime/i;\n\t\t\tprintf(\"%ju \", i);\n\t\t\tfflush(stdout);\n\t\t\ti = 1; \n\t\t}\n\t\telse if(nPrime < 2 || nPrime > n)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\r\\n\");\n}\n\nint main(void)\n{\n print_prime_factors(77); // expected result: 77: 7 11\n print_prime_factors(84); // expected result: 84: 2 2 3 7\n\t\n // expected result: 429496729675917: 3 18229 7853726291\n print_prime_factors(429496729675917);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.47051647305488586, "alphanum_fraction": 0.4786498546600342, "avg_line_length": 39.31147384643555, "blob_id": "0ea4c37e5482341584e1c2e9e9357b231ac776cb", "content_id": "eb98c64959ea4b6af90a8eec67a86e934d374cb0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2461, "license_type": "permissive", "max_line_length": 95, "num_lines": 61, "path": "/TP2_cpp/includes/capteur_stat.h", "repo_name": "PaulEmmanuelSotir/TPs_3IF", "src_encoding": "UTF-8", "text": "/*********************************************************************************************\n\t\t\t\t\tcapteur_stat - A struture of sensor's statistics\n\t\t\t\t\t--------------------------------------------------\ndate : 11/2015\ncopyright : (C) 2015 by B3311\n**********************************************************************************************/\n\n//-------------------------- Interface de la structure capteur_stat ---------------------------\n#pragma once\n\n//----------------------------------------------------------------------- Includes personnels\n#include \"capteur_event.h\"\n\nnamespace TP2\n{\n\tstruct capteur_stat\n\t{\n\t\t//---------------------------------------------------------------------------- PUBLIC\n\tpublic:\n\t\t//---------------------------------------------------------------------------- Usings\n\t\tusing sensor_t = capteur_event::sensor_t;\n\t\t//-------------------------------------------------------- Constructeurs destructeurs\n\t\tcapteur_stat() = default;\n\t\tcapteur_stat(capteur_event initial_event);\n\t\tcapteur_stat(const capteur_stat& other);\n\t\tcapteur_stat(capteur_stat&& other) noexcept;\n\t\t~capteur_stat();\n\n\t\t//---------------------------------------------------------------- Méthodes publiques\n\n\t\tvoid update(capteur_event new_event);\n\t\t/// <summary> calcul les ctatistique de trafic pour un capteur </summary>\n\t\tvoid show_time_distribution() const;\n\n\t\tsensor_t get_id() const;\n\t\tsensor_t get_d7() const;\n\t\tsensor_t get_hour() const;\n\t\tsensor_t get_min() const;\n\n\t\t//----------------------------------------------------------------------------- PRIVE\n\tprivate:\n\t\tsensor_t m_taffic_counts[capteur_event::TRAFFIC_CARDINALITY] = { 0, 0, 0, 0 };\n\t\tcapteur_event m_stat_timestamp;\n\n\t\tstatic inline size_t to_taffic_count_idx(traffic state);\n\n\t\t//----------------------------------------------------------- Surcharges d'opérateurs\n\tpublic:\n\t\tconst capteur_stat& operator=(capteur_stat other);\n\n\t\tfriend bool operator==(const capteur_stat& lhs, const capteur_stat& rhs);\n\t\tfriend bool operator!=(const capteur_stat& lhs, const capteur_stat& rhs);\n\n\t\tfriend bool operator<(const capteur_stat& lhs, const capteur_stat& rhs);\n\t\tfriend bool operator>(const capteur_stat& lhs, const capteur_stat& rhs);\n\t\tfriend bool operator<=(const capteur_stat& lhs, const capteur_stat& rhs);\n\t\tfriend bool operator>=(const capteur_stat& lhs, const capteur_stat& rhs);\n\n\t\tfriend void swap(capteur_stat& lhs, capteur_stat& rhs) noexcept;\n\t};\n}\n" } ]
135
NGS-ISC/model-studio
https://github.com/NGS-ISC/model-studio
f2a243b4a025863868433a68ea3e1f2e2158ea93
22f1a0d0577f868ad650777a465f5da3b7958396
2c02c899161af2c33020b52bc5f1456a0abcf480
refs/heads/master
2021-08-24T15:55:52.363294
2017-12-10T09:42:46
2017-12-10T09:42:46
110,221,072
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6959064602851868, "alphanum_fraction": 0.6959064602851868, "avg_line_length": 23.428571701049805, "blob_id": "1c627b06060ffe6ca6ac5f8af864759981f050cf", "content_id": "1d458ba59121363f04310233b306ff2cb42b3cf0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "permissive", "max_line_length": 44, "num_lines": 7, "path": "/icc.modelstudio/src/icc/modelstudio/__init__.py", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "# Example package with a console entry point\nfrom __future__ import print_function\n\n\ndef main(*args, **kwargs):\n from isu.gui.gtk import main\n main(*args, **kwargs)\n" }, { "alpha_fraction": 0.6350435614585876, "alphanum_fraction": 0.6450467705726624, "avg_line_length": 31.28125, "blob_id": "5cf769f5158147a57ae0d27723a010bdfcf6e5c6", "content_id": "20355127e5d4dbc688ecdd03b5a39de30c984e35", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3099, "license_type": "permissive", "max_line_length": 85, "num_lines": 96, "path": "/icc.modelstudio/setup.py", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "# This is your \"setup.py\" file.\n# See the following sites for general guide to Python packaging:\n# * `The Hitchhiker's Guide to Packaging <http://guide.python-distribute.org/>`_\n# * `Python Project Howto <http://infinitemonkeycorps.net/docs/pph/>`_\n\nfrom setuptools import setup, find_packages\nimport sys, os\n#from Cython.Build import cythonize\nfrom setuptools.extension import Extension\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\nNEWS = open(os.path.join(here, 'NEWS.rst')).read()\n\n\nversion = '0.1'\n\ninstall_requires = [\n # List your project dependencies here.\n # For more details, see:\n # http://packages.python.org/distribute/setuptools.html#declaring-dependencies\n # Packages with fixed versions\n # \"<package1>==0.1\",\n # \"<package2>==0.3.0\",\n # \"nose\", \"coverage\" # Put it here.\n]\n\ntests_requires = [\n # List your project testing dependencies here.\n]\n\ndev_requires = [\n # List your project development dependencies here.\\\n]\n\ndependency_links = [\n # Sources for some fixed versions packages\n #'https://github.com/<user1>/<package1>/archive/master.zip#egg=<package1>-0.1',\n #'https://github.com/<user2>/<package2>/archive/master.zip#egg=<package2>-0.3.0',\n]\n\n#Cython extension\n\n#TOP_DIR=\"/home/eugeneai/Development/codes/NLP/workprog/tmp/link-grammar\"\n#LG_DIR=\"link-grammar\"\n#LG_LIB_DIR=os.path.join(TOP_DIR,LG_DIR,\".libs\")\n#LG_HEADERS=os.path.join(TOP_DIR)\n\next_modules=[\n# Extension(\"icc.modelstudio.cython_module\",\n# sources=[\"src/./icc.modelstudio/cython_module.pyx\"],\n# libraries=[\"gdal\"],\n# )\n]\n\nsetup(\n name='icc.modelstudio',\n version=version,\n description=\"A GUI program for control of microbioma modeling.\",\n long_description=README + '\\n\\n' + NEWS,\n # Get classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n # classifiers=[c.strip() for c in \"\"\"\n # Development Status :: 4 - Beta\n # License :: OSI Approved :: MIT License\n # Operating System :: OS Independent\n # Programming Language :: Python :: 2.6\n # Programming Language :: Python :: 2.7\n # Programming Language :: Python :: 3\n # Topic :: Software Development :: Libraries :: Python Modules\n # \"\"\".split('\\n') if c.strip()],\n # ],\n keywords='GUI naturl modeling dataflow GTK+',\n author='Evgeny Cherkashin',\n author_email='[email protected]',\n url='https://github.com/NGS-ISC/model-studio',\n license='Apache-2.0',\n packages=find_packages(\"src\"),\n package_dir = {'': \"src\"},\n namespace_packages = ['icc'],\n include_package_data=True,\n zip_safe=False,\n install_requires=install_requires,\n dependency_links = dependency_links,\n extras_require={\n 'tests': tests_requires,\n 'dev': dev_requires,\n },\n test_suite='tests',\n entry_points={\n 'console_scripts':\n ['icc.modelstudio=icc.modelstudio:main']\n },\n #ext_modules = cythonize(ext_modules),\n #test_suite = 'nose.collector',\n #setup_requires=['nose>=1.0','Cython','coverage']\n)\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 31.5, "blob_id": "79aade636e40f4cfcdf8ffbf99748b175f448d48", "content_id": "491157ee20e91e92f76522985875bf8c1e41bb7c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "permissive", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "# model-studio\nA GUI program for control of microbioma modeling.\n" }, { "alpha_fraction": 0.7211538553237915, "alphanum_fraction": 0.7211538553237915, "avg_line_length": 50.5, "blob_id": "94280cc46e5448f35c4b84f58f1c67ab0d26feed", "content_id": "08d4155d98d4d1a2a6653fc9c894d60498f1e0bd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 104, "license_type": "permissive", "max_line_length": 56, "num_lines": 2, "path": "/ui/Makefile", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "\nresources.c: ../ui/model_studio.gresource.xml\n\tglib-compile-resources $< --target=$@ --generate-source\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 7.666666507720947, "blob_id": "3fbeceb44716e94c8563824b16fefda1129c9212", "content_id": "27990132fc9c9a2b81cfcfb81e7042ca245cc8f9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 26, "license_type": "permissive", "max_line_length": 11, "num_lines": 3, "path": "/icc.modelstudio/requirements.txt", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "#gi\n#libgflow\n#libgtkflow\n" }, { "alpha_fraction": 0.6514175534248352, "alphanum_fraction": 0.6514175534248352, "avg_line_length": 19.15584373474121, "blob_id": "e72867391702cc42b9a39ddba0e243109f5cda3a", "content_id": "3498c004457eb4495fc73a689ed00bbfcc2b936f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1552, "license_type": "permissive", "max_line_length": 82, "num_lines": 77, "path": "/icc.modelstudio/Makefile", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": ".PHONY: env dev develop install test edit \\\n\tpy pot init-ru update-ru comp-cat \\\n\tupd-cat setup test setup-requs tests \\\n\trun-tests gdb-test clean\n\n#A source dir of a local C/C++ library to link with\n#TOP_DIR=\n\n#A virtualenv name\n#LPYTHON=model\n#V=$(HOME)/.pyenv/versions/$(LPYTHON)\n#VB=$(V)/bin\nPYTHON=python\n#PYTHON=$(VB)/$(LPYTHON)\n#ROOT=$(PWD)\n#INI=icc.modelstudio\n#LCAT=src/icc.modelstudio/locale/\n\n#LG_DIR=\"link-grammar\"\n#LG_LIB_DIR=$(TOP_DIR)/$(LG_DIR)/.libs\n#LG_HEADERS=$(TOP_DIR)\n\nenv:\n\t[ -d $(V) ] || virtualenv $(V)\n\t$(VB)/easy_install --upgrade pip\n\npre-dev:env #dev-....\n\t$(VB)/easy_install pip setuptools\n\nsetup:\n\t$(PYTHON) setup.py build_ext # -L$(LG_LIB_DIR) -R$(LG_LIB_DIR) -I$(LG_HEADERS)\n\t$(PYTHON) setup.py develop\n\ndev:\tpre-dev setup-requs setup # upd-cat\n\ndevelop: dev\n\ninstall: env comp-cat\n\t$(PYTHON) setup.py install\n\nedit:\n\tcd src && emacs\n\nsetup-requs: requirements.txt\n\tpip install -r requirements.txt\n\nrun-tests:\n\tnosetests -w src/tests\n\ntests:\trun-tests\n\ntest:\tsetup run-tests\n\ngdb-test: setup\n\tgdb --args $(PYTHON) $(VB)/nosetests -w src/tests\n\npy:\n\t$(PYTHON)\npot:\n\tmkdir -p $(LCAT)\n\t$(VB)/pot-create src -o $(LCAT)/messages.pot || echo \"Someting unusual with pot.\"\n\ninit-ru:\n\t$(PYTHON) setup.py init_catalog -l ru -i $(LCAT)/messages.pot \\\n -d $(LCAT)\n\nupdate-ru:\n\t$(PYTHON) setup.py update_catalog -l ru -i $(LCAT)/messages.pot \\\n -d $(LCAT)\n\ncomp-cat:\n\t$(PYTHON) setup.py compile_catalog -d $(LCAT)\n\nupd-cat: pot update-ru comp-cat\n\nclean:\n\t$(PYTHON) setup.py clean\n" }, { "alpha_fraction": 0.6159235835075378, "alphanum_fraction": 0.6254777312278748, "avg_line_length": 28.62264060974121, "blob_id": "2d51fd825ca3e869bf065050d7d26563f7f92b0b", "content_id": "47c16bb4b9bfad183108312f88b12d5349cc8c31", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1570, "license_type": "permissive", "max_line_length": 75, "num_lines": 53, "path": "/icc.modelstudio/src/tests/test_basic.py", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": "from nose.plugins.skip import SkipTest\nfrom nose.tools import assert_raises, nottest\nimport os\n\ntypelib = '/home/eugeneai/development/codes/ngs/model-studio/vala/builddir'\n\n# os.environ['GI_TYPELIB_PATH'] = typelib\n# os.environ['LD_LIBRARY_PATH'] = typelib\n\n#@SkipTest\n\n\nclass TestBasic:\n\n def setUp(self):\n pass\n\n def test_something(self):\n assert 1 + 1 == 2\n\n def test_gobject(self):\n import os\n os.environ[\"GI_TYPELIB_PATH\"] = typelib\n import gi\n import pprint\n gi.require_version('GIRepository', '2.0')\n from gi.repository import GIRepository\n Rep = GIRepository.Repository\n # pprint.pprint(dir(Rep))\n # print(Rep.get_loaded_namespaces())\n print(Rep.get_search_path())\n # GIRepository.Repository.prepend_search_path(typelib)\n # print(Rep.get_search_path())\n rep = Rep.get_default()\n print(rep.get_loaded_namespaces())\n\n gi.require_version('Gtk', '3.0')\n gi.require_version('GFlow', '0.2')\n gi.require_version('GtkFlow', '0.2')\n print(\"1:\", rep.get_loaded_namespaces())\n from gi.repository import GLib\n from gi.repository import Gtk\n from gi.repository import GFlow\n from gi.repository import GtkFlow\n print(\"2:\", rep.get_loaded_namespaces())\n gi.require_version('ModelStudio', '0.1')\n #from gi.repository import ModelStudio\n print(dir(ModelStudio.Application))\n app = ModelStudio.Application.new()\n app.run()\n\n def tearDown(self):\n pass\n" }, { "alpha_fraction": 0.6836664080619812, "alphanum_fraction": 0.6933149695396423, "avg_line_length": 23.183332443237305, "blob_id": "3b16e6039fecf14fd50db02cde8526b5b052cd17", "content_id": "1f4db1ee30ea8936b2a3eec610cef5b7f8411b71", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1451, "license_type": "permissive", "max_line_length": 80, "num_lines": 60, "path": "/vala/Makefile", "repo_name": "NGS-ISC/model-studio", "src_encoding": "UTF-8", "text": ".PHONY: run build all meson meson-run\n\nAPI=0.1\n\nICCGUI=/home/eugeneai/Development/codes/NGS/model-studio/isu.gui.gtk/vala\nGRCDIR=/home/eugeneai/Development/codes/NGS/model-studio/isu.gui.gtk/vala\n\nPACKAGES=--pkg=gtk+-3.0 --pkg=glib-2.0\nRES=resources.o\nGRES=model_studio.gresource.xml\nSRC=model_studio.vala\nOBJS=model_studio.o $(RES)\n\nRSFLAGS= --gresources=$(GRES) --gresourcesdir=$(GRCDIR)\nFLAGS=-X $(ICCGUI)/icc_gui.so -X -I$(ICCGUI) -g\n\n# all: build-c test\n\nmeson: clean\n\tmeson builddir\n\tcd builddir && meson configure -Dapi=$(API)\n\tninja -v -C builddir\n\tninja -v -C builddir ModelStudio-$(API).typelib\n\nmeson-run: meson\n\tcd builddir && ./model-studio\n\nrun: build\n\ntest: build build-test\n\tLD_LIBRARY_PATH=$(ICCGUI) ./model_studio\n\nbuild-direct: $(SRC)\n\tvalac -o model_studio $(ICCGUI)/icc_gui.vapi $< $(PACKAGES) $(FLAGS) $(RSFLAGS)\n\nbuild-test:\n\nbuild: model_studio\n\nmodel_studio.c: $(SRC)\n\tvalac -C $(ICCGUI)/icc_gui.vapi $< $(PACKAGES) $(RSFLAGS)\n\nresources.c: $(GRES) application_window.glade\n\tglib-compile-resources $< --target=$@ --generate-source\nall: demo\n\nclean:\n\trm -fv *~ *.o model_studio *.c\n\trm -rf builddir\n\n\n#my-resources.c: my-resources.xml mywidget.ui\n#\tglib-compile-resources my-resources.xml \\\n#\t\t--target=$@ --sourcedir=$(srcdir) --c-name _my --generate-source\n\n%.o:%.c\n\tgcc -o $@ -c $< -Wall `pkg-config --cflags gtk+-3.0 gmodule-export-2.0`\n\nmodel_studio: $(OBJS)\n\tgcc -o $@ $^ `pkg-config --libs gtk+-3.0 gmodule-export-2.0`\n" } ]
8
Tarun-yadav777/Djanjo-Project-Schemer-
https://github.com/Tarun-yadav777/Djanjo-Project-Schemer-
4b2de7779768e30ef77fb3f05154a90727c60b03
1ed3ac0f4f86836131211b286d866884b53d53cb
301e1fb7806bfe7eecbd9c8982ee3c9ab90a6db4
refs/heads/master
2023-01-29T02:45:54.315059
2020-12-15T07:33:14
2020-12-15T07:33:14
321,587,681
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5967742204666138, "alphanum_fraction": 0.6306451559066772, "avg_line_length": 33.44444274902344, "blob_id": "6d0f91d3a8b0ef1f82d136c012ae8aca2453b69b", "content_id": "f963c1ee23c05fa97e792b0a896add679078b378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 620, "license_type": "no_license", "max_line_length": 287, "num_lines": 18, "path": "/schemegen/migrations/0003_auto_20201116_1718.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-11-16 11:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('schemegen', '0002_delete_genre'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='schemegen',\n name='type',\n field=models.CharField(choices=[(\"Women's Development\", \"Women's Development\"), ('Social Justice', 'Social Justice'), ('Sports', 'Sports'), ('Ruler Development', 'Ruler Development'), ('Child Development', 'Child Development')], default=\"Women's Development\", max_length=20),\n ),\n ]\n" }, { "alpha_fraction": 0.6324503421783447, "alphanum_fraction": 0.6523178815841675, "avg_line_length": 29.200000762939453, "blob_id": "1d6af83b097128ef77ebba408663b34c8320ca87", "content_id": "1757caadd2218e3a6bb9ccb473b18b6437da56f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/schemegen/models.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Schemegen(models.Model):\n choices = [\n (\"Women's Development\", \"Women's Development\"),\n (\"Social Justice\", \"Social Justice\"),\n (\"Sports\", \"Sports\"),\n (\"Ruler Development\", \"Ruler Development\"),\n (\"Child Development\", \"Child Development\")\n ]\n\n name = models.CharField(max_length=200)\n type = models.CharField(max_length=20, choices=choices, default=\"Women's Development\")\n info_link = models.URLField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass User_info(models.Model):\n name = models.CharField(max_length=200)\n gender = models.CharField(max_length=6)\n dob = models.DateField(auto_now=False)\n address = models.CharField(max_length=100)\n phone_no = models.IntegerField()\n interested_scheme = models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.519298255443573, "alphanum_fraction": 0.5859649181365967, "avg_line_length": 16.8125, "blob_id": "52cf015b99f56429c56523f5cdf9bc0b1be878f7", "content_id": "e363617b94075bce68869a315d754ed4fb1c3071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/schemegen/migrations/0002_delete_genre.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-11-13 11:25\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('schemegen', '0001_initial'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Genre',\n ),\n ]\n" }, { "alpha_fraction": 0.7046511769294739, "alphanum_fraction": 0.7046511769294739, "avg_line_length": 34.91666793823242, "blob_id": "03923f3b3e3f4a0740763bdb2003a1eb47390117", "content_id": "c639f702887393a45175eb900418b8b829513f45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/schemegen/urls.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom schemegen import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('adhaar', views.adhaar, name='adhaar'),\n path('requirements', views.requirements, name='requirements'),\n path('detail', views.detail, name='detail'),\n path('adhaar-hindi', views.adhaar_hindi, name='adhaar_hindi'),\npath('requirements-hindi', views.requirements_hindi, name='requirements-hindi'),\n]" }, { "alpha_fraction": 0.7341576218605042, "alphanum_fraction": 0.7341576218605042, "avg_line_length": 22.10714340209961, "blob_id": "06b9cc300fd27c9512fb8216656e9d5ecbc1e961", "content_id": "7d330069dc3e50df35d91f34744fe0fa89105b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 647, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/schemegen/views.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Schemegen\n\ndef index(request):\n return render(request, 'Index.html')\n\n\ndef adhaar(request):\n return render(request, 'Adhaar.html')\n\n\ndef requirements(request):\n return render(request, 'Requirements.html')\n\n\ndef detail(request):\n type = request.GET['occupation']\n schemes = Schemegen.objects.filter(type=type)\n return render(request, 'detail.html', {'schemes': schemes})\n\n\ndef adhaar_hindi(request):\n return render(request, 'adhaar_hindi.html')\n\n\ndef requirements_hindi(request):\n return render(request, 'requirements_hindi.html')\n" }, { "alpha_fraction": 0.5137446522712708, "alphanum_fraction": 0.5339034795761108, "avg_line_length": 37.97618865966797, "blob_id": "a96c584114aeeaf56ca2ae8cdc295f4fb0699484", "content_id": "72f316ed00e262f04fc96a770f42ff74a22674f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license_type": "no_license", "max_line_length": 239, "num_lines": 42, "path": "/schemegen/migrations/0001_initial.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-11-13 11:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Genre',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Schemegen',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('type', models.CharField(choices=[(\"W's D\", \"Women's Development\"), ('S J', 'Social Justice'), ('S', 'Sports'), ('R D', 'Ruler Development'), (\"C's D\", 'Child Development')], default=\"Women's Development\", max_length=20)),\n ('info_link', models.URLField()),\n ],\n ),\n migrations.CreateModel(\n name='User_info',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('gender', models.CharField(max_length=6)),\n ('dob', models.DateField()),\n ('address', models.CharField(max_length=100)),\n ('phone_no', models.IntegerField()),\n ('interested_scheme', models.CharField(max_length=200)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8175182342529297, "alphanum_fraction": 0.8175182342529297, "avg_line_length": 26.399999618530273, "blob_id": "85e74ece49860960145febfbdfa71ebf9a90fe41", "content_id": "f3167a3cad694bd845865b6fdaefa20e841c42c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/schemegen/admin.py", "repo_name": "Tarun-yadav777/Djanjo-Project-Schemer-", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Schemegen, User_info\n\nadmin.site.register(Schemegen)\nadmin.site.register(User_info)\n" } ]
7
rmarcontel/py4at
https://github.com/rmarcontel/py4at
ffa18d3a9608329a5305f0ca501ef45ea07c7253
5221b9b0646facc81960a9868af90889563dd58b
eb0491313067b9dfd3c3a9141ffdd6fb6cd6ac2b
refs/heads/master
2023-07-12T17:59:49.578217
2021-08-25T22:00:32
2021-08-25T22:00:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7446808218955994, "alphanum_fraction": 0.7517730593681335, "avg_line_length": 28.878787994384766, "blob_id": "98d0b265004372dde09e8df03800aedacb054705", "content_id": "21147b79b25213fae144bb499dd51d7c7be142aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 987, "license_type": "no_license", "max_line_length": 90, "num_lines": 33, "path": "/ch02/Docker/install.sh", "repo_name": "rmarcontel/py4at", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Script to Install\n# Linux System Tools and\n# Basic Python Components\n#\n# Python for Algorithmic Trading\n# (c) Dr. Yves J. Hilpisch\n# The Python Quants GmbH\n#\n# GENERAL LINUX\napt-get update # updates the package index cache\napt-get upgrade -y # updates packages\n# installs system tools\napt-get install -y bzip2 gcc git # system tools\napt-get install -y htop screen vim wget # system tools\napt-get upgrade -y bash # upgrades bash if necessary\napt-get clean # cleans up the package index cache\n\n# INSTALL MINICONDA\n# downloads Miniconda\nwget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O Miniconda.sh\nbash Miniconda.sh -b # installs it\nrm -rf Miniconda.sh # removes the installer\nexport PATH=\"/root/miniconda3/bin:$PATH\" # prepends the new path\n\n# INSTALL PYTHON LIBRARIES\nconda install -y pandas # installs pandas\nconda install -y ipython # installs IPython shell\n\n# CUSTOMIZATION\ncd /root/\nwget http://hilpisch.com/.vimrc # Vim configuration\t\n" }, { "alpha_fraction": 0.617521345615387, "alphanum_fraction": 0.6474359035491943, "avg_line_length": 19.34782600402832, "blob_id": "a340cabf8b6ffe9089a85ddec1838c01906578b0", "content_id": "db69358a8f8ff8b24e42562979d7839dc10b3053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/ch07/BarsServer.py", "repo_name": "rmarcontel/py4at", "src_encoding": "UTF-8", "text": "#\n# Python Script to Serve\n# Random Bars Data\n#\n# Python for Algorithmic Trading\n# (c) Dr. Yves J. Hilpisch\n# The Python Quants GmbH\n#\nimport zmq \nimport math\nimport time\nimport random\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUB)\nsocket.bind('tcp://0.0.0.0:5556')\n\nwhile True:\n bars = [random.random() * 100 for _ in range(8)] \n msg = ' '.join([f'{bar:.3f}' for bar in bars]) \n print(msg)\n socket.send_string(msg)\n time.sleep(random.random() * 2)\n" }, { "alpha_fraction": 0.7346711158752441, "alphanum_fraction": 0.7614269852638245, "avg_line_length": 46.157894134521484, "blob_id": "5360a41a2e48e35c536665007f292e52b15138f8", "content_id": "4c0883e46cb4a65ba3d8c7cc9dbeddf72bf8dbc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 898, "license_type": "no_license", "max_line_length": 231, "num_lines": 19, "path": "/README.md", "repo_name": "rmarcontel/py4at", "src_encoding": "UTF-8", "text": "# Python for Algorithmic Trading\n\n## About this Repository\n\nThis repository provides Python code and Jupyter Notebooks accompanying the **Python for Algorithmic Trading** book published by [O'Reilly](https://www.oreilly.com/library/view/python-for-algorithmic/9781492053347/).\n\n<img src=\"http://hilpisch.com/pyalgo_cover_color.png\" width=\"500\">\n\nYou can **register for free** on our [Quant Platform](http://py4at.pqp.io) to make easy use of the Python codes in the cloud.\n\n## Copyright & Disclaimer\n\n© Dr. Yves J. Hilpisch | The Python Quants GmbH | November 2020\n\nAll code and Jupyter Notebooks come without representations or warranties, to the extent permitted by applicable law. They are intended for personal use only and do not represent any investment advice or recommendation of any form.\n\n<img src=\"http://hilpisch.com/tpq_logo.png\" width=\"250\">\n\nhttp://tpq.io | [email protected] | http://twitter.com/dyjh\n\n" }, { "alpha_fraction": 0.7672448754310608, "alphanum_fraction": 0.7708753347396851, "avg_line_length": 34.92753601074219, "blob_id": "e6b9a53c2b704fa8341eae336ce94868f00307e3", "content_id": "1887a102616fc0706f6ac96f43db4aa7a8a350bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2479, "license_type": "no_license", "max_line_length": 76, "num_lines": 69, "path": "/ch02/cloud/install.sh", "repo_name": "rmarcontel/py4at", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# Script to Install\n# Linux System Tools and Basic Python Components\n# as well as to\n# Start Jupyter Lab Server\n#\n# Python for Algorithmic Trading\n# (c) Dr. Yves J. Hilpisch\n# The Python Quants GmbH\n#\n# GENERAL LINUX\napt-get update # updates the package index cache\napt-get upgrade -y # updates packages\n# install system tools\napt-get install -y gcc git htop # system tools\napt-get install -y screen htop vim wget # system tools\napt-get upgrade -y bash # upgrades bash if necessary\napt-get clean # cleans up the package index cache\n\n# INSTALLING MINICONDA\nwget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \\\n\t\t-O Miniconda.sh\nbash Miniconda.sh -b # installs Miniconda\nrm -rf Miniconda.sh # removes the installer\n# prepends the new path for current session\nexport PATH=\"/root/miniconda3/bin:$PATH\"\n# prepends the new path in the shell configuration\ncat >> ~/.profile <<EOF\nexport PATH=\"/root/miniconda3/bin:$PATH\"\nEOF\n\n# INSTALLING PYTHON LIBRARIES\nconda install -y jupyter # interactive data analytics in the browser\nconda install -y jupyterlab # Jupyter Lab environment\nconda install -y numpy # numerical computing package\nconda install -y pytables # wrapper for HDF5 binary storage\nconda install -y pandas # data analysis package\nconda install -y matplotlib # standard plotting library\nconda install -y seaborn # statistical plotting library\nconda install -y quandl # wrapper for Quandl data API\nconda install -y scikit-learn # machine learning library\nconda install -y openpyxl # package for Excel interaction\nconda install -y xlrd xlwt # packages for Excel interaction\nconda install -y pyyaml # package to manage yaml files\n\npip install --upgrade pip # upgrading the package manager\npip install q # logging and debugging\npip install plotly # interactive D3.js plots\npip install cufflinks # combining plotly with pandas\npip install tensorflow # deep learning library\npip install keras # deep learning library\npip install eikon # Python wrapper for the Refinitiv Eikon Data API\n# Python wrapper for Oanda API\npip install git+git://github.com/yhilpisch/tpqoa\n\n# COPYING FILES AND CREATING DIRECTORIES\nmkdir /root/.jupyter\nmkdir /root/.jupyter/custom\nwget http://hilpisch.com/custom.css\nmv custom.css /root/.jupyter/custom\nmv /root/jupyter_notebook_config.py /root/.jupyter/\nmv /root/mycert.pem /root/.jupyter\nmv /root/mykey.key /root/.jupyter\nmkdir /root/notebook\ncd /root/notebook\n\n# STARTING JUPYTER LAB\njupyter lab &\n" } ]
4
hillarry/sentiment
https://github.com/hillarry/sentiment
32c6eeb79f6d652d9d90c8a9304a381739e7cf3a
0befc453f0edbda9c7a7e78cb030aed5f7fab180
f8db157c20571801a094a263902c45ca5f93647d
refs/heads/master
2023-02-14T00:44:48.115888
2021-01-08T17:30:40
2021-01-08T17:30:40
327,969,051
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6571850776672363, "alphanum_fraction": 0.6845216155052185, "avg_line_length": 56.574466705322266, "blob_id": "6b5ae559bdcfe58c12bc81b7de24557aa4dba1ba", "content_id": "55f1ba06e5a50cc64e7932585cc28a80a6e2c9fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2707, "license_type": "no_license", "max_line_length": 246, "num_lines": 47, "path": "/DlogSysInfo.py", "repo_name": "hillarry/sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'C:\\Users\\DELL\\Desktop\\finalGUI\\DlogSysInfo.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_SystemInfo(object):\n def setupUi(self, SystemInfo):\n SystemInfo.setObjectName(\"SystemInfo\")\n SystemInfo.resize(343, 315)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/imcon/SysInfo1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n SystemInfo.setWindowIcon(icon)\n self.sysInfotxtBrowser = QtWidgets.QTextBrowser(SystemInfo)\n self.sysInfotxtBrowser.setGeometry(QtCore.QRect(0, 0, 351, 321))\n self.sysInfotxtBrowser.setStyleSheet(\"font: 8pt \\\"Courier New\\\";\")\n self.sysInfotxtBrowser.setObjectName(\"sysInfotxtBrowser\")\n\n self.retranslateUi(SystemInfo)\n QtCore.QMetaObject.connectSlotsByName(SystemInfo)\n\n def retranslateUi(self, SystemInfo):\n _translate = QtCore.QCoreApplication.translate\n SystemInfo.setWindowTitle(_translate(\"SystemInfo\", \"SystemInfo\"))\n self.sysInfotxtBrowser.setHtml(_translate(\"SystemInfo\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'Courier New\\'; font-size:8pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p align=\\\"center\\\" style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:11pt; font-weight:600;\\\">System Info</span></p>\\n\"\n\"<p style=\\\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\\'MS Shell Dlg 2\\'; font-size:10pt;\\\"><br /></p>\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:10pt;\\\">* Powered by Ipython,</span></p>\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:10pt;\\\">* Designed by PyQt5 Designer</span></p></body></html>\"))\n\nimport imicons\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n SystemInfo = QtWidgets.QDialog()\n ui = Ui_SystemInfo()\n ui.setupUi(SystemInfo)\n SystemInfo.show()\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.695803165435791, "alphanum_fraction": 0.7111432552337646, "avg_line_length": 32.153846740722656, "blob_id": "967aff31e60377eeda480c9743bec5f8928e8612", "content_id": "3360a4957f385708f77464cfb2eeedd5ecdce23e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3455, "license_type": "no_license", "max_line_length": 142, "num_lines": 104, "path": "/prouitest.py", "repo_name": "hillarry/sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 21 21:41:50 2019\n\n@author: User\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 14 22:02:39 2019\n\n@author: User\n\"\"\"\n\nimport nltk\nimport pandas as pd\nimport numpy as np\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer=WordNetLemmatizer()\nstemming = PorterStemmer()\nstops = set(stopwords.words(\"english\"))\ntry:\n file=open(\"D:/VITproject/train4.csv\",\"r\")\nexcept:\n print(\"File not found or path is incorrect\")\ndf=pd.read_csv(file,error_bad_lines=False,engine=\"python\")\ndf.comment=df.comment.astype(str)\ndef apply_cleaning_function_to_list(X):\n cleaned_X = []\n for element in X:\n cleaned_X.append(clean_text(element))\n return cleaned_X\ndef clean_text(raw_text):\n # Convert to lower case\n text = raw_text.lower()\n \n # Tokenize\n tokens = nltk.word_tokenize(text)\n \n # Keep only words (removes punctuation + numbers)\n # use .isalnum to keep also numbers\n token_words = [w for w in tokens if w.isalpha()]\n \n # Stemming\n #stemmed_words = [stemming.stem(w) for w in token_words]\n # lemmatizing\n lemmatized_words=[lemmatizer.lemmatize(word) for word in token_words]\n \n # Remove stop words\n meaningful_words = [w for w in lemmatized_words if not w in stops]\n # Rejoin meaningful stemmed words\n joined_words = ( \" \".join(meaningful_words))\n \n # Return cleaned data\n return joined_words\n#test.head(10)\ntext_to_clean =list(df['comment'])\ncleaned_text = apply_cleaning_function_to_list(text_to_clean)\n#for i in range(504):\n# #clean=cleaned_text[i]\n# print('Original text:',text_to_clean[i])\n# print ('\\nCleaned text:', cleaned_text[i])\n# print('')\n#combi=df.append(cleaned_text[i],ignore_index=True)\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer=CountVectorizer()\nvectorizer.fit(cleaned_text)\n#print(\"Vocabulary_content:\\n{}\".format(vectorizer.vocabulary_))\n#print(\"Features names:\"+str(vectorizer.get_feature_names()))\n#print(df.shape)\n#print(df.info())\nfrom sklearn.model_selection import train_test_split \nX_train, X_test, y_train, y_test = train_test_split(cleaned_text,df['sentiment'],train_size=0.75,test_size=0.25,random_state=42,shuffle=True) \n#print(X_train.shape,y_train.shape)\nTfidf_vect=TfidfVectorizer(max_features=5000)\nTfidf_vect.fit(cleaned_text)\nTrain_X_Tfidf=Tfidf_vect.transform(X_train)\nTest_X_Tfidf=Tfidf_vect.transform(X_test)\n#from sklearn import svm\nfrom sklearn import metrics\n#clf=svm.SVC(kernel='linear')\n#clf.fit(Train_X_Tfidf,y_train) \n#y_pred=clf.predict(Test_X_Tfidf)\n#accuracy=metrics.accuracy_score(y_test,y_pred)*100\n#print(\"Accuracy of the classifier=\",round(accuracy,2),'%')\nfrom sklearn.naive_bayes import MultinomialNB\nnb=MultinomialNB()\nnb.fit(Train_X_Tfidf,y_train)\n#print(\"Training set score:{:.3f}\".format(nb.score(Train_X_Tfidf,y_train)))\n#print(\"Test set score:{:.4f}\".format(nb.score(Test_X_Tfidf,y_test)))\npred_nb=nb.predict(Test_X_Tfidf)\nconfusion=metrics.confusion_matrix(y_test,pred_nb)\n#print(\"Confusion matrix:\\n{}\".format(confusion))\n#text_input=input(\"Enter the text what you want to type:\")\ndef testing(text_input):\n result=(nb.predict(vectorizer.transform([text_input]))[0])\n if result==1:\n return result\n elif result==0:\n return result\n#print(testing(\"Why was she so upset?\"))\n\n\n \n" }, { "alpha_fraction": 0.6652123928070068, "alphanum_fraction": 0.6895522475242615, "avg_line_length": 44.35416793823242, "blob_id": "63bf81c9e8a80185c6128a32a9d7d80fa89912fc", "content_id": "7842ac7f7babb3447aed85d5202a8fc05c2f128d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4355, "license_type": "no_license", "max_line_length": 236, "num_lines": 96, "path": "/DesignedWelWindow.py", "repo_name": "hillarry/sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'C:\\Users\\DELL\\Desktop\\finalGUI\\DesignedWelWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom DesignedHomeWin import Ui_HomeMainWindow\n\nclass Ui_DesignedWelWindow(object):\n\n def openMainWin(self):\n self.window = QtWidgets.QMainWindow()\n self.ui = Ui_HomeMainWindow()\n self.ui.setupUi(self.window)\n DesignedWelWindow.hide()\n self.window.show()\n\n\n \n def setupUi(self, DesignedWelWindow):\n DesignedWelWindow.setObjectName(\"DesignedWelWindow\")\n DesignedWelWindow.resize(762, 326)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/imcon/senti2.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n DesignedWelWindow.setWindowIcon(icon)\n self.centralwidget = QtWidgets.QWidget(DesignedWelWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.lbl_Heading = QtWidgets.QLabel(self.centralwidget)\n self.lbl_Heading.setGeometry(QtCore.QRect(160, 60, 541, 51))\n font = QtGui.QFont()\n font.setFamily(\"MV Boli\")\n font.setPointSize(26)\n self.lbl_Heading.setFont(font)\n self.lbl_Heading.setObjectName(\"lbl_Heading\")\n self.lbl_HeadIcon = QtWidgets.QLabel(self.centralwidget)\n self.lbl_HeadIcon.setGeometry(QtCore.QRect(40, 20, 121, 91))\n self.lbl_HeadIcon.setStyleSheet(\"image:url(:/imcon/classify1.png)\")\n self.lbl_HeadIcon.setText(\"\")\n self.lbl_HeadIcon.setObjectName(\"lbl_HeadIcon\")\n self.lbl_welIcon = QtWidgets.QLabel(self.centralwidget)\n self.lbl_welIcon.setGeometry(QtCore.QRect(620, 150, 51, 41))\n self.lbl_welIcon.setStyleSheet(\"image:url(:/imcon/senti1.png)\")\n self.lbl_welIcon.setText(\"\")\n self.lbl_welIcon.setObjectName(\"lbl_welIcon\")\n self.lbl_wel = QtWidgets.QLabel(self.centralwidget)\n self.lbl_wel.setGeometry(QtCore.QRect(120, 160, 501, 41))\n font = QtGui.QFont()\n font.setFamily(\"Lucida Calligraphy\")\n font.setPointSize(11)\n self.lbl_wel.setFont(font)\n self.lbl_wel.setObjectName(\"lbl_wel\")\n self.btnOpenMainWindow = QtWidgets.QPushButton(self.centralwidget)\n self.btnOpenMainWindow.setGeometry(QtCore.QRect(230, 250, 271, 41))\n font = QtGui.QFont()\n font.setFamily(\"Lucida Calligraphy\")\n font.setPointSize(11)\n self.btnOpenMainWindow.setFont(font)\n self.btnOpenMainWindow.setStyleSheet(\"\\n\"\n\"color: rgb(133, 66, 199);\\n\"\n\"background-color: rgb(0, 209, 0);\")\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\":/imcon/key1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnOpenMainWindow.setIcon(icon1)\n self.btnOpenMainWindow.setObjectName(\"btnOpenMainWindow\")\n\n #click to open home window\n self.btnOpenMainWindow.clicked.connect(self.openMainWin)\n \n DesignedWelWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(DesignedWelWindow)\n self.statusbar.setObjectName(\"statusbar\")\n DesignedWelWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(DesignedWelWindow)\n QtCore.QMetaObject.connectSlotsByName(DesignedWelWindow)\n\n def retranslateUi(self, DesignedWelWindow):\n _translate = QtCore.QCoreApplication.translate\n DesignedWelWindow.setWindowTitle(_translate(\"DesignedWelWindow\", \"This is a Welcome Page to You!\"))\n self.lbl_Heading.setText(_translate(\"DesignedWelWindow\", \"<html><head/><body><p><span style=\\\" color:#00007f;\\\">Abusive Word Detection System</span></p></body></html>\"))\n self.lbl_wel.setText(_translate(\"DesignedWelWindow\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600; color:#740057;\\\">Welcome to Our ProjectWork ,Abusive Word Detection System!.</span></p></body></html>\"))\n self.btnOpenMainWindow.setText(_translate(\"DesignedWelWindow\", \"ACCESS PROJECT\"))\n\nimport newresourses\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n DesignedWelWindow = QtWidgets.QMainWindow()\n ui = Ui_DesignedWelWindow()\n ui.setupUi(DesignedWelWindow)\n DesignedWelWindow.show()\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.6614384055137634, "alphanum_fraction": 0.6924254298210144, "avg_line_length": 57.06666564941406, "blob_id": "64b2572f81216081dc073021c77e7590501763e2", "content_id": "722b6300f2de6e3e5c06d1fbd22b33b1c8529106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2614, "license_type": "no_license", "max_line_length": 303, "num_lines": 45, "path": "/DlogExtLink.py", "repo_name": "hillarry/sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'C:\\Users\\DELL\\Desktop\\finalGUI\\DlogExtLink.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_ExternalLinks(object):\n def setupUi(self, ExternalLinks):\n ExternalLinks.setObjectName(\"ExternalLinks\")\n ExternalLinks.resize(343, 313)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/imcon/link1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n ExternalLinks.setWindowIcon(icon)\n self.ExternalLinktextBrowser = QtWidgets.QTextBrowser(ExternalLinks)\n self.ExternalLinktextBrowser.setGeometry(QtCore.QRect(0, 0, 351, 321))\n self.ExternalLinktextBrowser.setObjectName(\"ExternalLinktextBrowser\")\n\n self.retranslateUi(ExternalLinks)\n QtCore.QMetaObject.connectSlotsByName(ExternalLinks)\n\n def retranslateUi(self, ExternalLinks):\n _translate = QtCore.QCoreApplication.translate\n ExternalLinks.setWindowTitle(_translate(\"ExternalLinks\", \"External Links\"))\n self.ExternalLinktextBrowser.setHtml(_translate(\"ExternalLinks\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p align=\\\"center\\\" style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:10pt; font-weight:600;\\\">External Links</span></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:10pt;\\\">- </span><a href=\\\"www.pyorg.com\\\"><span style=\\\" font-size:10pt; text-decoration: underline; color:#0000ff;\\\">Python</span></a></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:10pt;\\\">- </span><a href=\\\"www.pyqt.com\\\"><span style=\\\" font-size:10pt; text-decoration: underline; color:#0000ff;\\\">PyQt</span></a></p></body></html>\"))\n\nimport imicons\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n ExternalLinks = QtWidgets.QDialog()\n ui = Ui_ExternalLinks()\n ui.setupUi(ExternalLinks)\n ExternalLinks.show()\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.6244858503341675, "alphanum_fraction": 0.6644977927207947, "avg_line_length": 47.4420280456543, "blob_id": "7dac230cdbc8df0db904b9161b5483d063c92405", "content_id": "de693c88dac499fc4b7974ccc5e17d5755b26fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13371, "license_type": "no_license", "max_line_length": 232, "num_lines": 276, "path": "/DesignedHomeWin.py", "repo_name": "hillarry/sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'C:\\Users\\DELL\\Desktop\\finalGUI\\DesignedHomeWin.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nfrom DlogSysInfo import Ui_SystemInfo\nfrom DlogExtLink import Ui_ExternalLinks\nfrom DlogAbtUs import Ui_AboutUs\nfrom PyQt5.QtWidgets import QMessageBox\nimport prouitest\n\nclass Ui_HomeMainWindow(object):\n def openSysInfo(self):\n self.window = QtWidgets.QDialog()\n self.ui = Ui_SystemInfo()\n self.ui.setupUi(self.window)\n self.window.show()\n\n def openExternalLink(self):\n \n self.window = QtWidgets.QDialog()\n self.ui =Ui_ExternalLinks()\n self.ui.setupUi(self.window)\n self.window.show()\n\n def openAboutUs(self):\n \n self.window = QtWidgets.QDialog()\n self.ui = Ui_AboutUs()\n self.ui.setupUi(self.window)\n self.window.show()\n\n\n def setupUi(self, HomeMainWindow):\n HomeMainWindow.setObjectName(\"HomeMainWindow\")\n HomeMainWindow.resize(1041, 622)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\":/imcon/senti2.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n HomeMainWindow.setWindowIcon(icon)\n #HomeMainWindow.setStyleSheet(\"border-color: rgb(85, 0, 0);\\n\"\n#\"background-color: rgb(255, 246, 247);\\n\"\n#\"\")\n HomeMainWindow.setStyleSheet(\"background-color: qlineargradient(spread:pad, x1:0.068, y1:1, x2:0.113636, y2:0.807, stop:0.409091 rgba(221, 115, 106, 255), stop:1 rgba(255, 255, 255, 255));\")\n self.centralwidget = QtWidgets.QWidget(HomeMainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.lbl_Heading = QtWidgets.QLabel(self.centralwidget)\n self.lbl_Heading.setGeometry(QtCore.QRect(370, 40, 541, 51))\n font = QtGui.QFont()\n font.setFamily(\"MV Boli\")\n font.setPointSize(26)\n self.lbl_Heading.setFont(font)\n self.lbl_Heading.setObjectName(\"lbl_Heading\")\n self.lbl_MainIcon = QtWidgets.QLabel(self.centralwidget)\n self.lbl_MainIcon.setGeometry(QtCore.QRect(270, 0, 91, 81))\n self.lbl_MainIcon.setStyleSheet(\"image:url(:/imcon/classify1.png)\")\n self.lbl_MainIcon.setText(\"\")\n self.lbl_MainIcon.setObjectName(\"lbl_MainIcon\")\n self.label_entertext = QtWidgets.QLabel(self.centralwidget)\n self.label_entertext.setGeometry(QtCore.QRect(70, 190, 111, 21))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.label_entertext.setFont(font)\n self.label_entertext.setObjectName(\"label_entertext\")\n self.lineEdit_InputText = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit_InputText.setGeometry(QtCore.QRect(190, 180, 621, 41))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(12)\n self.lineEdit_InputText.setFont(font)\n self.lineEdit_InputText.setObjectName(\"lineEdit_InputText\")\n self.lineEdit_InputText.setPlaceholderText(\" Enter the text what you want to type \")\n self.btnAnalyze = QtWidgets.QPushButton(self.centralwidget)\n self.btnAnalyze.setGeometry(QtCore.QRect(840, 180, 111, 41))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(12)\n self.btnAnalyze.setFont(font)\n self.btnAnalyze.setStyleSheet(\"background-color: rgb(0, 255, 0);\\n\"\n\"border-color: rgb(239, 0, 0);\")\n self.btnAnalyze.clicked.connect(self.on_click)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\":/imcon/system2.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnAnalyze.setIcon(icon1)\n self.btnAnalyze.setObjectName(\"btnAnalyze\")\n self.lbl_Language = QtWidgets.QLabel(self.centralwidget)\n self.lbl_Language.setGeometry(QtCore.QRect(120, 310, 211, 31))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.lbl_Language.setFont(font)\n self.lbl_Language.setObjectName(\"lbl_Language\")\n self.label_sentiment = QtWidgets.QLabel(self.centralwidget)\n self.label_sentiment.setGeometry(QtCore.QRect(120, 400, 201, 41))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.label_sentiment.setFont(font)\n self.label_sentiment.setObjectName(\"label_sentiment\")\n self.label_classification = QtWidgets.QLabel(self.centralwidget)\n self.label_classification.setGeometry(QtCore.QRect(710, 310, 171, 31))\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.label_classification.setFont(font)\n self.label_classification.setObjectName(\"label_classification\")\n self.btnAbusive = QtWidgets.QPushButton(self.centralwidget)\n\n self.btnAbusive.setStyleSheet(\"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0.0340909 rgba(255, 97, 90, 255), stop:0.0511364 rgba(252, 63, 131, 14), stop:1 rgba(255, 36, 36, 228));\")\n\n\n \n self.btnAbusive.setGeometry(QtCore.QRect(610, 380, 161, 71))\n self.btnAbusive.setEnabled(False)\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.btnAbusive.setFont(font)\n## self.btnAbusive.setStyleSheet(\"color: rgb(255, 0, 0);\\n\"\n##\"gridline-color: rgb(193, 0, 0);\")\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(\":/imcon/Icon4.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnAbusive.setIcon(icon2)\n self.btnAbusive.setObjectName(\"btnAbusive\")\n \n self.btnNonAbusive = QtWidgets.QPushButton(self.centralwidget)\n\n self.btnNonAbusive.setStyleSheet(\"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0.0340909 rgba(0, 207, 0, 255), stop:0.0511364 rgba(252, 63, 131, 14), stop:0.426136 rgba(16, 203, 4, 221));\")\n \n \n self.btnNonAbusive.setGeometry(QtCore.QRect(790, 380, 161, 71))\n self.btnNonAbusive.setEnabled(False)\n \n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n font.setPointSize(14)\n self.btnNonAbusive.setFont(font)\n## self.btnNonAbusive.setStyleSheet(\"color: rgb(0, 150, 0);\\n\"\n##\"gridline-color: rgb(0, 166, 0);\")\n icon3 = QtGui.QIcon()\n icon3.addPixmap(QtGui.QPixmap(\":/imcon/Icon3.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnNonAbusive.setIcon(icon3)\n self.btnNonAbusive.setObjectName(\"btnNonAbusive\")\n HomeMainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(HomeMainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1041, 21))\n self.menubar.setObjectName(\"menubar\")\n self.menuAbout = QtWidgets.QMenu(self.menubar)\n self.menuAbout.setObjectName(\"menuAbout\")\n HomeMainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(HomeMainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n HomeMainWindow.setStatusBar(self.statusbar)\n self.actionSystem_Info = QtWidgets.QAction(HomeMainWindow)\n icon4 = QtGui.QIcon()\n icon4.addPixmap(QtGui.QPixmap(\":/imcon/SysInfo1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionSystem_Info.setIcon(icon4)\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n self.actionSystem_Info.setFont(font)\n self.actionSystem_Info.setObjectName(\"actionSystem_Info\")\n \n #open System Info Dialog\n self.actionSystem_Info.triggered.connect(self.openSysInfo)\n \n self.actionExternal_Link = QtWidgets.QAction(HomeMainWindow)\n icon5 = QtGui.QIcon()\n icon5.addPixmap(QtGui.QPixmap(\":/imcon/link3.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionExternal_Link.setIcon(icon5)\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n self.actionExternal_Link.setFont(font)\n self.actionExternal_Link.setObjectName(\"actionExternal_Link\")\n\n #open External Links Dialog\n self.actionExternal_Link.triggered.connect(self.openExternalLink)\n \n self.actionAbout_Us = QtWidgets.QAction(HomeMainWindow)\n icon6 = QtGui.QIcon()\n icon6.addPixmap(QtGui.QPixmap(\":/imcon/about2.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.actionAbout_Us.setIcon(icon6)\n font = QtGui.QFont()\n font.setFamily(\"Courier New\")\n self.actionAbout_Us.setFont(font)\n self.actionAbout_Us.setObjectName(\"actionAbout_Us\")\n\n #open About Us Dialog\n self.actionAbout_Us.triggered.connect(self.openAboutUs)\n \n self.menuAbout.addAction(self.actionSystem_Info)\n self.menuAbout.addAction(self.actionExternal_Link)\n self.menuAbout.addAction(self.actionAbout_Us)\n self.menubar.addAction(self.menuAbout.menuAction())\n\n self.retranslateUi(HomeMainWindow)\n self.btnAnalyze.clicked.connect(self.lineEdit_InputText.clear)\n QtCore.QMetaObject.connectSlotsByName(HomeMainWindow)\n\n def retranslateUi(self, HomeMainWindow):\n _translate = QtCore.QCoreApplication.translate\n HomeMainWindow.setWindowTitle(_translate(\"HomeMainWindow\", \"Abusive Word Detection System\"))\n self.lbl_Heading.setText(_translate(\"HomeMainWindow\", \"<html><head/><body><p><span style=\\\" color:#55007f;\\\">Abusive Word Detection System</span></p></body></html>\"))\n self.label_entertext.setText(_translate(\"HomeMainWindow\", \"Enter Text\"))\n self.btnAnalyze.setText(_translate(\"HomeMainWindow\", \"Analyze\"))\n self.lbl_Language.setText(_translate(\"HomeMainWindow\", \"<html><head/><body><p><span style=\\\" color:#47006b;\\\">Language:</span><span style=\\\" color:#00b900;\\\">English</span></p></body></html>\"))\n self.label_sentiment.setText(_translate(\"HomeMainWindow\", \"<html><head/><body><p><span style=\\\" color:#3e005d;\\\">Accuracy:</span></p></body></html>\"))\n self.label_classification.setText(_translate(\"HomeMainWindow\", \"<html><head/><body><p><span style=\\\" color:#55007f;\\\">Classification</span></p></body></html>\"))\n self.btnAbusive.setText(_translate(\"HomeMainWindow\", \"Abusive\"))\n self.btnNonAbusive.setText(_translate(\"HomeMainWindow\", \"NonAbusive\"))\n self.menuAbout.setTitle(_translate(\"HomeMainWindow\", \"About\"))\n self.actionSystem_Info.setText(_translate(\"HomeMainWindow\", \"System Info\"))\n self.actionExternal_Link.setText(_translate(\"HomeMainWindow\", \"External Link\"))\n self.actionAbout_Us.setText(_translate(\"HomeMainWindow\", \"About Us\"))\n #self.actionAbout_Us.setShortcut(_translate(\"HomeMainWindow\", \"Ctrl+U\"))\n def on_click(self):\n text_input=self.lineEdit_InputText.text()\n x=str(text_input)\n command=prouitest.testing(x)\n self.label_sentiment.setText(\"<html><head/><body><p><span style=\\\" color:#3e005d;\\\">Accuracy:85.88%</span></p></body></html>\") \n if command==1:\n #self.btnAnalyze.clicked.connect(self.show_popup)\n #self.btnAnalyze.clicked.connect(\n self.btnAbusive.setEnabled(True)\n\n #self.btnAbusive.setStyleSheet(\"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0.0340909 rgba(255, 97, 90, 255), stop:0.0511364 rgba(252, 63, 131, 14), stop:1 rgba(255, 36, 36, 228));\")\n\n QMessageBox.warning(QMessageBox(),\"Warning\",\"We can't allow your abusive message\")\n self.btnAbusive.setEnabled(False)\n \n #self.btnAbusive.setEnabled(True)\n #self.btnAbusive.clicked.connect(self.show_popup)\n elif command==0:\n \n #self.btnAnalyze.clicked.connect(self.show)\n self.btnNonAbusive.setEnabled(True)\n\n #self.btnNonAbusive.setStyleSheet(\"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0.0340909 rgba(0, 207, 0, 255), stop:0.0511364 rgba(252, 63, 131, 14), stop:0.585227 rgba(16, 203, 4, 221));\")\n \n QMessageBox.information(QMessageBox(),\"Allow\",\"We allow your message\")\n \n self.btnNonAbusive.setEnabled(False)\n #self.btnNonAbusive.clicked.connect(self.show)\n #self.label_sentiment.setText(\"<html><head/><body><p><span style=\\\" color:#3e005d;\\\">Accuracy:85.88%</span></p></body></html>\") \n \n '''def show_popup(self):\n msg=QMessageBox()\n msg.setWindowTitle(\"Warning!\")\n msg.setIcon(QtWidgets.QMessageBox.Warning)\n msg.setText(\"Your sentence has abusive words.We can't allow your message.\")\n x=msg.exec_()\n self.btnAbusive.setEnabled(False)'''\n \n '''def show(self):\n msg=QMessageBox()\n msg.setWindowTitle(\"Allow\")\n msg.setIcon(QtWidgets.QMessageBox.Information)\n msg.setText(\"Your message has no abusive words.We can allow your message.\")\n x=msg.exec_()\n self.btnNonAbusive.setEnabled(False)'''\n\n \nimport newresourses\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n HomeMainWindow = QtWidgets.QMainWindow()\n ui = Ui_HomeMainWindow()\n ui.setupUi(HomeMainWindow)\n HomeMainWindow.show()\n sys.exit(app.exec_())\n\n" } ]
5
vickyleon/APTManualUsuario
https://github.com/vickyleon/APTManualUsuario
d0dbe977f10c4efcf704923e7b4e05e687115df8
563c7462f24dbabf582723398e1361762ee9c223
f9f8751bbdeb2de7432d6affcd6ea3c87d05a23d
refs/heads/master
2021-05-11T04:02:06.324828
2018-01-20T05:01:37
2018-01-20T05:01:37
117,930,557
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5509419441223145, "alphanum_fraction": 0.5517109036445618, "avg_line_length": 25.81443214416504, "blob_id": "24fb125c19146497c2f1689f5946ce82e804d24a", "content_id": "e29ac9e028bdd13d847f39bfb6d69740db55d380", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2602, "license_type": "permissive", "max_line_length": 87, "num_lines": 97, "path": "/public_html/app/Controller.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": " <?php\n \tclass Controller{\n\t\tpublic function inicio(){\n\t\t\t$params = array(\n\t\t\t\t'mensaje' => 'Bienvenido al curso de symfony 1.4',\n\t\t\t\t'fecha' => date('d-m-yyy')\n\t\t\t\t);\n require __DIR__ . '/templates/inicio.php';\n \t}\n\t\t\n\t\tpublic function eventos(){\n\t\t\trequire __DIR__ . '/templates/eventos.php';\n \t}\n\t\t\n\t\tpublic function normas(){\n\t\t\trequire __DIR__ . '/templates/normatividad.php';\n \t}\n\t\t\n\t\tpublic function mostrarBoletines(){\n\t\t\trequire __DIR__ . '/templates/boletin.php';\n \t}\n public function materialDidactico(){\n require __DIR__ . '/templates/mdidactico.php';\n }\n\t\t\n\t\t/*public function listar(){\n\t\t\t$m = new Model(Config::$mvc_bd_nombre, Config::$mvc_bd_usuario,\n\t\t\t\tConfig::$mvc_bd_clave, Config::$mvc_bd_hostname);\n\t\t\t\n\t\t\t$params = array(\n\t\t\t\t'alimentos' => $m->dameAlimentos()\n\t\t\t);\n\t\t\t\n\t\t\trequire __DIR__ . '/templates/mostrarAlimentos.php';\n\t\t}\n\t\t\n\t\tpublic function insertarIns(){\n\t\t\t$params = array(\n\t\t\t\t'nombre' => '',\n 'siglas' => ''\n\t\t\t);\n\t\t\t\n\t\t\t$m = new Model(Config::$mvc_bd_nombre, Config::$mvc_bd_usuario,\n\t\t\t\t\t\tConfig::$mvc_bd_clave, Config::$mvc_bd_hostname);\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t// comprobar campos formulario\n\t\t\t\tif ($m->validarDatos($_POST['nombre'], $_POST['siglas'])){\n\t\t\t\t\t$m->insertarIns($_POST['nombre'], $_POST['siglas']);\n\t\t\t\t\t//header('Location: index.php?ctl=listar');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$params = array(\n\t\t\t\t\t\t'nombre' => $_POST['nombre'],\n \t'siglas' => $_POST['siglas']\n\t\t\t\t\t);\n\t\t\t\t\t$params['mensaje'] = 'No se ha podido insertar el alimento. Revisa el formulario';\n\t\t\t\t}\n\t\t\t}\n\t\t\trequire __DIR__ . '/templates/formInsertarInstitucion.php';\n\t\t}\n\t\t\n\t\tpublic function buscar(){\n\t\t\t$params = array(\n\t\t\t\t'nombre' => '',\n\t\t\t\t'resultado' => array()\n\t\t\t);\n\t\t\t\n\t\t\t$m = new Model(Config::$mvc_bd_nombre, Config::$mvc_bd_usuario,\n Config::$mvc_bd_clave, Config::$mvc_bd_hostname);\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST'){\n\t\t\t\t$params['nombre'] = $_POST['nombre'];\n\t\t\t\t$params['resultado'] = $m->buscarAlimentosPorNombre($_POST['nombre']);\n\t\t\t}\n\t\t\t\n\t\t\trequire __DIR__ . '/templates/buscarPorNombre.php';\n\t\t}\n\t\t\n\t\tpublic function ver(){\n\t\t\tif (!isset($_GET['id'])) {\n\t\t\t\tthrow new Exception('Página no encontrada');\n\t\t\t}\n\t\t\t\n\t\t\t$id = $_GET['id'];\n\t\t\t\n\t\t\t$m = new Model(Config::$mvc_bd_nombre, Config::$mvc_bd_usuario,\n Config::$mvc_bd_clave, Config::$mvc_bd_hostname);\n\t\t\t\t\t \n\t\t\t$alimento = $m->dameAlimento($id);\n\t\t\t\n\t\t\t$params = $alimento;\n\t\t\t\n\t\t\trequire __DIR__ . '/templates/verAlimento.php';\n\t\t}*/\n\t}\n?>" }, { "alpha_fraction": 0.49776387214660645, "alphanum_fraction": 0.5090936422348022, "avg_line_length": 27.299577713012695, "blob_id": "3d96a8dc4035823966b1ede55473b9f644fd07e7", "content_id": "ecbf1158ba77b52699a7380b485d4fc74daddf6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 13423, "license_type": "permissive", "max_line_length": 208, "num_lines": 474, "path": "/administracionEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nsession_start();\nif($_SESSION[\"acceso\"][5]==1 || $_SESSION[\"acceso\"][5]==2 || $_SESSION[\"acceso\"][5]==3 || $_SESSION[\"acceso\"][5]==4){\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n$sql=\"select distinct idpregunta from respuestaprofesor order by idpregunta;\";\n$result=mysqli_query($conexion,$sql);\n\n//obtengo el numero de profesores que contestaron la encuesta\n\n$sql2=\"select distinct id from respuestaprofesor;\";\n$result2=mysqli_query($conexion,$sql2);\n//genero n resulsets\n\n\n$profes=0;\necho $profes;\n?>\n\n\n<span style=\"font-style:italic;\"><!doctype html>\n\t<html lang=\"es\">\n\t\t<style>\n\t\t\tcanvas {\n\t\t\t\t-moz-user-select: none;\n\t\t\t\t-webkit-user-select: none;\n\t\t\t\t-ms-user-select: none;\n\t\t\t}\n\t\t</style>\n\t\t<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n\t\t<head>\n\t\t\t<?php require_once(\"controlador/verificar.php\");\n\t\t\trequire_once(\"controlador/connection.php\");\n\t\t\t?>\n\t\t\t<meta charset=\"utf-8\">\n\n\n\t\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\n\t\t\t<script src=\"js/utils.js\"></script>\n\t\t\t<script src=\"js/Chart.bundle.js\"></script>\n\n\t\t\t<script\n\t\t\t\t\tsrc=\"https://code.jquery.com/jquery-3.2.1.min.js\"\n\t\t\t\t\tintegrity=\"sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=\"\n\t\t\t\t\tcrossorigin=\"anonymous\"></script>\n\t\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t\t\t<!-- links-->\n\t\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n\t\t\t<title>Grupo de investigación en la enseñanza de física</title>\n\t\t</head>\n\t\t<script>\n\t\t\t$(document).ready(function() {\n\n\t\t\t\tvar divOne = document.getElementById('btn1');\n\t\t\t\tdivOne.style.visibility = 'hidden';\n\t\t\t\tvar divOnes = document.getElementById('btn2');\n\t\t\t\tdivOnes.style.visibility = 'hidden';\n\t\t\t\t$('.modal').modal();\n\t\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t\t// Initialize collapsible (uncomment the line below if you use the dropdown variation)\n\t\t\t\t$('.collapsible').collapsible();\n\t\t\t\t$('select').material_select();\n\n\t\t\t\t$(function () {\n\t\t\t\t\t$(\"#desp1\").change(function () {\n\t\t\t\t\t\t//$(\"#segundo\").html(\"cambioo\");\n\t\t\t\t\t\t//alert(\"change\");\n\t\t\t\t\t\t//alert($(\"#desp1\").serialize());\n\t\t\t\t\t\tvar x=\"seleccion=1\";\n\t\t\t\t\t\tvar w=\"seleccion=2\";\n\t\t\t\t\t\tvar y=$(\"#desp1\").serialize();\n\t\t\t\t\t\tif(x.localeCompare(y)==0){\n\n\n\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\ttype: \"post\",\n\t\t\t\t\t\t\t\turl: \"ObtieneProfesores.php\",\n\t\t\t\t\t\t\t\tdata: $(\"#desp1\").serialize(),\n\t\t\t\t\t\t\t\tsuccess: function(r) {\n\n\t\t\t\t\t\t\t\t\tvar resp=$.parseJSON(r);\n\t\t\t\t\t\t\t\t\t//alert(resp.length);\n\t\t\t\t\t\t\t\t\tvar boxe = \"\";\n\t\t\t\t\t\t\t\t\tboxe='<form action=\"\" id=\"desp2\"><div class=\"input-field col s12\"><select class=\"select-dropdown\" id=\"seleccion2\" name=\"seleccion2\"><option value=\"\" disabled selected>Seleccionar profesor</option>';\n\n\t\t\t\t\t\t\t\t\tfor (i = 0; i < resp.length; i++) {\n\t\t\t\t\t\t\t\t\t\t//alert(boxe);\n\t\t\t\t\t\t\t\t\t\tboxe+='<option value=\"'+resp[i].ID+'\">'+resp[i].ApPaterno+' '+resp[i].ApMaterno+' '+resp[i].Nombre+'</option>';\t\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tboxe+=\"</select></div></form>\";\n\t\t\t\t\t\t\t\t\t$(\"#segundo\").html(boxe);\n\t\t\t\t\t\t\t\t\tdivOne.style.visibility = 'visible';\n\n\t\t\t\t\t\t\t\t\t/*if (resp == 1) {\n\t\t\t\t\t\t\t\t\t$('#modal1').openModal();\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\talert(resp);\n\t\t\t\t\t\t\t\t\t$('#modal2').openModal();\n\n\t\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(w.localeCompare(y)==0){\n\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\ttype: \"post\",\n\t\t\t\t\t\t\t\turl: \"ObtieneNum.php\",\n\t\t\t\t\t\t\t\tdata: $(\"#desp1\").serialize(),\n\t\t\t\t\t\t\t\tsuccess: function(r) {\n\n\t\t\t\t\t\t\t\t\tvar resp=$.parseJSON(r);\n\t\t\t\t\t\t\t\t\t//alert(resp.length);\n\t\t\t\t\t\t\t\t\tvar boxe = \"\";\n\t\t\t\t\t\t\t\t\tboxe='<form action=\"\" id=\"desp2\"><div class=\"input-field col s12\"><select id=\"seleccion2\" name=\"seleccion2\"><option value=\"\" disabled selected>Seleccionar pregunta</option>';\n\n\t\t\t\t\t\t\t\t\tfor (i = 0; i < resp.length; i++) {\n\t\t\t\t\t\t\t\t\t\t//alert(boxe);\n\t\t\t\t\t\t\t\t\t\tboxe+='<option value=\"'+resp[i].IDPregunta+'\">Pregunta '+resp[i].IDPregunta+'</option>';\t\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tboxe+=\"</select></div></form>\";\n\t\t\t\t\t\t\t\t\t$(\"#segundo\").html(boxe);\n\t\t\t\t\t\t\t\t\tdivOnes.style.visibility = 'visible';\n\n\t\t\t\t\t\t\t\t\t/*if (resp == 1) {\n\t\t\t\t\t\t\t\t\t$('#modal1').openModal();\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\talert(resp);\n\t\t\t\t\t\t\t\t\t$('#modal2').openModal();\n\n\t\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t$(\"#tercero\").html(\"\");\n\t\t\t\t\t\t\tvar ctx = document.getElementById(\"canvas\");\n\t\t\t\t\t\t\tvar MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\t\t\t\t\t\t\tvar color = Chart.helpers.color;\n\t\t\t\t\t\t\t/*var barChart = new Chart(ctx, {\n\t\t\t\ttype: 'bar',\n\t\t\t\tdata: {\n\t\t\t\t\tlabels: [\"Dog\", \"Cat\", \"Pangolin\"],\n\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\tbackgroundColor: '#00ff00',\n\t\t\t\t\t\tlabel: '# of Votes 2016',\n\t\t\t\t\t\tdata: [12, 19, 3]\n\t\t\t\t\t}]\n\t\t\t\t}\n\t\t\t});*/\n\t\t\t\t\t\t\tvar barChartData = new Chart(ctx, {\n\t\t\t\t\t\t\t\ttype:'bar',\n\t\t\t\t\t\t\t\tdata:{\n\t\t\t\t\t\t\t\t\tlabels: [\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\twhile($registros=mysqli_fetch_array($result)){\n\t\t\t\t\t\t\t\t\t\t?>\n\n\t\t\t\t\t\t\t\t\t\t'<?php echo $registros[0]; ?>',\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\t\t\t\t\tlabel: 'Dataset 1',\n\t\t\t\t\t\t\t\t\t\tbackgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),\n\t\t\t\t\t\t\t\t\t\tborderColor: window.chartColors.red,\n\t\t\t\t\t\t\t\t\t\tborderWidth: 1,\n\t\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t\t0,0\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t}]\n\n\t\t\t\t\t\t\t\t}});\n\n\t\t\t\t\t\t\t//un data set por cada profesor, cada dataset tiene las respuestas por pregunta\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\twhile($registros2=mysqli_fetch_array($result2)){\n\t\t\t\t\t\t\t\t//ahora obtengo las respuestas\n\t\t\t\t\t\t\t\t$sql3=\"select rango from respuestaprofesor where id=\".$registros2[\"id\"].\" order by idpregunta;\";\n\t\t\t\t\t\t\t\t//echo $sql3;\n\t\t\t\t\t\t\t\t$result3=mysqli_query($conexion,$sql3);\n\t\t\t\t\t\t\t\t$sql4=\"select ApPaterno, ApMaterno, Nombre from usuario where id=\".$registros2[\"id\"].\";\";\n\t\t\t\t\t\t\t\t$result4=mysqli_query($conexion,$sql4);\n\t\t\t\t\t\t\t\twhile($registros4=mysqli_fetch_array($result4)){\n\t\t\t\t\t\t\t\t\t$nombre=$registros4[\"ApPaterno\"].\" \".$registros4[\"ApMaterno\"].\" \".$registros4[\"Nombre\"];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\n\t\t\t\t\t\t\taddData(barChartData,'<?php echo $nombre; ?>', '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6), [\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\twhile($registro3=mysqli_fetch_array($result3)){\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t<?php echo $registro3[\"rango\"]?>,\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t]);\n\n\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\n\n\n\n\t\t\t\t\t\t\twindow.onload = function() {\n\t\t\t\t\t\t\t\tvar ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n\t\t\t\t\t\t\t\twindow.myBar = new Chart(ctx, {\n\t\t\t\t\t\t\t\t\ttype: 'bar',\n\t\t\t\t\t\t\t\t\tdata: barChartData,\n\t\t\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\t\t\tresponsive: true,\n\t\t\t\t\t\t\t\t\t\tlegend: {\n\t\t\t\t\t\t\t\t\t\t\tposition: 'top',\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttitle: {\n\t\t\t\t\t\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\t\t\t\t\t\ttext: 'Chart.js Bar Chart'\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tdocument.getElementById('randomizeData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tvar zero = Math.random() < 0.2 ? true : false;\n\t\t\t\t\t\t\t\tbarChartData.datasets.forEach(function(dataset) {\n\t\t\t\t\t\t\t\t\tdataset.data = dataset.data.map(function() {\n\t\t\t\t\t\t\t\t\t\treturn zero ? 0.0 : randomScalingFactor();\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tvar colorNames = Object.keys(window.chartColors);\n\n\n\t\t\t\t\t\t\tdocument.getElementById('addData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tif (barChartData.datasets.length > 0) {\n\t\t\t\t\t\t\t\t\tvar month = MONTHS[barChartData.labels.length % MONTHS.length];\n\t\t\t\t\t\t\t\t\tbarChartData.labels.push(month);\n\n\t\t\t\t\t\t\t\t\tfor (var index = 0; index < barChartData.datasets.length; ++index) {\n\t\t\t\t\t\t\t\t\t\t//window.myBar.addData(randomScalingFactor(), index);\n\t\t\t\t\t\t\t\t\t\tbarChartData.datasets[index].data.push(randomScalingFactor());\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tdocument.getElementById('removeDataset').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tbarChartData.datasets.splice(0, 1);\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tdocument.getElementById('removeData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tbarChartData.labels.splice(-1, 1); // remove the label first\n\n\t\t\t\t\t\t\t\tbarChartData.datasets.forEach(function(dataset, datasetIndex) {\n\t\t\t\t\t\t\t\t\tdataset.data.pop();\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tfunction addData(chart, label, color, data) {\n\t\t\t\t\t\t\t\tchart.data.datasets.push({\n\t\t\t\t\t\t\t\t\tlabel: label,\n\t\t\t\t\t\t\t\t\tbackgroundColor: color,\n\t\t\t\t\t\t\t\t\tdata: data\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tchart.update();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\n\t\t\t\t});\n\n\n\n\t\t\t});\n\n\n\t\t</script>\n\n\t\t<body>\n\n\t\t\t<?php\n\t\t\tinclude (\"barra.html\");\n\t\t\t?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"encabezados\" -->\n\t\t\t<div id='banner'>\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<header>\n\t\t\t\t\t\t<div class=\"col s12 m5 l6\">\n\t\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t\t<h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n\t\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"col s12 m6 l6\">\n\t\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</header>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\n\n\n\t\t\t<?php \n\t\t\tinclude(\"minibarra.php\");\n\t\t\t?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"content\" -->\n\t\t\t<div class=\"container\">\n\n\t\t\t\t<form action=\"\" id=\"desp1\">\n\n\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t<select id=\"seleccion\" name=\"seleccion\">\n\t\t\t\t\t\t\t<option value=\"\" disabled selected>Ver datos:</option>\n\t\t\t\t\t\t\t<option value=\"1\">Por profesor</option>\n\t\t\t\t\t\t\t<option value=\"2\">Por pregunta</option>\n\t\t\t\t\t\t\t<option value=\"3\">Ver todo</option>\n\t\t\t\t\t\t\t<option value=\"4\">Opiniones del cuestionario</option>\n\t\t\t\t\t\t</select>\n\n\t\t\t\t\t</div>\n\t\t\t\t</form>\n\n\t\t\t\t<div id=\"segundo\">\n\n\t\t\t\t</div>\n\t\t\t\t<p><a class='waves-effect waves-light btn' id='btn1'>Consultar profesor</a>\n\t\t\t\t<p><a class='waves-effect waves-light btn' id='btn2'>Consultar pregunta</a>\n\t\t\t\t\t<!--inicio-->\n\t\t\t\t<div id=\"container\" style=\"width: 75%;\">\n\t\t\t\t\t<canvas id=\"canvas\" ></canvas>\n\t\t\t\t</div>\n\t\t\t\t\n <!--tabla de comentarios generales-->\n <ul class=\"collapsible\" data-collapsible=\"accordion\">\n <li>\n <div class=\"collapsible-header\">\n <i class=\"material-icons\">filter_drama</i>\n Nombre \n </div>\n <div class=\"collapsible-body\">\n <table class=\"highlight\">\n \n <tr>\n <th>Tamaño letra e imagenes</th>\n <td>cool</td>\n </tr>\n <tr>\n <th>Redacción de la pregunta</th>\n <td>cool</td>\n </tr>\n <tr>\n <th>Distractores</th>\n <td>cool</td>\n </tr>\n <tr>\n <th>Dificultad</th>\n <td>cool</td>\n </tr>\n <tr>\n <th>Tiempo Estimado</th>\n <td>coll</td>\n </tr>\n <tr>\n <th>Otro Comentario</th>\n <td>nel</td>\n </tr>\n \n </table>\n\t\t\t\t\n </div>\n </li>\n\n </ul>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<a class=\"waves-effect waves-light btn-large offset-s5 col s2\" id=\"btnback\">Volver</a>\n\t\t\t\t</div>\n\t\t\t\t<br>\n\t\t\t\t<br>\n\t\t\t\n\n\t\t\t<!--fin-->\n\n\t\t\t</div>\n\t\t<footer>\n\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t<br>\n\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t<br>\n\t\t</footer>\n\t\t</body>\n\t<script>\n\t\t$(\"#btn1\").click(function(e) {\n\t\t\t//alert($(\"#desp2\").serialize());\n\n\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/asignaCuadro.php\",\n\t\t\t\tdata: $(\"#desp2\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\t\t\t\t\twindow.location.replace(\"datos.php\");\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t});\n\n\t\t$(\"#btn2\").click(function(e) {\n\t\t\t//alert($(\"#desp2\").serialize());\n\n\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/asignaCuadro.php\",\n\t\t\t\tdata: $(\"#desp2\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\t\t\t\t\twindow.location.replace(\"datos2.php\");\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t});\n\t\t$(\"#btnback\").click(function(e) {\n\t\t\t\t//alert($(\"#desp2\").serialize());\n\t\t\t\twindow.location.replace(\"EncuestaPiloto.php\");\n\t\t\t\t\n\n\t\t\t});\n\t</script>\n\t<!-- InstanceEnd -->\n\n\t</html>\n\t<?php\n\t }\n else{\n echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n }\n\t?>\n</span>\n\n\n" }, { "alpha_fraction": 0.4324324429035187, "alphanum_fraction": 0.4445340931415558, "avg_line_length": 44.27853775024414, "blob_id": "99d945a0ccd92ca8f26204a53d3c209884cc5cd0", "content_id": "c9d62751cf49a7b02b15a84c0cbf7bef11d33a76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9932, "license_type": "permissive", "max_line_length": 200, "num_lines": 219, "path": "/administrador.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html lang=\"es\"><!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\"> \n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\n $('.datepicker').pickadate({\n selectMonths: true, // Creates a dropdown to control month\n selectYears: 15 // Creates a dropdown of 15 years to control year\n });\n $('select').material_select();\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n });\n\n </script>\n\n\n <body>\n\n <?php\n include(\"barra.html\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"encabezados\" --> \n <!-- InstanceBeginEditable name=\"encabezados\" --> \n <div id='banner'>\n <div class=\"row\"> \n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\">Sistema 4MAT</h2> \n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\"/>\n </div>\n </header>\n </div>\n </div>\n\n\n\n\n <?php \n include(\"minibarra.php\");\n ?>\n \n <!-- InstanceBeginEditable name=\"content\" -->\n <?php \n require_once(\"controlador/busqueda.php\"); \n esAdministrador();//Si es un administrador lo dejamos aqui sino no puede estar en esta pagina\t\n ?>\n <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\n\n\n <div class=\"contenido\">\n <article> \t\n <h4>Panel de visualización de resultados</h4>\n <p> En esta sección encontrarás información acerca de las personas que han contestado el cuestionario, ya que podrás hacer búsquedas <strong></strong>empleando diversos parámetros.</p>\n <hr color=\"#70ce24\">\n </article>\n <article>\n\n <form name=\"busqueda\" method=\"post\" action=\"#resultados\">\n <div class=row>\n \n \n <div class=\"col s12 m12 l6\">\n <br>\n <input type=\"search\" name=\"txtBuscar\" placeholder=\"Buscar por nombre o institución\">\n </div>\n <div class=cuest>Rango de fechas en que se contestó el cuestionario.</div>\n <div class=\"col s12 m10 l2\">\n \n <input type=\"date\" class=\"datepicker\" name=\"fechaCuest1\">\n \n </div>\n <div class=\"col s12 m10 l2\">\n <input type=\"date\" class=\"datepicker\" name=\"fechaCuest2\">\n </div>\n \n <div class=\"input-field col s12 m10 l3\">\n <select name=\"idCuest\" style=\"display:none;\">\n <option value=\"1\" selected>Cuestionario</option>\n \n\t\t\t\t <option value=\"1\">Estilos de Aprendizaje</option>\n\t\t\t\t <option value=\"2\">Estilos de Enseñanza</option>\n <option value=\"1\">Conocimientos Historicos de Ciencia </option> \n\t\t\t\t </select>\n <label >Cuestionario</label>\n </div>\n <div class=\" input-field col s12 m10 l3\">\n <select name=\"ocupacion\" style=\"display:none;\">\n <option value=\"A\">Todas las ocupaciones</option>\n <option value=\"Estudiante\">Estudiante</option>\n <option value=\"Egresado\">Egresado</option>\n <option value=\"Profesor\">Profesor</option>\n </select>\n </div>\n \n <div class=\"col s12 m12 l5\"> Rango de fechas de nacimiento. </div>\n <div class=\"col s12 m10 l2\">\n \n <input type=\"date\" class=\"datepicker\" name=\"fechaCuest1\">\n \n </div>\n <div class=\"col s12 m10 l2\">\n <input type=\"date\" class=\"datepicker\" name=\"fechaCuest2\">\n </div>\n \n <div class=\"col s12 m10 l5\">\n Genero:\n <br> \n <input name=\"sexo\" value=\"M\" type=\"checkbox\" id=\"test5\" > \n <label for=\"test5\">Masculino</label>\n <input name=\"sexo\" value=\"F\" type=\"checkbox\" id=\"test6\" > \n <label for=\"test6\">Femenino</label>\n <input type=\"checkbox\" id=\"test7\" name=\"sexo\" value=\"A\" checked>\n <label for=\"test7\">Ambos</label> \n </div> \n \n <div class=\"col s12 m10 l5\">\n <input name=\"btnBuscar\" type=\"submit\" class=\"btn\" value=\"Buscar\">\n <input name=\"btnALL\" type=\"submit\" class=\"btn\" value=\"Mostrar todo\">\n </div> \n \n \n \n </div>\n </form>\n \n </article>\n </div>\n\n <article>\n \n <a name=\"resultados\"></a>\n <?php \n $busqueda = new Busqueda();\n $busqueda->principal();\n $_SESSION['numEstudiantes'] = $busqueda->getCoincidecias(\"Estudiante\");\n $_SESSION['numEgresados'] = $busqueda->getCoincidecias(\"Egresado\");\n $_SESSION['numProfesores'] = $busqueda->getCoincidecias(\"Profesor\");\n ?>\t\n \t\t\n </article>\n \n <!-- Graficas -->\n <!--Load the AJAX API-->\n <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n <script type=\"text/javascript\">\n\n // Load the Visualization API and the piechart package.\n google.load('visualization', '1.0', {'packages':['corechart']});\n\n // Set a callback to run when the Google Visualization API is loaded.\n google.setOnLoadCallback(drawChart);\n \n // Callback that creates and populates a data table,\n // instantiates the pie chart, passes in the data and\n // draws it.\n function drawChart() {\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows([\n ['Estudiante', <?php if(isset($_SESSION['numEstudiantes'])) echo $_SESSION['numEstudiantes']; else echo \"0\"; ?>],\n ['Egresado', <?php if(isset($_SESSION['numEgresados'])) echo $_SESSION['numEgresados']; else echo \"0\"; ?>],\n ['Profesor', <?php if(isset($_SESSION['numProfesores'])) echo $_SESSION['numProfesores']; else echo \"0\"; ?>]\n ]);\n\n // Set chart options\n var options = {'title':'Ocupación',\n 'width':'100%',\n 'height':'100%'};\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }\n </script>\n \n <div class=\"row\">\n <div class=\"col s12 m10 l5\">\n <div id=\"chart_div\"></div>\n </div>\n </div>\n \n \n <!-- InstanceEndEditable -->\n <footer> \n <!--Aqui va el pie de pagina-->\n <br><p>2017 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos BEIFI</p><br>\n </footer> \t \t\n </body>\n <!-- InstanceEnd --></html>\n" }, { "alpha_fraction": 0.626086950302124, "alphanum_fraction": 0.6275362372398376, "avg_line_length": 27.77083396911621, "blob_id": "b2cc45f46e507e3f1e06ffceeb39c12b62c1f738", "content_id": "7e2f539a1b8eef2d8b71bacf8c94841083e710c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1380, "license_type": "permissive", "max_line_length": 111, "num_lines": 48, "path": "/public_html/app/controlador/ControladorInstitucion.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ControladorInstitucion{\n\t\tpublic function registroInstitucion($dir){\n\t\t\t$parametros = array(\n\t\t\t\t\n\t\t\t);\n\t\t\t\n\t\t\t$modelo = new ModeloInstitucion();\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t//Creacion del beanInstitucion\n\t\t\t\t$ins = new Institucion(0, htmlspecialchars($_POST['txtInst']),htmlspecialchars($_POST['txtSiglas']));\n\t\t\t\t\n\t\t\t\t//Validar datos\n\t\t\t\tif($modelo->validarDatos($ins)){\n\t\t\t\t\t$modelo->insertar($ins);\n\t\t\t\t\t$ins->setIdInstitucion($modelo->buscarPorNombre($ins->getNombre(), $ins->getSiglas()));\n\n\t\t\t\t\t$url = 'index.php?ctl=registroEsc&mem='.$_POST['mem'].'&idIns='.$ins->getIdInstitucion().'#RegistroP3Esc';\n\t\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t//require $dir.'/app/templates/fomRegistroIns.php';\n\t\t\trequire $dir.'/app/templates/inicio.php';\n\t\t}\n\t\t\n\t\tpublic function mostrarInstitucion($dir){\n\t\t\t$modelo = new ModeloInstitucion();\n\t\t\t$busqueda = '';\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t//Se recupera el parametro de la busqueda\n\t\t\t\t$busqueda = $_POST['txtBuscar'];\n\t\t\t}\n\t\t\t\n\t\t\t$parametros = array(\n\t\t\t\t'instituciones' => $modelo->getInstituciones($busqueda)\n\t\t\t);\n\t\t\t\n\t\t\t//require $dir.'/app/templates/formBuscarInst.php';\n\t\t\t//require $dir.'/app/templates/mostrarInstituciones.php';\n\t\t\trequire $dir.'/app/templates/inicio.php';\n\t\t}\t\t\n\t}\n?>" }, { "alpha_fraction": 0.7336814403533936, "alphanum_fraction": 0.7336814403533936, "avg_line_length": 17.285715103149414, "blob_id": "194623225e9151764d71c063d1e3e09398f168ec", "content_id": "21b3e08d1ba868e46ba9f960fb3f87abb74f07e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 383, "license_type": "permissive", "max_line_length": 37, "num_lines": 21, "path": "/ManualUsuario/makefile", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "manuales: solicitante encargado admin\n\nsolicitante: manual_solicitante.tex\n\tmkdir -p tmp\n\tpdflatex --output-dir tmp $<\n\nencargado: manual_encargado.tex\n\tmkdir -p tmp\n\tpdflatex --output-dir tmp $<\n\nadmin: manual_administrador.tex\n\tmkdir -p tmp\n\tpdflatex --output-dir tmp $<\n\napoyoTecnico: indexApoyoTecnico.tex\n\tmkdir -p tmp\n\tpdflatex --output-dir tmp $<\n\nclean:\n\trm *.pdf &\n\trm tmp/*" }, { "alpha_fraction": 0.6275100111961365, "alphanum_fraction": 0.6365461945533752, "avg_line_length": 35.925926208496094, "blob_id": "f54cf53484fbc31efbbf8ee0b71f16d381f6a193", "content_id": "0582b9949de927317f1da033f2d7bc1fa0bbf625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 996, "license_type": "permissive", "max_line_length": 161, "num_lines": 27, "path": "/controlador/registraRespuestaEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$opcion=$_POST[\"group1\"];\n\t$opinion=$_POST[\"opinion\"];\n\t$sqlp=\"insert into opinion (opinion) values ('\".$opinion.\"');\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t$sql=\"select IDOpinion from opinion where opinion like '$opinion';\";\n\t$usrs=mysqli_query($conexion,$sql);\n\t\t\t\tif($usrs->num_rows)//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\twhile($row = mysqli_fetch_assoc($usrs)) {\n\t\t\t\t\t\t\t$idop= $row[\"IDOpinion\"];\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\n\t$sqlp=\"insert into respuesta (idpregunta,idopcion,id,idopinion) values (\".$_SESSION[\"acceso\"][7].\",\".$_POST[\"group1\"].\",\".$_SESSION[\"acceso\"][6].\",\".$idop.\");\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\n\t$sqlp=\"update usuario set ultimapregunta=\".$_SESSION[\"acceso\"][7].\" where id=\".$_SESSION[\"acceso\"][6].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t\n\t$_SESSION[\"acceso\"][7]=$_SESSION[\"acceso\"][7]+1;\n\t\n?>" }, { "alpha_fraction": 0.6310043931007385, "alphanum_fraction": 0.6426491737365723, "avg_line_length": 40.66666793823242, "blob_id": "f805e296c0781e6b26b3d31abcb5702c8873091a", "content_id": "7aa19e14f1541564f4e59fb16a39a89830d7be93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1374, "license_type": "permissive", "max_line_length": 229, "num_lines": 33, "path": "/controlador/regresaPregunta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t//printArray($_POST);\n\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$opinion=$_POST[\"opinion\"];\n\t$rango=$_POST[\"fader_\"];\n\t//contamos el numero de respuestas que ya existen para esa pregeunta\n\t$sqlp=\"select * from respuestaProfesor where IDPregunta=\".$_SESSION[\"acceso\"][7].\" and ID=\".$_SESSION[\"acceso\"][6].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t$x=0;\n\t while($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t $x++;\n\t }\n\tif($x==0){\n\t\t$sqlp=\"insert into respuestaProfesor (ID,IDPregunta,Opinion,Rango) values(\".$_SESSION[\"acceso\"][6].\",\".$_SESSION[\"acceso\"][7].\",'\".$opinion.\"',\".$rango.\");\";\n\t\t$paises=mysqli_query($conexion,$sqlp);\n \n\t}\n\telse{\n\t\t$sqlp=\"update respuestaProfesor set ID=\".$_SESSION[\"acceso\"][6].\", IDPregunta=\".$_SESSION[\"acceso\"][7].\", Opinion='\".$opinion.\"', Rango=\".$rango.\" where IDPregunta=\".$_SESSION[\"acceso\"][7].\" and ID=\".$_SESSION[\"acceso\"][6].\";\";\n\t\t$paises=mysqli_query($conexion,$sqlp);\n \n\t}\n\t\n\t$x=$_SESSION[\"acceso\"][7]-2;\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$_SESSION[\"acceso\"][7]=$x;\n\t$sqlp=\"update usuario set ultimapregunta=\".$_SESSION[\"acceso\"][7].\" where id=\".$_SESSION[\"acceso\"][6].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t//echo $_SESSION[\"acceso\"][7];\n\n?>" }, { "alpha_fraction": 0.583745002746582, "alphanum_fraction": 0.601270318031311, "avg_line_length": 30.812734603881836, "blob_id": "ea3f5d97835c9a212b5cbce2d4d889f74277d01b", "content_id": "5110882f281fc21c2db8906fb3ef32850e90b07c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8509, "license_type": "permissive", "max_line_length": 130, "num_lines": 267, "path": "/js/validaciones.js", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "\t\t\t\t\n\t\t\t\tfunction capPaterno()\n\t\t\t\t{\n\t\t\t\t\tvar apP = formUsuario.txtApPat.value;\n\t\t\t\t\tvar apPa=\"\";\t\t\t\t\n\t\t\t\t\tapP=apP.replace(/[0-9]/g,\"\");\n\t\t\t\t\tvar stringArray = new Array();\n\t\t\t\t\tstringArray = apP.split(\" \");\n\t\t\t\t\tfor (i = 0; i < stringArray.length; i++) {\n\t\t\t\t\t\tif(i==(stringArray.length-1)){\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tapPa+=stringArray[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tapPa+=stringArray[i]+\" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttxtApPat.value =apPa;\n\t\t\t\t}\n\t\t\t\tfunction capMaterno()\n\t\t\t\t{\n\t\t\t\t\tvar apM = formUsuario.txtApMat.value;\n\t\t\t\t\tvar apMa=\"\";\t\t\t\t\n\t\t\t\t\tapM=apM.replace(/[0-9]/g,\"\");\n\t\t\t\t\tvar stringArray = new Array();\n\t\t\t\t\tstringArray = apM.split(\" \");\n\t\t\t\t\tfor (i = 0; i < stringArray.length; i++) {\n\t\t\t\t\t\tif(i==(stringArray.length-1)){\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tapMa+=stringArray[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tapMa+=stringArray[i]+\" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttxtApMat.value =apMa;\n\t\t\t\t}\n\t\t\t\tfunction cnombre()\n\t\t\t\t{\t\t\t\t\n\t\t\t\t\tvar nom = formUsuario.txtNombre.value;\n\t\t\t\t\tvar nomb=\"\";\t\t\t\t\n\t\t\t\t\tnom=nom.replace(/[0-9]/g,\"\");\n\t\t\t\t\tvar stringArray = new Array();\t\t\t\t\n\t\t\t\t\tstringArray = nom.split(\" \");\n\t\t\t\t\tfor (i = 0; i < stringArray.length; i++) {\n\t\t\t\t\t\tif(i==(stringArray.length-1)){\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tnomb+=stringArray[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tstringArray[i]=stringArray[i].charAt(0).toUpperCase()+ (stringArray[i].slice(1)).toLowerCase();\n\t\t\t\t\t\t\tnomb+=stringArray[i]+\" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttxtNombre.value =nomb;\n\t\t\t\t}\n\t\t\t\tfunction cemail()\n\t\t\t\t{\n\t\t\t\t\tvar email1 = formUsuario.txtEmail.value;\n\t\t\t\t\tvar email2 = formUsuario.txtEmail2.value;\n\t\t\t\t\tif(email1==email2 && (email1!=\"\" || email2!=\"\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelEmail\").style.color=\"green\";\n\t\t\t\t\t\tdocument.getElementById(\"labelEmail\").textContent= \"Los correos coinciden.\";\t\t\t\t\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelEmail\").style.color=\"red\";\n\t\t\t\t\t\tdocument.getElementById(\"labelEmail\").textContent= \"Los correos no coinciden.\";\t\t\t\t\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction pass(){\n\t\t\t\t\tvar password1 = formUsuario.txtPwd.value;\n\t\t\t\t\tvar password2 = formUsuario.txtPwd2.value;\n\t\t\t\t\n\t\t\t\t\tif(password2.length>password1.length && password1.length>5){\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").style.color=\"red\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").textContent= \"Las contraseñas no coinciden.\";\t\t\t\t\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t\tif(password1.length<6 && password1.length>0){\n\t\t\t\t\t\tdocument.getElementById(\"labelPass\").style.color=\"red\";\t\t\t\t\n\t\t\t\t\t\tdocument.getElementById(\"labelPass\").textContent= \"Contraseña muy corta\";\n\t\t\t\t\t\tdocument.formUsuario.siguiente.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t\tif(!(password1.length<6 && password1.length>0) && !(password2.length>password1.length && password1.length>5)){\n\t\t\t\t\t\tdocument.getElementById(\"labelPass\").style.color=\"white\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPass\").textContent= \".\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t\tif(password2.length<password1.length && password2.length>0){\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").style.color=\"red\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").textContent= \"Contraseña de confirmación muy corta\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t\tif(!(password2.length<password1.length && password2.length>0) && !(password2.length>password1.length && password1.length>5)){\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").style.color=\"white\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").textContent= \".\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tif(!(password2.length<password1.length) && !(password1.length<6) && password2.length>0 && password1==password2){\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").style.color=\"green\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").textContent= \"Las contraseñas coinciden.\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=false;\n\t\t\t\t\t}\n\t\t\t\t\tif(!(password2.length<password1.length) && !(password1.length<6) && password2.length>0 && !(password1==password2)){\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").style.color=\"red\";\n\t\t\t\t\t\tdocument.getElementById(\"labelPassC\").textContent= \"Las contraseñas no coinciden.\";\t\t\t\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction cfecha()\n\t\t\t\t{\n\t\t\t\t\tvar fecha = formUsuario.txtFechaNac.value;\t\t\n\t\t\t\t\tvar pFecha=\"^(19[0-9]{2}|20[0-1]{1}[0-9]{1})[-](0[1-9]|1[0-2])[-](0[0-9]|1[0-9]|2[0-9]|3[0-1])$\";\t\n\t\t\t\t\tpFechaExp = new RegExp(pFecha);\n\t\t\t\n\t\t\t\t\tif(fecha.length==10 && fecha.match(pFechaExp))\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelFN\").style.color=\"green\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=false; \n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelFN\").style.color=\"red\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction cinstitucion()\n\t\t\t\t{\n\t\t\t\t\tvar inst=formUsuario.txtInstitucion.value;\n\t\t\t\t\ttxtInstitucion.value = inst.toUpperCase();\n\t\t\t\t\tvar pinst=\"[A-Z]+[-][A-Z]+\";\n\t\t\t\t\tinstExp= new RegExp(pinst);\n\t\t\t\t\tif(inst.match(instExp))\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelInst\").style.color=\"green\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=false;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(\"labelInst\").style.color=\"red\";\n\t\t\t\t\t\tdocument.formUsuario.Registrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction validaSelect(id)\n\t\t\t\t{\t\t\t\n\t\t\t\t\n\t\t\t\t\tvar arreglo=id.split(\"-\");\n\t\t\t\t\tvar numPregunta= parseInt(arreglo[0]);\n\t\t\t\t\tvar numRespuesta=parseInt(arreglo[1]);\n\t\t\t\t\t\n\t\t\t\t\t//alert(x);\n\t\t\t\t\t\n\t\t\t\t\tvar posicion=parseInt(document.getElementById(id).options.selectedIndex);\n\t\t\t\t\tvar valor=document.getElementById(id).options[posicion].text;\n\t\t\t\t\tif(valor=='-')\n\t\t\t\t\t{\n\t\t\t\t\t\t//alert(\"No puedes dejar marcada la opcion '-'\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse\t\t\t\t\t\n\t\t\t\t\t\tvar valor=parseInt(document.getElementById(id).options[posicion].text);\n\t\t\t\t\t\n\t\t\t\t\t//alert(\"posicion: \"+posicion+\" valor: \"+valor);\n\t\t\t\t\t\n\t\t\t\t\t\t\n \t\t\t\t\n\t\t\t\t\tfor(i=1;i<=4;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t//alert(i);\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tvar sel = document.getElementById(numPregunta+\"-\"+i);\n\t\t\t\t\t\taBorrar = sel.options[valor];\n\t\t\t\t\t\taBorrar.disabled=true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t}\n\t\t\t\tfunction magia(numPreguntas)\n\t\t\t\t{\n\t\t\t\t\tfor(i=1;i<=numPreguntas;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(j=1;j<=4;j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(k=0;k<5;k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar sel = document.getElementById(i+\"-\"+j);\n\t\t\t\t\t\t\t\taBorrar = sel.options[k];\n\t\t\t\t\t\t\t\taBorrar.disabled=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction resetSelect(id)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById(id).checked=false;\n\t\t\t\t\t\n\t\t\t\t\tvar arreglo=id.split(\"-\");\n\t\t\t\t\tvar numPregunta=parseInt(arreglo[1]);\n\t\t\t\t\tfor(j=1;j<=4;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(k=0;k<5;k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar sel = document.getElementById(numPregunta+\"-\"+j);\n\t\t\t\t\t\t\t\tsel.selectedIndex=0;\n\t\t\t\t\t\t\t\taBorrar = sel.options[k];\n\t\t\t\t\t\t\t\taBorrar.disabled=false;\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tfunction verificaEnvio(idCuestionario)\n\t\t\t\t{\t\t\n\t\t\t\t\tvar numPreguntas=9;\t\n\t\t\t\t\tif(parseInt(idCuestionario)==1)\n\t\t\t\t\t\tnumPreguntas=15\t\n\t\t\t\t\t\t\n\t\t\t\t\tfor(i=1;i<=numPreguntas;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(j=1;j<=4;j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(k=0;k<5;k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar sel = document.getElementById(i+\"-\"+j);\n\t\t\t\t\t\t\t\tif(sel.selectedIndex==0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\talert(\"No puedes dejar seleccionado '-' en la pregunta \"+i+\" opción \"+j);\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tmagia(numPreguntas);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\t\tfunction cambiarCorreo(correo)\n\t\t\t\t{\n\t\t\t\t\tvar correo1 = document.getElementById(\"txtEmail\");\n\t\t\t\t\tvar correo2 = document.getElementById('txtEmail2');\n\t\t\t\t\tif(document.getElementById(\"nuevoCorreo\").checked == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tcorreo1.readOnly=false;\n\t\t\t\t\t\tcorreo1.value=\"\";\n\t\t\t\t\t\tcorreo2.value=\"\";\n\t\t\t\t\t\tcorreo2.style.visibility = \"visible\";\n\t\t\t\t\t\tcorreo1.placeholder = \"nuevo correo\";\n\t\t\t\t\t\tcorreo2.placeholder = \"confirmar nuevo correo\";\n\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcorreo1.value = correo;\n\t\t\t\t\t\tcorreo2.value = correo;\n\t\t\t\t\t\tcorreo1.readOnly = true;\n\t\t\t\t\t\tcorreo2.style.visibility = \"hidden\";\n\t\t\t\t\t}\n\t\t\t\t}" }, { "alpha_fraction": 0.3913300633430481, "alphanum_fraction": 0.40161025524139404, "avg_line_length": 40.95228958129883, "blob_id": "4a4226dd5498820a3a14c2582b3c0adb8c679967", "content_id": "7b08205a748233ad64d4f66168ccc1900b6dd3cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 22013, "license_type": "permissive", "max_line_length": 296, "num_lines": 524, "path": "/todasPreguntas.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nsession_start();\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\nmysqli_set_charset($conexion,\"utf8\");\n$contesto=$_SESSION[\"acceso\"][3];\n//echo $contesto;\n$Area=$_SESSION[\"acceso\"][5];\n/*if($_SESSION[\"acceso\"][7]==21){\n //checo que sea medico\n if($_SESSION[\"acceso\"][5]!=2){\n //NO ES MEDICO\n $sqlp=\"update usuario set contestoEncuesta='Si' WHERE id=\".$_SESSION[\"acceso\"][6].\";\";\n $contesto=\"Si\";\n //unset($_SESSION[\"acceso\"]);\n $paises=mysqli_query($conexion,$sqlp);\n }\n}*/\nif($_SESSION[\"acceso\"][7]==30){\n //YA ACABO\n\n $sqlp=\"update usuario set contestoEncuesta='Si' WHERE id=\".$_SESSION[\"acceso\"][6].\";\";\n $contesto=\"Si\";\n $paises=mysqli_query($conexion,$sqlp);\n //unset($_SESSION[\"acceso\"]);\n}\t\n//$_SESSION[\"acceso\"][7]=2;\n///////////////////////////////////////////////////////$_SESSION[\"acceso\"][7]=1;\n//// OBTENGO LA ULTIMA PREGUNTA QUE CONTESTO EL USUARIO\n//echo $_SESSION[\"acceso\"][6];\n$sql=\"select UltimaPregunta from usuario where id=\".$_SESSION[\"acceso\"][6].\";\";\n$pai=mysqli_query($conexion,$sql);\nif($pai)//Si me regresa tuplas significa que ya esta registrado\n{\n\n while($cuba=mysqli_fetch_array($pai,MYSQLI_BOTH)){\n $cuba[0]+=1;\n\t\t\n\t\tif($cuba[0]>30){\n\t\t\t$cuba[0]=30;\n\t\t}\n if($cuba[0]<0){\n $cuba[0]=1;\n }\n $_SESSION[\"acceso\"][7]=$cuba[0];\n\n //echo $_SESSION[\"acceso\"][7];\n }\n\n}\nelse{\n echo mysqli_error($conexion);\n}\n$sqlp=\"select pregunta,pathImg from pregunta where idPregunta=\".$_SESSION[\"acceso\"][7].\";\";\n$paises=mysqli_query($conexion,$sqlp);\n$sql=\"select * from opciones where idPregunta=\".$_SESSION[\"acceso\"][7].\";\";\n$respuestas=mysqli_query($conexion,$sql);\n//echo $Area;\n\nif($Area==1 || $Area==2 || $Area==3)\n{\n // if(strcmp(\"No\", $contesto)==0){ para redir\n\n\n?>\n\n<!doctype html>\n<html lang=\"es\">\n <!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=.9,maximum-scale=.9\">\n\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.1/js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\n $('.modal').modal();\n\t\t\t<?php\n\t\t\t\tif($_SESSION[\"acceso\"][7]==30){\n\t\t\t?>\n // $('#modal1').modal('open');\n\t\t\t //alert(\"Usted ha terminado de contestar nuestro cuestionario. Si necesita hacer una modificación a sus respuestas anteriores, puede hacerlo\");\n\t\t\t<?php\n\t\t\t\t}\n\t\t\t?>\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n // Initialize collapsible (uncomment the line below if you use the dropdown variation)\n //$('.collapsible').collapsible();\n\n //tipo parallax\n /*\n\t\t\t$('.pushpin-demo-nav').each(function() {\n\t\t\t\tvar $this = $(this);\n\t\t\t\tvar $target = $('#' + $(this).attr('data-target'));\n\t\t\t\t$this.pushpin({\n\t\t\t\t\t//top: $target.offset().top,\n\t\t\t\t\tbottom: $target.offset().top + $target.outerHeight() - $this.height()\n\t\t\t\t});\n\t\t\t});*/\n\n $('.target').pushpin({\n top: 0,\n bottom: 1000,\n offset: 0\n });\n\n $(\"#btn-submit\").click(function(e){\n //alert(\"holaaa\");\n //alert($(\"#respuesta\").serialize());\n $.ajax({\n type: \"post\",\n url: \"controlador/registraRespuestaProfesor.php\",\n data: $(\"#respuesta\").serialize(),\n success: function(resp) {\n //alert(resp);\n location.reload();\n\n }\n });\n\t\t\t\t\n\t\t\t\t $.ajax({\n type: \"post\",\n url: \"controlador/opinionGeneral.php\",\n data: $(\"#opGeneral\").serialize(),\n success: function(resp) {\n //alert(resp);\n location.reload();\n\n }\n });\n\n return false;\n });\n $(\"#btn-finalizar\").click(function(e){\n $('#modal1').modal('open');\n //alert(\"holaaa\");\n //alert($(\"#respuesta\").serialize());\n \n \n });\n\t\t\t\n\t\t\t\n\t\t\t$(\"#getback\").click(function(e){\n \t//alert(\"holaaa\");\n \n $.ajax({\n type: \"post\",\n url: \"controlador/regresaPregunta.php\",\n data: $(\"#respuesta\").serialize(),\n success: function(resp) {\n //alert(resp);\n location.reload();\n\n }\n });\n\t\t\t\t $.ajax({\n type: \"post\",\n url: \"controlador/opinionGeneral.php\",\n data: $(\"#opGeneral\").serialize(),\n success: function(resp) {\n //alert(resp);\n location.reload();\n\n }\n });\n\n\n return false;\n });\n\t\t\t\n });\n\n var slider = document.getElementById('test5');\n noUiSlider.create(slider, {\n start: [20, 80],\n connect: true,\n step: 1,\n range: {\n 'min': 0,\n 'max': 100\n },\n format: wNumb({\n decimals: 0\n })\n });\n function outputUpdate(vol) {\n document.querySelector('#escala').value = vol;\n }\n\n\n </script>\n\n <body>\n\n <?php\n include (\"barra.html\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"encabezados\" -->\n <div id='banner'>\n <div class=\"row\">\n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n </div>\n </header>\n </div>\n </div>\n\n\n\n\n <?php \n include(\"BarraConfiguracion.php\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"content\" -->\n <div class=\"contenido\">\n\n\n <div class=\"row\">\n <div class=\"col s12 m6 l6\">\n <h2 style=\"color:black;\">Cuestionario propuesto</h2>\n <!-- NUEVO-->\n <h4> Pregunta \n <?php\n echo $_SESSION[\"acceso\"][7];\n ?>\n </h4>\n <ul>\n <li>\n <?php\n\t\t\t\t\t\t\t\t\t\n while($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n //echo $pais[0];\n\t\t\t\t\t\t\t\t\t $pais[0]=str_replace(\"<img>\", \"<div class='barraLateral'>\n <div class='row'>\n <div class='col s5 offset-s1'>\n <img src='$pais[1]' class='materialboxed' style='width:250%;' >\n </div>\n </div>\n </div>\", $pais[0]);\n\t\t\t\t\t\t\t\t\t $pais[0]=str_replace(\"<imgsmall>\", \"<div class='barraLateral'>\n <div class='row'>\n <div class='col s5 offset-s1'>\n <img src='$pais[1]' class='materialboxed' style='width:150%;' >\n </div>\n </div>\n </div>\", $pais[0]);\n\t\t\t\t\t\t\t\t\t echo $pais[0];\n\n\n ?>\n </li>\n </ul> \n <?php\n /*echo \"<div class='barraLateral'>\n <div class='row'>\n <div class='col s5 offset-s1'>\n <img src='$pais[1]' class='materialboxed' style='width:250%;' >\n </div>\n </div>\n </div>\";\t*/\n }\n ?>\n\n\n\n <form action=\"#\" id=\"respuesta\" name=respuesta>\n <?php\n while($miau=mysqli_fetch_array($respuestas,MYSQLI_BOTH)){\n echo \"<p><input name='group1' type='radio' id='\".$miau[0].\"' value='\".$miau[0].\"' disabled='disabled'><label for='\".$miau[0].\"'></label>\".$miau[1].\"</p>\";\n }\n ?>\n\n <p class=\"range-field\">\n <label for=\"fader\">Escala de Dificultad </label>\n <br>\n <label for=\"fader\">0=Muy fácil, 10=Muy difícil</label>\n <?php\n $query=\"select rango, opinion, id from respuestaprofesor where id=\".$_SESSION[\"acceso\"][6].\" and idpregunta=\".$_SESSION[\"acceso\"][7].\";\";\n $respu=mysqli_query($conexion,$query);\n while($miaus=mysqli_fetch_array($respu,MYSQLI_BOTH)){\n $rango=$miaus[0];\n $op=$miaus[1];\n }\n if($rango==\"\"){\n $rango=5;\n } \n ?>\n <div class=\"col s12 m9 l10\" >\n <input type=\"range\" id=\"fader\" value=\"<?php echo $rango; ?>\" name=\"fader \"min=\"0\" max=\"10\" step=\"1\" oninput=\"outputUpdate(value)\" />\n </div>\n <div class=\"col l2\">\n <output for=\"fader\" id=\"escala\" name=\"escala\"><?php echo $rango; ?></output> \n </div> \n\n <div class=\"input-field col s12\">\n <textarea id=\"opinion\" class=\"materialize-textarea\" name=\"opinion\"><?php echo $op; ?></textarea>\n <label for=\"textarea1\">Opinion De la Pregunta</label>\n </div>\n </form>\n </div>\n\n <!-- FIN NUEVO-->\n <?php\n $cons='select Texto from opiniongeneral where id='.$_SESSION[\"acceso\"][6].';';\n $res=mysqli_query($conexion,$cons);\n $ac=0;\n $arreglo[]=array();\n while($pra=mysqli_fetch_array($res,MYSQLI_BOTH)){\n \n $arreglo[$ac]=$pra[0];\n //echo $arreglo[$ac]; \n $ac++;\n }\n ?>\n\n\t\t\t\n <div class=\"col s12 m6 l6\">\n \n <h5>Opini&oacute;n del cuestionario en general</h5>\n <ol>\t\n <li>Presentación de las preguntas. ¿El tipo y tamaño de letra son adecuados?, ¿las imágenes están bien distribuidas?, etc.\n </li>\n <form action=\"\" id=\"opGeneral\" name=\"opGeneral\">\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text1\" name=\"text1\" class=\"materialize-textarea\" ><?php if(mysqli_num_rows($res)!=0){echo $arreglo[0];} ?></textarea>\n <label for=\"text1\">Opinion </label>\n </div>\n </div>\n \n </div>\n <li>\n \tRedacción de las preguntas. ¿La redacción de las preguntas es suficientemente clara como para evitar ambigüedades?, ¿se puede extraer con claridad la información, así como comprender lo que se pregunta?\n </li>\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text2\" name=\"text2\" class=\"materialize-textarea\"><?php if(mysqli_num_rows($res)!=0){echo $arreglo[1];} ?></textarea>\n <label for=\"text2\">Opinion </label>\n </div>\n </div>\n \n </div>\n <li>\n \tCalidad de los distractores, ¿los distractores permitirían discriminar entre un estudiante que comprende adecuadamente los conceptos y otro que tenga errores conceptuales?\n </li>\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text3\" name=\"text3\" class=\"materialize-textarea\"><?php if(mysqli_num_rows($res)!=0){echo $arreglo[2];} ?></textarea>\n <label for=\"text3\">Opinion </label>\n </div>\n </div>\n \n </div>\n <li>\n Nivel de dificultad del cuestionario en su conjunto. ¿Considera el cuestionario con un bajo nivel de dificultad, con un alto nivel de dificultad, o bien, con un nivel adecuado para ser aplicado a estudiantes de pregrado?\n </li>\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text4\" name=\"text4\" class=\"materialize-textarea\"><?php if(mysqli_num_rows($res)!=0){echo $arreglo[3];} ?></textarea>\n <label for=\"text4\">Opinion </label>\n </div>\n </div>\n \n </div>\n <li>\n Tiempo estimado de respuesta del cuestionario. ¿Cuánto tiempo estima usted necesario para responder el cuestionario? Considere dos casos: a) incluyendo la selección del nivel de seguridad y la justificación de la respuesta y b) solo respondiendo cada pregunta.\n </li>\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text5\" name=\"text5\" class=\"materialize-textarea\"><?php if(mysqli_num_rows($res)!=0){echo $arreglo[4];} ?></textarea>\n <label for=\"text5\">Opinion </label>\n </div>\n </div>\n \n </div>\n <li>\n \tOtros comentarios que considere pertinentes\n </li>\n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"text6\" name=\"text6\" class=\"materialize-textarea\"><?php if(mysqli_num_rows($res)!=0){echo $arreglo[5];} ?></textarea>\n <label for=\"text6\">Opinion </label>\n </div>\n </div>\n \n </div>\n </form>\n </ol>\n </div>\n \n </div>\n <div class=\"row\">\n <?php\n\t\t\t\t\tif($_SESSION[\"acceso\"][7]!=1 && $_SESSION[\"acceso\"][7]!=30 ){\n\t\t\t\t?>\n <div class=\"input-field col s6\" style=\" position: relative;text-align: right;\">\n <a href=\"todasPreguntas.php\" id=\"getback\" name=\"getback\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Anterior\n <i class=\"material-icons right\">arrow_back</i>\n </button></a>\n </div>\n \n <div class=\"input-field col s6\" >\n <a href=\"todasPreguntas.php\" id=\"btn-submit\" name=\"btn-submit\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Siguiente\n <i class=\"material-icons right\">send</i>\n </button></a>\n </div>\n \n <?php\n\t\t\t\t\t}\n\t\n\t\t\t\t\telse if($_SESSION[\"acceso\"][7]==30){\n\t\t\t\t\t\n\t\t\t\t\t\t?>\n\t\t\t\t\t \t \n\t\t\t\t <div class=\"input-field col s6\" style=\" position: relative;text-align: right;\">\n <a href=\"todasPreguntas.php\" id=\"getback\" name=\"getback\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Anterior\n <i class=\"material-icons right\">arrow_back</i>\n </button></a>\n </div>\n <div class=\"input-field col s6\" >\n <a id=\"btn-finalizar\" name=\"btn-submit\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Finalizar\n <i class=\"material-icons right\">check</i>\n </button></a>\n </div>\n </div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t else{\n\t\t\t\t\t\t ?>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"input-field col s6\" style=\" position: relative;text-align: right;\">\n <a href=\"todasPreguntas.php\" id=\"btn-submit\" name=\"btn-submit\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Siguiente\n <i class=\"material-icons right\">send</i>\n </button></a>\n </div>\n </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t \n\t\t\t\t\t\t <?php\n\t\t\t\t\t }\n\t\t\t\t?>\n \n \n\n \n\n <!-- InstanceEndEditable -->\n <footer>\n <!--Aqui va el pie de pagina-->\n <br>\n <p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n <br>\n </footer>\n \n <div id=\"modal1\" class=\"modal\">\n\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t <h4>Cuestionario completado</h4>\n\t\t\t\t <p>Usted ha terminado de contestar nuestro cuestionario. Si necesita hacer una modificación a sus respuestas anteriores, puede hacerlo.</p>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t <a href=\"EncuestaPiloto.php\" class=\"modal-action modal-close waves-effect waves-green btn-flat \">Aceptar</a>\n\t\t\t\t <a href=\"#!\" class=\"modal-action modal-close waves-effect waves-green btn-flat \">Continuar en el cuestionario</a>\n\t\t\t\t</div>\n\t\t\t </div>\n \n </body>\n <!-- InstanceEnd -->\n\n </html>\n <?php\n }\n /* else{ //para redir\n echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n }*/\n//}\nelse{\n\n echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n}\n\n ?>\n\n" }, { "alpha_fraction": 0.6273062825202942, "alphanum_fraction": 0.6273062825202942, "avg_line_length": 16.69565200805664, "blob_id": "687a09f20dad4bb01fe604f24f65b763ea9ed24b", "content_id": "1e86fb62ce1dcd2cc193f92e4bfeaf075cddb7ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 813, "license_type": "permissive", "max_line_length": 63, "num_lines": 46, "path": "/public_html/app/bean/Institucion.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass Institucion\n\t{\n\t\t//Atributos\n\t\tprivate $idInstitucion;\n\t\tprivate $nombre;\n\t\tprivate $siglas;\n\t\t\n\t\t//Constructor\n\t\tpublic function __construct($idInstitucion, $nombre, $siglas)\n\t\t{\n\t\t\t$this -> idInstitucion = $idInstitucion;\n\t\t\t$this -> nombre= $nombre;\n\t\t\t$this -> siglas = $siglas;\n\t\t}\t\t\n\t\t\t\t\n\t\t//Metodos\n\t\t//getters\n\t\tpublic function getIdInstitucion(){\n\t\t\treturn $this -> idInstitucion;\n\t\t}\n\t\t\n\t\tpublic function getNombre(){\n\t\t\treturn $this -> nombre;\n\t\t}\n\t\t\n\t\tpublic function getSiglas(){\n\t\t\treturn $this -> siglas;\n\t\t}\n\t\t\n\t\t//Setters\n\t\tpublic function setIdInstitucion($idInstitucion){\n\t\t\t$this -> idInstitucion = $idInstitucion;\n\t\t}\n\t\t\n\t\tpublic function setNombre($nombre){\n\t\t\t$this -> nombre = $nombre;\n\t\t}\n\t\t\n\t\tpublic function setSiglas($siglas){\n\t\t\t$this -> siglas = $siglas;\n\t\t}\n\t}\n\t\n\t\n?>" }, { "alpha_fraction": 0.5886544585227966, "alphanum_fraction": 0.5996249318122864, "avg_line_length": 33.073482513427734, "blob_id": "c320de0cb17e65bfe34e9668d9dc15887660d643", "content_id": "41250cb6376951be40e6210a48177ffb8c32a1fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10687, "license_type": "permissive", "max_line_length": 169, "num_lines": 313, "path": "/registroEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<?php\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$sqlp=\"select * from pais;\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t\n?>\n<html lang=\"es\">\n<!-- InstanceBegin template=\"/Templates/plantillaCasiFull.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n<head>\n\t<meta charset=\"utf-8\">\n\n\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t<!-- links-->\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n\n\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t<!-- InstanceBeginEditable name=\"doctitle\" -->\n\n\n\n\n\n\t<title>Grupo de investigación en la enseñanza de física</title>\n\t<!-- InstanceEndEditable -->\n\t<!-- InstanceBeginEditable name=\"head\" -->\n\t<!-- InstanceEndEditable -->\n</head>\n<script>\n\t$(document).ready(function() {\n\n\t\t$('.modal').modal();\n\t\t$(\".button-collapse\").sideNav(); //boton de menu\n\n\t\t//para la fecha de nacimiento\n\t\t$('.datepicker').pickadate({\n\t\t\tselectMonths: true, // Creates a dropdown to control month\n\t\t\tselectYears: 15 // Creates a dropdown of 15 years to control year\n\t\t});\n\t\t//opcion \n\t\t$('select').material_select();\n\t\t$(\"#btn-Registrar\").click(function(e) {\n\t\t\t//alert($(\"#Registrar\").serialize());\n\n\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/registroServEncuesta.php\",\n\t\t\t\tdata: $(\"#Registrar\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\n\t\t\t\t\tif (resp == 1) {\n\t\t\t\t\t\t$('#modal1').modal('open');\n\n\t\t\t\t\t} else if (resp == 2) {\n\t\t\t\t\t\t$('#modal2').modal('open');\n\n\t\t\t\t\t} else if (resp == 3) {\n\t\t\t\t\t\t$('#modal3').modal('open');\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(resp)\n\t\t\t\t\t\t$('#modal4').modal('open');\n\t\t\t\t\t}\n\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t});\n\t});\n\n</script>\n\n<body>\n\n\t<?php\n include (\"barra.html\");\n ?>\n\n\n\n\n\t\t<!-- InstanceBeginEditable name=\"Banner\" -->\n\t\t<div id='banner'>\n\t\t\t<div class=\"row\">\n\t\t\t\t<header>\n\t\t\t\t\t<div class=\"col s12 m8 l6\">\n\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t<h2 style=\"padding:20%;\">Registro de usuario</h2>\n\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"col s12 m8 l6\">\n\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t</div>\n\t\t\t\t</header>\n\t\t\t</div>\n\t\t</div>\n\t\t<!-- InstanceEndEditable -->\n\t\t<!-- InstanceBeginEditable name=\"Content\" -->\n\t\t<div class=\"contenido\">\n\t\t\t<article>\n\t\t\t\t<h3 style=\"text-align:-webkit-center;\">Ingresa tus datos</h3>\n\t\t\t\t<p>Estos se guardarán de manera confidencial, por lo cual se te invita a realizar un registro responsable llenando los campos con tus datos reales.</p>\n\t\t\t\t<div class=\"formulario\">\n\t\t\t\t\t<form name=\"formUsuario\" action=\"controlador/registro.php\" method=\"post\" class=\"pure-form pure-form-stacked\" id=\"Registrar\">\n\n\n\n\t\t\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t<input id=\"icon_prefix\" type=\"text\" class=\"validate\" name=\"txtNombre\" id=\"txtNombre\" oninput=\"cnombre()\" placeholder=\"Nombre (s)\" required/>\n\t\t\t\t\t\t\t\t\t<label>Nombre(s)</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t<input id=\"icon_telephone\" class=\"validate\" type=\"text\" name=\"txtApPat\" id=\"txtApPat\" oninput=\"capPaterno()\" placeholder=\"Ap. Paterno\" required/>\n\t\t\t\t\t\t\t\t\t<label for=\"icon_telephone\">Apellido paterno</label>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t<input id=\"icon_prefix\" type=\"text\" class=\"validate\" name=\"txtApMat\" id=\"txtApMat\" oninput=\"capMaterno()\" placeholder=\"Ap. Materno\" required//>\n\t\t\t\t\t\t\t\t\t<label>Apellido materno:</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"input-field col s6\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">perm_identity</i>\n\t\t\t\t\t\t\t\t\t<input type=\"text\" class=\"validate\" name=\"txtEdad\" id=\"txtEdadUsuario\" maxlength=\"10\" oninput=\"\" required placeholder=\"\">\n\t\t\t\t\t\t\t\t\t<label>Edad:</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"input-field col s6\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">perm_identity</i>\n\t\t\t\t\t\t\t\t\t<label for=\"genero\" id=\"labelGenero\">Genero:</label>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\t<input type=\"radio\" name=\"genero\" value=\"M\" id=\"genero_0\" class=\"tRadio\" />\n\t\t\t\t\t\t\t\t\t\t<label for=\"genero_0\">Masculino</label>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\t<input type=\"radio\" name=\"genero\" value=\"F\" id=\"genero_1\" class=\"tRadio\" />\n\t\t\t\t\t\t\t\t\t\t<label for=\"genero_1\">Femenino</label>\n\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6 \">\n\n\t\t\t\t\t\t\t\t\t<label for=\"txtOcupacion\" id=\"labelOcup\" class=\"pure-checkbox\"> Nivel de formación que entrega tu institución:</label>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">toc</i>\n\t\t\t\t\t\t\t\t\t<select name=\"txtOcupacion\" id=\"txtOcupacion\" style=\"display:none;\" required>\n\t\t\t\t\t\t\t\t\t\t<option value=\"\" disabled selected>Elija una opción ...</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"1\">Secundaria</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"2\">Bachillerato o preparatoria</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"3\">Universitario</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"4\">Posgrado</option>\n\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6 \">\n\n\t\t\t\t\t\t\t\t\t<label for=\"txtOcupacion\" id=\"labelOcup\" class=\"pure-checkbox\">Pais</label>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">toc</i>\n\t\t\t\t\t\t\t\t\t<select name=\"txtPais\" id=\"txtPais\" style=\"display:none;\" required>\n\t\t\t\t\t\t\t\t\t\t<option value=\"\" disabled selected>Elija una opción ...</option>\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\t\t$x=0;\n\n\t\t\t\t\t\t\t\t\t\t\twhile($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t\t\t\t\t\t\t\t\t\t\techo \"<option value='$pais[0]'> $pais[1] </option>\";\n\n\t\t\t\t\t\t\t\t\t\t\t\t$x++;\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6 \">\n\n\t\t\t\t\t\t\t\t\t<label for=\"txtOcupacion\" id=\"labelOcup\" class=\"pure-checkbox\">Area de Institucion Educativa</label>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">toc</i>\n\t\t\t\t\t\t\t\t\t<select name=\"txtArea\" id=\"txtArea\" style=\"display:none;\" required>\n\t\t\t\t\t\t\t\t\t\t<option value=\"\" disabled selected>Elija una opción ...</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"\"></option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"1\">Ciencias Físico Matemáticas</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"2\">Ciencias Médico Biológicas</option>\n\t\t\t\t\t\t\t\t\t\t<option value=\"3\"> Ciencias Sociales y Administrativas</option>\n\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\n\n\t\t\t\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">label_outline</i>\n\t\t\t\t\t\t\t\t\t<textarea class=\"materialize-textarea\" name=\"txtInstitucion\" id=\"txtInstitucion\" oninput=\"cinstitucion()\" placeholder=\"Escuela-Institución\" required></textarea>\n\t\t\t\t\t\t\t\t\t<label for=\"txtInstitucion\">Institución (Ejemplo: ESCOM-IPN)</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">email</i>\n\t\t\t\t\t\t\t\t\t<input type=\"email\" name=\"txtEmail\" id=\"txtEmail\" oninput=\"cemail()\" placeholder=\"Email\" required/>\n\t\t\t\t\t\t\t\t\t<label for=\"txtEmail\">Email</label>\n\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">email</i>\n\t\t\t\t\t\t\t\t\t<input type=\"email\" name=\"txtEmail2\" id=\"txtEmail2\" oninput=\"cemail()\" placeholder=\"Confirmar email\" required/>\n\t\t\t\t\t\t\t\t\t<label for=\"txtEmail2\">Confirmar Email:</label>\n\t\t\t\t\t\t\t\t</div>\n\n\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">https</i>\n\t\t\t\t\t\t\t\t\t<input type=\"password\" name=\"txtPwd\" id=\"txtPwd\" oninput=\"pass()\" minlength=\"6\" maxlength=\"10\" placeholder=\"password\" required/>\n\n\t\t\t\t\t\t\t\t\t<label for=\"txtEmail\" id=\"labelEmail\">Contraseña<pre style='display:inline'>&#09;</pre></label>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">https</i>\n\t\t\t\t\t\t\t\t\t<input type=\"password\" name=\"txtPwd2\" id=\"txtPwd2\" oninput=\"pass()\" min=\"6\" maxlength=\"10\" placeholder=\"Confirmar password\" required/>\n\n\t\t\t\t\t\t\t\t\t<label for=\"txtPwd2\" id=\"labelPassC\" size=\"40\">Confirmar Contraseña<pre style='display:inline'>&#09;</pre></label>\n\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t<div class=\"input-field col s6\" style=\"padding-left:45%;\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" id=\"btn-Registrar\" value=\"Registrar\" class=\"btn waves-effect waves-light\" style=\"color:white;\">Registrar\n\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons right\">send</i>\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\n\n\t\t\t\t\t\t</div>\n\n\n\t\t\t\t\t</form>\n\n\n\t\t\t\t</div>\n\t\t\t</article>\n\t\t</div>\n\t\t<!-- InstanceEndEditable -->\n\t\t<footer>\n\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t<br>\n\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t<br>\n\t\t</footer>\n\t\t<div id=\"modal1\" class=\"modal\">\n\t\t\t<div class=\"modal-content\">\n\t\t\t\t<h4>Has sido registrado con &eacute;xito!!</h4>\n\t\t\t</div>\n\t\t\t<div class=\"modal-footer\">\n\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t</div>\n\t\t</div>\n\t\t<div id=\"modal2\" class=\"modal\">\n\t\t\t<div class=\"modal-content\">\n\t\t\t\t<h4>No hemos podido registrarte</h4>\n\t\t\t\t<p>Tus contraseñas no coinciden o est&aacute;n vac&iacute;as</p>\n\t\t\t</div>\n\t\t\t<div class=\"modal-footer\">\n\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t</div>\n\t\t</div>\n\t\t<div id=\"modal3\" class=\"modal\">\n\t\t\t<div class=\"modal-content\">\n\t\t\t\t<h4>Error</h4>\n\t\t\t\t<p>Ya te has dado de alta anteriormente</p>\n\n\t\t\t</div>\n\t\t\t<div class=\"modal-footer\">\n\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t</div>\n\t\t</div>\n\t\t<div id=\"modal4\" class=\"modal\">\n\t\t\t<div class=\"modal-content\">\n\t\t\t\t<h4>Error</h4>\n\t\t\t\t<p>Los datos que propocionaste no son suficientes</p>\n\n\t\t\t</div>\n\t\t\t<div class=\"modal-footer\">\n\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t</div>\n\t\t</div>\n</body>\n<!-- InstanceEnd -->\n\n</html>\n" }, { "alpha_fraction": 0.6207701563835144, "alphanum_fraction": 0.6231038570404053, "avg_line_length": 23.514286041259766, "blob_id": "faaeb5a163caa3022647566ff120c1a7290b5365", "content_id": "ba5f921c3f5e42533529d52bd74bbc5ec31fc247", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 857, "license_type": "permissive", "max_line_length": 98, "num_lines": 35, "path": "/controlador/verificar.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\t/* Este script sirve para verificar si existe o no una sesion de login para ayudar a seleccionar \n\t que menu de opciones mostrar dependiendo de cada tipo de usuario.\n\t */\n\t require_once(\"BeanUsuario.php\");\n\t \n\t session_start();\n\t $banderaEllos = false;\n\t $banderaSesion = false;\n\t $usuario = NULL;\n\t \n\t //Verificamos si existe la sesion\n\t if(isset($_SESSION['login'])){\n\t\t $usuario = unserialize($_SESSION['login']);\n\t\t $banderaSesion = true;\n\t\t \n\t\t //Revisamos que tipo de usuario es\n\t\t if($usuario->getTipo() == \"Ellos\"){\n\t\t\t $banderaEllos = true;\n\t\t }\n\t }\n\t \n\t function esAdministrador(){ \n\t\t if(isset($_SESSION['login'])){\n\t\t \t//Revisamos que tipo de usuario es\n\t\t\t$user = unserialize($_SESSION['login']);\n\t\t \tif($user->getTipo() == \"Ellos\"){\n\t\t\t\theader('Location: 4mat.php'); \n\t\t \t}\n\t\t }\n\t\t else{\n\t\t\t header('Location: 4mat.php'); \n\t\t }\n\t }\n?>" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 17, "blob_id": "ffaf0996593ce506bc3d6f6fc5f9ac2fc5d65834", "content_id": "1116a7ad35b517d1156f50c5b431a437113fbd1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 36, "license_type": "permissive", "max_line_length": 20, "num_lines": 2, "path": "/public_html/app/templates/css/imagenes/desktop.ini", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "[LocalizedFileNames]\n175.jpg=@175,0\n" }, { "alpha_fraction": 0.5582022666931152, "alphanum_fraction": 0.5635955333709717, "avg_line_length": 23.450550079345703, "blob_id": "8496a7103f504011af1f599912576555042c55d6", "content_id": "e6a70410c74c643e7243b32da8bf85632eb002d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2225, "license_type": "permissive", "max_line_length": 315, "num_lines": 91, "path": "/controlador/registroServEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php \n\t\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\n\t//obtener los datos del form\n\t$nombre = $_POST['txtNombre'];\n\t$apP=$_POST['txtApPat'];\n\t$apM=$_POST['txtApMat'];\n\t$edad = $_POST['txtEdad'];\n\t$inst = $_POST['txtInstitucion'];\n\t$nivel=$_POST['txtOcupacion'];\n\t$genero = $_POST['genero'];\n\t$email = $_POST['txtEmail'];\n\t$email2 = $_POST['txtEmail2'];\n\t$pass = $_POST['txtPwd'];\n\t$pass2 = $_POST['txtPwd2'];\n\t$area=$_POST['txtArea'];\n\t$pais=$_POST['txtPais'];\n\n\tif(empty($nombre) || empty($email)){\n\t\techo 4;\n\t}\n\t\n\telse if($email==$email2)\n\t{\n\t\t$query=\"select * from usuario where email='\".$email.\"'\";\n\t\t\n\t\t$usrs=mysqli_query($conexion,$query);\n\t\tif($usrs->num_rows)//Si me regresa tuplas significa que ya esta registrado\n\t\t{\n\n\t\t\techo 3;\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(empty($pass)){\n\t\t\t\techo 2;\n\t\t\t}\n\t\t\telse if($pass==$pass2)\n\t\t\t{\t\n\t\t\t\t$pass = md5($pass);\n\t\t\t\t\n\t\t\t\t//CHECO QUE EXISTA LA INSTITUCION:\n\t\t\t\t$query=\"SELECT IDInst FROM INSTITUCION WHERE NOMBRE LIKE '\".$inst.\"'; \";\n\t\t\t\t$usrs=mysqli_query($conexion,$query);\n\t\t\t\tif($usrs->num_rows)//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\twhile($row = mysqli_fetch_assoc($usrs)) {\n\t\t\t\t\t\t\t$inst= $row[\"IDInst\"];\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t$query=\"INSERT INTO INSTITUCION (NOMBRE) VALUES ('\".$inst.\"');\";\n\t\t\t\t\t$usrs=mysqli_query($conexion,$query);\n\t\t\t\t\t$query=\"SELECT IDInst FROM INSTITUCION WHERE NOMBRE LIKE '\".$inst.\"'; \";\n\t\t\t\t\t$usrs=mysqli_query($conexion,$query);\n\t\t\t\t\twhile($row = mysqli_fetch_assoc($usrs)) {\n\t\t\t\t\t\t\t$inst= $row[\"IDInst\"];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//AGREGO EL NIVEL\n\t\t\t\t\n\t\t\t\t$query=\"INSERT INTO usuario (ID, Nombre, ApPaterno, ApMaterno, Edad, Email, Passw, ContestoEncuesta, TipoUsuario, IDNivel, IDPais, IDInst,IDArea) VALUES (NULL, '\".$nombre.\"', '\".$apP.\"', '\".$apM.\"', '\".$edad.\"', '\".$email.\"', '\".$pass.\"', 'No', 'Profesor', '\".$nivel.\"', '\".$pais.\"', '\".$inst.\"','\".$area.\"');\";\n\t\t\t\t\n\t\t\t if(mysqli_query($conexion,$query))//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\techo 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t echo \"Error: \" . $query . \"<br>\" . mysqli_error($conexion);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\t\n\t}\n\telse\n\t\techo 2;\n \n\n\t\n\n?>\n" }, { "alpha_fraction": 0.6138211488723755, "alphanum_fraction": 0.6138211488723755, "avg_line_length": 16, "blob_id": "be82cce10e6cdae61d21a3e450d049502239d633", "content_id": "1111507f46f87f07603e8eedaac239476636607e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 492, "license_type": "permissive", "max_line_length": 45, "num_lines": 29, "path": "/public_html/app/controlador/Sesion.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nclass Sesion {\n\tfunction __construct() {\n\t\t//session_start();\n\t}\n\n\tpublic function setSesion($nombre, $valor) {\n\t\t$_SESSION [$nombre] = serialize($valor);\n\t}\n\n\tpublic function getSesion($nombre) {\n\t\tif (isset ( $_SESSION [$nombre] )) {\n\t\t\treturn unserialize( $_SESSION [$nombre]);\n\t\t} \n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic function eliminaSesion($nombre) {\n\t\tunset ( $_SESSION [$nombre] );\n\t}\n\n\tpublic function terminaSesion() {\n\t\t$_SESSION = array();\n\t\tsession_destroy ();\n\t}\n}\n?>" }, { "alpha_fraction": 0.5943238735198975, "alphanum_fraction": 0.5943238735198975, "avg_line_length": 34.17647171020508, "blob_id": "e5a5190f27720136378fe1f47c6307d1cda1fa5e", "content_id": "b1e0af1888b77b34001b9b2ed34f79902577a572", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 599, "license_type": "permissive", "max_line_length": 57, "num_lines": 17, "path": "/public_html/app/Config.php~", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": " <?php \n class Config\n {\n static public $mvc_bd_hostname = \"aapt-mx.org\";\n static public $mvc_bd_nombre = \"aaptmx_db_prueba\";\n static public $mvc_bd_usuario = \"aaptmx\";\n static public $mvc_bd_clave = \"ylatesis?\";\n\t \n /* static public $mvc_bd_hostname = \"localhost\";\n static public $mvc_bd_nombre = \"aaptmx_db_prueba\";\n static public $mvc_bd_usuario = \"aaptmx_dev_db\";\n static public $mvc_bd_clave = \"Ylatesisinsigneprofesor?\";\n\t \n\t /*static public $mvc_bd_nombre = \"aapt_mx\";\n static public $mvc_bd_usuario = \"\";\n static public $mvc_bd_clave = \"\";*/\n }\n" }, { "alpha_fraction": 0.5462334752082825, "alphanum_fraction": 0.5762227773666382, "avg_line_length": 24.94444465637207, "blob_id": "5c787faf9c589a71744ff22c000afc4c97b552b9", "content_id": "60fe5e3dcc3f204b9a292f2424e5c576de5807e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2808, "license_type": "permissive", "max_line_length": 154, "num_lines": 108, "path": "/public_html/app/templates/recover.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire 'PHPMailer-master/PHPMailerAutoload.php';\n\t$email=$_POST['email'];\n\t$mysqli= new mysqli(\"aapt-mx.org\",\"aaptmx\",\"ylatesis?\",\"aaptmx_db_prueba\") ;\n\tif (mysqli_connect_errno())\n\t\t{\n\t\t \tprintf(\"Falló la conexión failed: %s\\n\", $mysqli->connect_error);\n\t \t\texit();\n\t\t}\n\t$query = \"SELECT password from socio where email like('%$email%'); \";\n\t$result = mysqli_query($mysqli,$query);\n\t $numrows=mysqli_num_rows($result);\n\t\twhile ($line = mysqli_fetch_array($result, MYSQLI_BOTH)) \n\t\t{\n\t\t\t$pass=$line['0'];\n\t\t\t//echo $pass;\n\t\t}\n\tif($numrows==1){\n\t\t$mail = new PHPMailer;\n\n//$mail->SMTPDebug = 3; // Enable verbose debug output\n\n//$mail->isSMTP(); // Set mailer to use SMTP\n$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers\n$mail->SMTPAuth = true; // Enable SMTP authentication\n$mail->Username = '[email protected]'; // SMTP username\n$mail->Password = 'ylatesis?'; // SMTP password\n$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted\n$mail->Port = 587; // TCP port to connect to\n\n$mail->setFrom('[email protected]', 'Servicio de Recuperacion de Contraseñas AAPT-MX');\n$mail->addAddress($email, 'Usuario'); // Add a recipient\n$mail->addReplyTo('[email protected]', 'Servicio de Recuperacion de Contraseñas AAPT-MX');\n$mail->addCC('[email protected]');\n$mail->addBCC($email);\n\n\n$mail->isHTML(true); // Set email format to HTML\n\n$mail->Subject = 'Renvio de contraseña';\n$mail->Body = '\n<style type=\"text/css\">\n body,\n html, \n .body {\n background: #f3f3f3 !important;\n }\n\n .container.header {\n background: #f3f3f3;\n }\n\n .body-border {\n border-top: 8px solid #663399;\n }\n</style>\n\n<container class=\"header\">\n <row>\n <columns>\n <h1 class=\"text-center\"><center>AAPT-MX</center></h1>\n\n\n </columns>\n </row>\n</container>\n\n<container class=\"body-border\">\n <row>\n <columns>\n\n <spacer size=\"32\"></spacer>\n\n <center>\n <img src=\"https://scontent.fmex6-1.fna.fbcdn.net/v/t1.0-9/970630_654021824663735_487968958_n.jpg?oh=150aad6b32e4a5d3c0d4da1f1accffcc&oe=595F7D71\">\n </center>\n\n <spacer size=\"16\"></spacer>\n\n <h4>Estimado usuario:</h4>\n <p>Agradecemos que haya preferido nuestra servicio de reposici&oactue;n de contraseñas, sus datos son:\n \n <p>Contraseña: '.$pass.'</p>\n\n\n \n\n </columns>\n </row>\n\n <spacer size=\"16\"></spacer>\n</container>\n';\n$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';\n\nif(!$mail->send()) {\n // echo 'Message could not be sent.';\n echo 'Mailer Error: ' . $mail->ErrorInfo;\n \n} else {\n echo 1;\n}\n\n\t}\n\n\n\t\t\n?>" }, { "alpha_fraction": 0.6367424130439758, "alphanum_fraction": 0.6382575631141663, "avg_line_length": 22.16666603088379, "blob_id": "c16e30dd0470645333cbf7af4e3cff68224ac831", "content_id": "2f905ba3383c3d1771eff52fc7a25985dc4e53c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2640, "license_type": "permissive", "max_line_length": 150, "num_lines": 114, "path": "/public_html/app/bean/Socio.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass Socio\n\t{\n\t\t//Atributos\n\t\tprivate $noMembresia;\n\t\tprivate $nombreCompleto;\n\t\tprivate $prefijo; // Valores: Dr. | M. en C. | Ing. | Lic. | C. \n\t\tprivate $email;\n\t\tprivate $estudProf; // Valores: 0 := Profesor | 1 := Estudiante\n\t\tprivate $niClase; // Valores: posgrado | ns := Nivel Superior | nms | basico\n\t\tprivate $avisoBoletin; // Valores: 1 := Si | 0 := No\n\t\tprotected $password;\n\t\tprivate $idEscuela;\n\t\tprivate $idTrabajo;\n\t\t\n\t\t//Constructor\n\t\tpublic function __construct($noMembresia, $nombreCompleto, $prefijo, $email, $estudProf, $niClase, $avisoBoletin, $password, $idTrabajo, $idEscuela)\n\t\t{\n\t\t\t$this -> noMembresia= $noMembresia;\n\t\t\t$this -> nombreCompleto = $nombreCompleto ;\n\t\t\t$this -> prefijo= $prefijo;\n\t\t\t$this -> email= $email;\n\t\t\t$this -> estudProf = $estudProf ;\n\t\t\t$this -> niClase= $niClase ;\n\t\t\t$this -> avisoBoletin= $avisoBoletin ;\n\t\t\t$this -> password= $password ;\n\t\t\t$this -> idEscuela = $idEscuela;\n\t\t\t$this -> idTrabajo = $idTrabajo;\n\t\t\t\n\t\t}\n\t\t\n\t\t//Metodos getters\n\t\tpublic function getNoMembresia(){\n\t\t\treturn $this -> noMembresia;\n\t\t}\n\t\t\n\t\tpublic function getNombreCompleto(){\n\t\t\treturn $this -> nombreCompleto ;\n\t\t}\n\t\t\n\t\tpublic function getPrefijo(){\n\t\t\treturn $this -> prefijo;\n\t\t}\n\t\t\n\t\tpublic function getEmail(){\n\t\t\treturn $this -> email;\n\t\t}\n\t\t\n\t\tpublic function getEstudProf(){\n\t\t\treturn $this -> estudProf;\n\t\t}\n\t\t\n\t\tpublic function getNiClase(){\n\t\t\treturn $this -> niClase;\n\t\t}\n\t\t\n\t\tpublic function getAvisoBoletin(){\n\t\t\treturn $this -> avisoBoletin;\n\t\t}\n\t\t\n\t\tpublic function getPassword(){\n\t\t\treturn $this -> password;\n\t\t}\n\t\t\n\t\tpublic function getIdEscuela(){\n\t\t\treturn $this ->idEscuela ;\n\t\t}\n\t\t\n\t\tpublic function getIdTrabajo(){\n\t\t\treturn $this -> idTrabajo;\n\t\t}\n\t\n\t\t//Metodos setters\n\t\tpublic function setNoMembresia($noMembresia){\n\t\t\t$this -> noMembresia = $noMembresia;\n\t\t}\n\t\t\n\t\tpublic function setNombreCompleto($nombreCompleto){\n\t\t\t$this -> nombreCompleto = $nombreCompleto;\n\t\t}\n\t\t\n\t\tpublic function setPrefijo($prefijo){\n\t\t\t$this -> prefijo = $prefijo;\n\t\t}\n\t\t\n\t\tpublic function setEmail($email){\n\t\t\t$this -> email = $email;\n\t\t}\n\t\t\n\t\tpublic function setEstudProf($estudProf){\n\t\t\t$this -> estudProf = $estudProf;\n\t\t}\n\t\t\n\t\tpublic function setNiClase($niClase){\n\t\t\t$this -> niClase = $niClase;\n\t\t}\n\t\t\n\t\tpublic function setAvisoBoletin($avisoBoletin){\n\t\t\t$this -> avisoBoletin = $avisoBoletin;\n\t\t}\n\t\t\n\t\tpublic function setPassword($password){\n\t\t\t$this -> password = $password;\n\t\t}\n\t\t\n\t\tpublic function setIdEscuela($idEscuela){\n\t\t\t$this ->idEscuela = $idEscuela;\n\t\t}\n\t\t\n\t\tpublic function setIdTrabajo($idTrabajo){\n\t\t\t$this -> idTrabajo = $idTrabajo;\n\t\t}\n\t}\t\n?>" }, { "alpha_fraction": 0.5782918334007263, "alphanum_fraction": 0.5943060517311096, "avg_line_length": 19.851852416992188, "blob_id": "341774f5242942233d91e52ab84f82266c36e74d", "content_id": "afc2168af2af3594a43b034d6399c72a363b29c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 562, "license_type": "permissive", "max_line_length": 102, "num_lines": 27, "path": "/controlador/modcontraEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\n\t//Conexion a la BD//\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\tsession_start();\n\t$usuario = $_SESSION[\"acceso\"][6];\n\t$pass = $_POST['txtPwd'];\n\t$pass2 = $_POST['txtPwd2'];\n\t\n\tif(empty($pass) || empty($pass2)){\n\t\techo 2;\n\t}\n\telse if($pass==$pass2){\n\t\t$p=md5($pass);\n\t\t$query= \"UPDATE usuario SET Passw =\\\"\".$p.\"\\\" WHERE ID= \".$usuario.\";\";\n\t\tif($res=mysqli_query($conexion,$query)){\n\t\t\techo 1;\n\t\t}\n\t\telse{\n\t\t\techo(\"Error description: \" . mysqli_error($conexion));\n\t\t}\n\t\t\n\t}\n\telse\n\t\techo 3;\n\n?>" }, { "alpha_fraction": 0.5315051078796387, "alphanum_fraction": 0.5407159328460693, "avg_line_length": 23.37755012512207, "blob_id": "473ca1284df0b55203e7c507c4ea3a94ce44d735", "content_id": "dd4d84fd15b456f086091d9941ade37541ca5fe8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4777, "license_type": "permissive", "max_line_length": 101, "num_lines": 196, "path": "/controlador/BeanUsuario.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire_once(\"connection.php\");\n\tclass BeanUsuario\n\t{\t\t\n\t\t/****************Atributos****************/\n\t\tprivate $idUsuario;\n\t\tprivate $tipo;\n\t\tprivate $nombre;\n\t\tprivate $fechaNac;\n\t\tprivate $sex;\n\t\tprivate $ocupacion;\n\t\tprivate $institucion;\n\t\tprivate $email;\n\t\t\n\t\tprivate $estilo;\n\t\tprivate $descEstilo;\n\t\tprivate $combinaEstilos;\n\t\t/******************************************/\t\t\n\t\t\n\t\tpublic function BeanUsuario($idUsuario,$nombre,$fechaNac,$sex,$ocupacion,$institucion,$email,$tipo)\n\t\t{\n\t\t\t$this->idUsuario = $idUsuario;\n\t\t\t$this->nombre = $nombre;\n\t\t\t$this->fechaNac=$fechaNac;\n\t\t\t$this->sex=$sex;\n\t\t\t$this->ocupacion=$ocupacion;\n\t\t\t$this->institucion=$institucion;\n\t\t\t$this->email=$email;\n\t\t\t$this->tipo=$tipo;\n\t\t}\n\t\t/******************METODOS GETTERS************************/\n\t\tpublic function getTipo()\n\t\t{\n\t\t\treturn $this->tipo;\n\t\t}\n\t\tpublic function getId()\n\t\t{\n\t\t\treturn $this->idUsuario;\n\t\t}\n\t\tpublic function getNombre()\n\t\t{\n\t\t\treturn $this->nombre;\n\t\t}\n\t\tpublic function getFechaNac()\n\t\t{\n\t\t\treturn $this->fechaNac;\n\t\t}\n\t\tpublic function getSex()\n\t\t{\n\t\t\treturn $this->sex;\n\t\t}\n\t\tpublic function getOcupacion()\n\t\t{\n\t\t\treturn $this->ocupacion;\n\t\t}\n\t\tpublic function getInstitucion()\n\t\t{\n\t\t\treturn $this->institucion;\n\t\t}\n\t\tpublic function getEmail()\n\t\t{\n\t\t\treturn $this->email;\n\t\t}\n\t\tpublic function getEstilo()\n\t\t{\n\t\t\treturn $this->estilo;\t\n\t\t}\n\t\tpublic function getDescEstilo()\n\t\t{\n\t\t\treturn $this->descEstilo;\n\t\t}\n\t\t/******************METODOS SETTERS***********************/\n\t\tpublic function setEstilo($numestilo)\n\t\t{\n\t\t\t$this->estilo=$numestilo;\n\t\t}\n\t\tpublic function setDescEstilo($descip)\n\t\t{\t\t\t\n\t\t\t$this->descEstilo=$descip;\n\t\t}\n\t\tpublic function setTipo($tipo)\n\t\t{\n\t\t\t$this->tipo = $tipo;\n\t\t}\n\t\tpublic function setId($idUsuario)\n\t\t{\n\t\t\t$this->idUsuario = $idUsuario;\n\t\t}\n\t\tpublic function setNombre($nombre)\n\t\t{\n\t\t\t$this->nombre = $nombre;\n\t\t}\n\t\tpublic function setFechaNac($fechaNac)\n\t\t{\n\t\t\t$this->fechaNac=$fechaNac;\n\t\t}\n\t\tpublic function setSex($sex)\n\t\t{\n\t\t\t$this->sex=$sex;\n\t\t}\n\t\tpublic function setOcupacion($ocupacion)\n\t\t{\n\t\t\t$this->ocupacion=$ocupacion;\n\t\t}\n\t\tpublic function setInstitucion($institucion)\n\t\t{\n\t\t\t$this->institucion=$institucion;\n\t\t}\n\t\tpublic function setEmail($email)\n\t\t{\n\t\t\t$this->email=$email;\n\t\t}\n\t\tpublic function calcularEstilo($mR)\n\t\t{\t\t\t\n\t\t\t$conexion = new connection();\n\t\t\t//-----------------------------------------------------------\n\t\t\t$query=\"call obtenerRespuesta(\".$this->getId().\",1,\".$mR.\")\";\n\t\t\t//echo $query;\n\t\t\t$conexion->conectar();\n\t\t\t$conexion->myQuery($query);\t\t\t\n\t\t\t$rs=$conexion->getArrayFila();\n\t\t\t$estilo1=$rs['count(*)'];\n\t\t\t$conexion->desconectar();\n\t\t\t//echo $estilo1.\"<br>\";\n\t\t\t//-----------------------------------------------------------\n\t\t\t$query=\"call obtenerRespuesta(\".$this->getId().\",2,\".$mR.\")\";\n\t\t\t//echo $query;\t\n\t\t\t$conexion->conectar();\t\t\n\t\t\t$conexion->myQuery($query);\t\t\t\n\t\t\t$rs=$conexion->getArrayFila();\n\t\t\t$estilo2=$rs['count(*)'];\n\t\t\t$conexion->desconectar();\n\t\t\t//echo $estilo2.\"<br>\";\t\t\t\n\t\t\t//-----------------------------------------------------------\n\t\t\t$query=\"call obtenerRespuesta(\".$this->getId().\",3,\".$mR.\")\";\n\t\t\t//echo $query;\n\t\t\t$conexion->conectar();\t\t\t\n\t\t\t$conexion->myQuery($query);\t\t\t\n\t\t\t$rs=$conexion->getArrayFila();\n\t\t\t$estilo3=$rs['count(*)'];\n\t\t\t$conexion->desconectar();\n\t\t\t//echo $estilo3.\"<br>\";\t\t\t\n\t\t\t//-----------------------------------------------------------\n\t\t\t$query=\"call obtenerRespuesta(\".$this->getId().\",4,\".$mR.\")\";\n\t\t\t//echo $query;\t\n\t\t\t$conexion->conectar();\t\t\n\t\t\t$conexion->myQuery($query);\t\t\t\n\t\t\t$rs=$conexion->getArrayFila();\n\t\t\t$estilo4=$rs['count(*)'];\n\t\t\t$conexion->desconectar();\n\t\t\t//echo $estilo4.\"<br>\";\t\t\t\n\t\t\t//-----------------------------------------------------------\t\t\n\t\t\t$array = array\n\t\t\t(\n\t\t \t1 => $estilo1,\n\t\t \t2 => $estilo2,\n\t\t\t\t3 => $estilo3,\n\t\t\t\t4 => $estilo4,\n\t\t\t);\t\t\n\t\t\tarsort($array);\n\t\t\tforeach($array as $key => $valor)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//echo $Estilo;\n\t\t\t$query=\"select descripcionE from estilo where idEstilo='\".$key.\"'\";\n\t\t\t//$this->setEstilo($key);\n\t\t\t//echo $query;\t\t\n\t\t\t$conexion->conectar();\n\t\t\t$conexion->myQuery($query);\t\t\t\n\t\t\t$rs=$conexion->getArrayFila();\n\t\t\t$this->setDescEstilo($rs['descripcionE']);\n\t\t\t$conexion->desconectar();\n\t\t\t\t\t\t\n\t\t\t//echo \"<br><br>Tu estilo es: \".$Estilo.\" <br>Descipcion: \".$descripcion.\"<br>\";\n\t\t\treturn $key;\t\t\t\n\t\t\t\n\t\t}\n\t\tpublic function calcular()\n\t\t{\n\t\t\t$res4=$this->calcularEstilo(4);\n\t\t\t$res3=$this->calcularEstilo(3);\n\t\t\t$res2=$this->calcularEstilo(2);\n\t\t\t$res1=$this->calcularEstilo(1);\n\t\t\tif($res4==$res3 && $res3== $res2 && $res2==$res1)\n\t\t\t\t$this->setEstilo(\"No Contestado\");\n\t\t\telse\t\n\t\t\t\tif(($res4+$res3+$res2+$res1)==10)\n\t\t\t\t\t$this->setEstilo($res4.\"-\".$res3.\"-\".$res2.\"-\".$res1);\n\t\t\t\telse\n\t\t\t\t\t$this->setEstilo(\"Mal contestado\");\n\t\t\t\n\t\t\t\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.5735707879066467, "alphanum_fraction": 0.654170572757721, "avg_line_length": 32.28125, "blob_id": "0c82c5eb8bf38d71c1d3ab4139979bd06a770a17", "content_id": "1ce3efa69e5e18b4bd8abd948b82dfcaa3beb30f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "permissive", "max_line_length": 173, "num_lines": 32, "path": "/public_html/app/templates/docs/batman.py", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "import random\nimport time\n\ndef anio():\n\tfurier=random.randrange(5)\n\testados={1:\"batman\", 2:\"blink\", 3:\"1526\", 4:\"supersegura\", 5:\"ekisde\",0:\"batbat\"}\n\treturn (estados[furier])\n\ndef nombre():\n\tfurier=random.randrange(20)\n\testados={0:\"JOAQUIN\",1:\"ISRAEL\", 2:\"ANGEL\", 3:\"PEDRO\", 4:\"ELIZABETH\", 5:\"ALAN\", 6:\"TEUCTZINTLI\",7:\"MAURICIO\",\n\t 8:\"JAVIER\",9:\"GERARDO\",10:\"ALY\",11:\"GABRIEL\",12:\"LUIS\",13:\"IVAN\",14:\"ERIKA\",15:\"ALAN\",16:\"AKETZALI\",17:\"ANTONIO\",18:\"ALEJANDRO\",19:\"BRANDO\",20:\"JESUS\",21:\"ARTURO\" }\n\treturn (estados[furier])\t\n\ndef app():\n\tfurier=random.randrange(20)\n\testados={0:\"AGUIRRE\",1:\"BARUCH\", 2:\"DIAZ\", 3:\"FERNANDEZ\", 4:\"GONZALEZ\", 5:\"LARA\", 6:\"LOPEZ\",7:\"MORANTE\",\n\t 8:\"OCHOA\",9:\"RONQUILLO\",10:\"RUIZ\",11:\"GABRIEL\",12:\"VAZQUEZ\",13:\"ZUNIGA\",14:\"BLANCO\",15:\"CARRASCO\",16:\"CASTRO\",17:\"CHACON\",18:\"FUENTES\",19:\"GARCIA\",20:\"GOMEZ\",21:\"GUZMAN\" }\n\treturn (estados[furier])\n\nj=0;\nk=input(\"Ingrese numero\");\nwhile j!=k:\n\tfurier=random.randrange(5)\n\tprint \"update aspirante set contra=\\\"\",\n\tprint anio(),\n\tprint\"\\\"\",\n\tprint\" where folio=\",\n\tprint j,\n\tprint \";\"\n\n\tj=j+1 \n\n" }, { "alpha_fraction": 0.6401433944702148, "alphanum_fraction": 0.64838707447052, "avg_line_length": 32.22618865966797, "blob_id": "a0641c9037fda2dbbb7e6ae563ba9fa880927cd0", "content_id": "1c04ee9911f4d151dd8e7752e192e41ededfc421", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2800, "license_type": "permissive", "max_line_length": 122, "num_lines": 84, "path": "/public_html/app/controlador/ControladorEmail.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ControladorEmail{\n\t\t//propiedades de la clase\n\t\tprivate $destinatario = array();\n\t\tprivate $asunto;\n\t\tprivate $mensaje;\n\t\tprivate $cabecera;\n\t\tprivate $tipoMensaje;\n\t\t/* Los tipos de mensajes serán:\n\t\t** 0: Registro de socios. Correo con datos como nombre, numero de socio, correo y contraseña al registrarse en el sitio.\n\t\t** 1: Reestablecimiento de contraseña. Correo con una nueva contraseña generada por el sistema.\n\t\t** 2: Notificacion de nuevo boletin. Correo con enlace de descarga del boletin para los socios que quieren recibirlo.\n\t\t** 3: Nuevo evento. Correo con información de un evento dado de alta en el sistema. \n\t\t*/\n\t\t\n\t\tpublic function __construct($destino, $tipoMsg){\n\t\t\t$this->destinatario[] = $destino;\n\t\t\t$this->tipoMensaje = $tipoMsg;\n\t\t\t\n\t\t\t$this->cabecera = \"MIME-Version: 1.0\".\"\\r\\n\";\n\t\t\t$this->cabecera.= \"Content-type: text/html; charset=utf-8\".\"\\r\\n\";\t\n\t\t\t$this->cabecera.= 'From: AAPT-MX<[email protected]>';\n\t\t}\n\t\t\n\t\tpublic function formarMensaje($datosAdicionales){\n\t\t\t$this->mensaje = '<html><body><img src=\"http://aapt-mx.org/web/img/bannerAaptMx.png\"><br>';\n\t\t\tswitch($this->tipoMensaje){\n\t\t\t\tcase 0: //Registro de socios.\n\t\t\t\t\t$this->asunto = \"Registro en AAPT-MX\";\n\t\t\t\t\t$this->mensaje.= \"<h2>Bienvenido a AAPT-MX</h2>\";\n\t\t\t\t\t$this->mensaje.= $datosAdicionales;\n\t\t\t\tbreak;\n\t\t\t\tcase 1: //Reestablecimiento de contraseña.\n\t\t\t\t\t$this->asunto = \"Reestablecimiento de contraseña en AAPT-MX\";\n\t\t\t\t\t$this->mensaje.= \"<h2>mensaje tipo 1</h2>\";\n\t\t\t\tbreak;\n\t\t\t\tcase 2: //Notificacion de nuevo boletin.\n\t\t\t\t\t$this->asunto = \"Nuevo número del boletín de AAPT-MX disponible\";\n\t\t\t\t\t$this->mensaje.= \"<h2>mensaje tipo 2</h2>\";\n\t\t\t\tbreak;\n\t\t\t\tcase 3: //Nuevo evento.\n\t\t\t\t\t$this->asunto = \"Nuevo evento registrado en AAPT-MX\";\n\t\t\t\t\t$this->mensaje.= \"<h2>mensaje tipo 3</h2>\";\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\techo \"ERROR NO hay nada que mandar<br>\";\n\t\t\t}\n\t\t\t$this->mensaje .= \"</html></body>\";\n\t\t}\n\t\t\n\t\tpublic function agregarDestinatario($email){\n\t\t\t$this->destinatario[] = $email;\n\t\t}\n\t\t\n\t\tpublic function enviarCorreo(){\n\t\t\t//echo \"Se enviará a: \".implode(\",\", $this->destinatario).\"<br>\";\n\t\t\treturn mail(implode(\",\", $this->destinatario), $this->asunto, $this->mensaje, $this->cabecera);\n\t\t}\n\t\t\n\t\tpublic function setAsunto($asunto){\n\t\t\t$this->asunto = $asunto;\n\t\t}\n\t\tpublic function setMensaje($msg){\n\t\t\t$this->mensaje = $msg;\t\n\t\t}\n\t\tpublic function setDestinatarios($destinatarios){ //Recibe un array de emails\n\t\t\t$this->destinatario = $destinatarios;\n\t\t}\n\t}\n\t\n\t/*echo \"Prueba\";\n\t$obj = new Correo(\"[email protected]\", 0);\n\t$obj->formarMensaje(\"Oscar David\");\n\t//$obj->setDestinatarios(array(\"[email protected]\",\"[email protected]\",\"[email protected]\"));\n\t$obj->agregarDestinatario(\"[email protected]\");\n\t$obj->agregarDestinatario(\"[email protected]\");\n\t$obj->enviarCorreo();\n\t\n\techo \"<pre>\";\n\tprint_r($obj);\n\techo \"</pre>\";\n\t\n\t*/\n?>" }, { "alpha_fraction": 0.5164813995361328, "alphanum_fraction": 0.5296855568885803, "avg_line_length": 28.00275421142578, "blob_id": "0c2dd34e3a7d90e7251f4e3a6ac4c260aa224cbb", "content_id": "3007a908d4fe048480856f15fac04878041d3e42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10533, "license_type": "permissive", "max_line_length": 405, "num_lines": 363, "path": "/datos.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nsession_start();\nif($_SESSION[\"acceso\"][5]==1 || $_SESSION[\"acceso\"][5]==2 || $_SESSION[\"acceso\"][5]==3 || $_SESSION[\"acceso\"][5]==4){\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n$sql=\"select distinct idpregunta from respuestaprofesor order by idpregunta;\";\n$result=mysqli_query($conexion,$sql);\n\n//obtengo el numero de profesores que contestaron la encuesta\n\n$sql2=\"select distinct id from respuestaprofesor;\";\n$result2=mysqli_query($conexion,$sql2);\n//genero n resulsets\n\n\n$profes=0;\necho $profes;\n?>\n\n\n<span style=\"font-style:italic;\"><!doctype html>\n\t<html lang=\"es\">\n\t\t<style>\n\t\t\tcanvas {\n\t\t\t\t-moz-user-select: none;\n\t\t\t\t-webkit-user-select: none;\n\t\t\t\t-ms-user-select: none;\n\t\t\t}\n\t\t</style>\n\t\t<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n\t\t<head>\n\t\t\t<?php require_once(\"controlador/verificar.php\");\n\t\t\trequire_once(\"controlador/connection.php\");\n\t\t\t?>\n\t\t\t<meta charset=\"utf-8\">\n\n\n\t\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t\t\t<script src=\"js/utils.js\"></script>\n\t\t\t<script src=\"js/Chart.bundle.js\"></script>\n\n\t\t\t<script\n\t\t\t\t\tsrc=\"https://code.jquery.com/jquery-3.2.1.min.js\"\n\t\t\t\t\tintegrity=\"sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=\"\n\t\t\t\t\tcrossorigin=\"anonymous\"></script>\n\t\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t\t\t<!-- links-->\n\t\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n\t\t\t<title>Grupo de investigación en la enseñanza de física</title>\n\t\t</head>\n\t\t<script>\n\t\t\t$(document).ready(function() {\n\n\n\t\t\t\t$('.modal').modal();\n\t\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t\t// Initialize collapsible (uncomment the line below if you use the dropdown variation)\n\t\t\t\t$('.collapsible').collapsible();\n\t\t\t\t$('select').material_select();\n\t\t\t});\n\n\n\t\t</script>\n\n\t\t<body>\n\n\t\t\t<?php\n\t\t\tinclude (\"barra.html\");\n\t\t\t?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"encabezados\" -->\n\t\t\t<div id='banner'>\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<header>\n\t\t\t\t\t\t<div class=\"col s12 m5 l6\">\n\t\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t\t<h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n\t\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"col s12 m6 l6\">\n\t\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</header>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\n\n\n\t\t\t<?php \n\t\t\tinclude(\"minibarra.php\");\n\t\t\t?>\n\n\t\n\t \n\t \n\t\n\t\t\t<!-- InstanceBeginEditable name=\"content\" -->\n\t\t\t<div class=\"container\">\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t<h2 style=\"color: black;\">Profesor <?php $sqlps=\"SELECT u.ApPaterno, u.ApMaterno,u.Nombre, U.Edad, u.Email, p.nombre as pais, i.nombre as institucion, a.nombre as area, n.nivel from usuario u, pais p, nivel n, institucion i, area a where u.IDPais=p.IDPais and u.IDInst=i.IDInst and u.idArea=a.IDArea and n.idNivel=u.idNivel and u.ID=\".$_SESSION[\"acceso\"][8].\";\"; $sth = mysqli_query($conexion,$sqlps);\n\t\t\t\t\twhile($REP=mysqli_fetch_array($sth)){\n\t\t\t\t\t\techo $REP[0] .\" \".$REP[1].\" \".$REP[2];\n $miau1=$REP[3];\n $miau2=$REP[4];\n $miau3=$REP[5];\n $miau4=$REP[6];\n $miau5=$REP[7];\n $miau6=$REP[8];\n\t\t\t\t\t}\n\t\t\t\t\t?> </h2>\n\t\t\t\t\t\n\t\t\t\t\t<!--Tabla de los usuarios-->\n\t\t\t <table>\n <thead>\n <tr>\n <th>Edad</th>\n <th>Email</th>\n <th>Pais</th>\n <th>Institución</th>\n <th>Area</th>\n <th>Nivel</th>\n </tr>\n </thead>\n\n <tbody>\n <tr>\n <td><?php echo $miau1; ?></td>\n <td><?php echo $miau2; ?></td>\n <td><?php echo $miau3; ?></td>\n <td><?php echo $miau4; ?></td>\n <td><?php echo $miau5; ?></td>\n <td><?php echo $miau6; ?></td>\n </tr>\n \n </tbody>\n </table>\n\t\t\t\t<div id=\"container\" style=\"width: 75%;\">\n\t\t\t\t\t<canvas id=\"canvas\" ></canvas>\n\t\t\t\t</div>\n\n\t\t\t\t\t<table class=\"highlight\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Pregunta</th>\n\t\t\t\t\t\t\t<th>Opini&oacute;n</th>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<?php\n\t\t\t\t\t\t$consulta=\"select b.idpregunta, b.Opinion FROM usuario a, respuestaprofesor b where a.ID=b.ID and b.ID=\".$_SESSION[\"acceso\"][8].\";\";\n\t\t\t\t\t\t$html=\"<tbody>\";\n\t\t\t\t\t\techo $html;\n\t\t\t\t\t\t$jack=mysqli_query($conexion,$consulta);\n\t\t\t\t\t\twhile($REP=mysqli_fetch_array($jack)){\n\t\t\t\t\t\t\t//$html+=\"<tr><td>\".$REP[0] .\" \".$REP[1].\" \".$REP[2].\"</td><td>\".$REP[3].\"<td></tr>\";\n\t\t\t\t\t\t\techo \"<tr><td>Pregunta \".$REP[0].\"</td><td>\".$REP[1].\"<td></tr>\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$html=\"</tbody>\";\n\t\t\t\t\t\techo $html;\n\t\t\t\t\t?>\n\t\t\t\t\t\n\t\t\t\t</table>\n\n\t\t\t<br>\n\t\t\t<div class=\"row\">\n\t\t\t\t<a class=\"waves-effect waves-light btn-large offset-s5 col s2\" id=\"btnback\">Volver</a>\n\t\t\t</div>\n\t\t\t<br>\n\t\t\t<br>\n\t\t\t</div>\n\t\t\t<footer>\n\t\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t\t<br>\n\t\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t\t<br>\n\t\t\t</footer>\n\t\t</body>\n\t\t<script>\n\t\t\t\n\t\t\t$(\"#btnback\").click(function(e) {\n\t\t\t\t//alert($(\"#desp2\").serialize());\n\n\t\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/asignaCuadro.php\",\n\t\t\t\tdata: $(\"#desp2\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\t\t\t\t\twindow.location.replace(\"administracionEncuesta.php\");\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t\t});\n\t\t</script>\n\t\t<script>\n\t\t\tvar ctx = document.getElementById(\"canvas\");\n\t\t\t\t\t\t\tvar MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\t\t\t\t\t\t\tvar color = Chart.helpers.color;\n\t\t\t\t\t\t\t/*var barChart = new Chart(ctx, {\n\t\t\t\ttype: 'bar',\n\t\t\t\tdata: {\n\t\t\t\t\tlabels: [\"Dog\", \"Cat\", \"Pangolin\"],\n\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\tbackgroundColor: '#00ff00',\n\t\t\t\t\t\tlabel: '# of Votes 2016',\n\t\t\t\t\t\tdata: [12, 19, 3]\n\t\t\t\t\t}]\n\t\t\t\t}\n\t\t\t});*/\n\t\t\t\t\t\t\tvar barChartData = new Chart(ctx, {\n\t\t\t\t\t\t\t\ttype:'bar',\n\t\t\t\t\t\t\t\tdata:{\n\t\t\t\t\t\t\t\t\tlabels: [\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\twhile($registros=mysqli_fetch_array($result)){\n\t\t\t\t\t\t\t\t\t\t?>\n\n\t\t\t\t\t\t\t\t\t\t'<?php echo $registros[0]; ?>',\n\t\t\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\t\t\t\t\tlabel: 'Dataset 1',\n\t\t\t\t\t\t\t\t\t\tbackgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),\n\t\t\t\t\t\t\t\t\t\tborderColor: window.chartColors.red,\n\t\t\t\t\t\t\t\t\t\tborderWidth: 1,\n\t\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t\t0,0\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t}]\n\n\t\t\t\t\t\t\t\t}});\n\n\t\t\t\t\t\t\t//un data set por cada profesor, cada dataset tiene las respuestas por pregunta\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t//while($registros2=mysqli_fetch_array($result2)){\n\t\t\t\t\t\t\t\t//ahora obtengo las respuestas\n\t\t\t\t\t\t\t\t$sql3=\"select rango from respuestaprofesor where id=\".$_SESSION[\"acceso\"][8].\" order by idpregunta;\";\n\t\t\t\t\t\t\t\t//echo $sql3;\n\t\t\t\t\t\t\t\t$result3=mysqli_query($conexion,$sql3);\n\t\t\t\t\t\t\t\t$sql4=\"select ApPaterno, ApMaterno, Nombre from usuario where id=\".$_SESSION[\"acceso\"][8].\";\";\n\t\t\t\t\t\t\t\t$result4=mysqli_query($conexion,$sql4);\n\t\t\t\t\t\t\t\twhile($registros4=mysqli_fetch_array($result4)){\n\t\t\t\t\t\t\t\t\t$nombre=$registros4[\"ApPaterno\"].\" \".$registros4[\"ApMaterno\"].\" \".$registros4[\"Nombre\"];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t?>\n\n\t\t\t\t\t\t\taddData(barChartData,'<?php echo $nombre; ?>', '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6), [\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\twhile($registro3=mysqli_fetch_array($result3)){\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t\t<?php echo $registro3[\"rango\"]?>,\n\t\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t\t]);\n\n\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t//}\n\t\t\t\t\t\t\t?>\n\n\n\n\n\t\t\t\t\t\t\twindow.onload = function() {\n\t\t\t\t\t\t\t\tvar ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n\t\t\t\t\t\t\t\twindow.myBar = new Chart(ctx, {\n\t\t\t\t\t\t\t\t\ttype: 'bar',\n\t\t\t\t\t\t\t\t\tdata: barChartData,\n\t\t\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\t\t\tresponsive: true,\n\t\t\t\t\t\t\t\t\t\tlegend: {\n\t\t\t\t\t\t\t\t\t\t\tposition: 'top',\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttitle: {\n\t\t\t\t\t\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\t\t\t\t\t\ttext: 'Chart.js Bar Chart'\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tdocument.getElementById('randomizeData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tvar zero = Math.random() < 0.2 ? true : false;\n\t\t\t\t\t\t\t\tbarChartData.datasets.forEach(function(dataset) {\n\t\t\t\t\t\t\t\t\tdataset.data = dataset.data.map(function() {\n\t\t\t\t\t\t\t\t\t\treturn zero ? 0.0 : randomScalingFactor();\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tvar colorNames = Object.keys(window.chartColors);\n\n\n\t\t\t\t\t\t\tdocument.getElementById('addData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tif (barChartData.datasets.length > 0) {\n\t\t\t\t\t\t\t\t\tvar month = MONTHS[barChartData.labels.length % MONTHS.length];\n\t\t\t\t\t\t\t\t\tbarChartData.labels.push(month);\n\n\t\t\t\t\t\t\t\t\tfor (var index = 0; index < barChartData.datasets.length; ++index) {\n\t\t\t\t\t\t\t\t\t\t//window.myBar.addData(randomScalingFactor(), index);\n\t\t\t\t\t\t\t\t\t\tbarChartData.datasets[index].data.push(randomScalingFactor());\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tdocument.getElementById('removeDataset').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tbarChartData.datasets.splice(0, 1);\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tdocument.getElementById('removeData').addEventListener('click', function() {\n\t\t\t\t\t\t\t\tbarChartData.labels.splice(-1, 1); // remove the label first\n\n\t\t\t\t\t\t\t\tbarChartData.datasets.forEach(function(dataset, datasetIndex) {\n\t\t\t\t\t\t\t\t\tdataset.data.pop();\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\twindow.myBar.update();\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tfunction addData(chart, label, color, data) {\n\t\t\t\t\t\t\t\tchart.data.datasets.push({\n\t\t\t\t\t\t\t\t\tlabel: label,\n\t\t\t\t\t\t\t\t\tbackgroundColor: color,\n\t\t\t\t\t\t\t\t\tdata: data\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tchart.update();\n\t\t\t\t\t\t\t}\n\t\t</script>\n\t\t<!-- InstanceEnd -->\n\n\t</html>\n\t<?php\n }\n else{\n echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n }\n\t?>\n</span>" }, { "alpha_fraction": 0.5972388982772827, "alphanum_fraction": 0.6017407178878784, "avg_line_length": 44.0405387878418, "blob_id": "7f1651c85f76d03487903fe5096eb6e8897d6d98", "content_id": "b1231008e47ba171956700c877d2d9c98b661219", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3333, "license_type": "permissive", "max_line_length": 156, "num_lines": 74, "path": "/public_html/index.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start(); //Debe de ir aqui de otra forma no funciona\n\t// Controlador frontal\n\t// index.php\n\t$directorio = __DIR__;\n\n\t// Carga de Beans\n\trequire_once __DIR__ . '/app/bean/Socio.php';\n\trequire_once __DIR__ . '/app/bean/Escuela.php';\n\trequire_once __DIR__ . '/app/bean/Institucion.php';\n\t\n\t// Carga de Modelos\n\trequire_once __DIR__ . '/app/Config.php';\n\trequire_once __DIR__ . '/app/Model.php';\n\trequire_once __DIR__ . '/app/modelo/Connection.php';\n\trequire_once __DIR__ . '/app/modelo/ModeloSocio.php';\n\trequire_once __DIR__ . '/app/modelo/ModeloEscuela.php';\n\trequire_once __DIR__ . '/app/modelo/ModeloInstitucion.php';\n\t\n\t// Carga de controladores\n\trequire_once __DIR__ . '/app/Controller.php';\n\trequire_once __DIR__ . '/app/controlador/ControladorSocio.php';\n\trequire_once __DIR__ . '/app/controlador/ControladorEscuela.php';\n\trequire_once __DIR__ . '/app/controlador/ControladorInstitucion.php';\n\trequire_once __DIR__ . '/app/controlador/ControladorEmail.php';\n\trequire_once __DIR__ . '/app/controlador/Sesion.php';\n\t\n\t\n\t// enrutamiento\n\t$map = array(\n\t\t'inicio' => array('controller' => 'Controller', 'action' => 'inicio'),\n\t\t'eventos' => array('controller' => 'Controller', 'action' => 'eventos'),\n\t\t'normatividad'=> array('controller' => 'Controller', 'action' => 'normas'),\n\t\t'boletin'\t => array('controller' => 'Controller', 'action' => 'mostrarBoletines'),\n 'material'\t => array('controller' => 'Controller', 'action' => 'materialDidactico'),\n\t\t'registroSoc' => array('controller' => 'ControladorSocio', 'action' => 'registroSocio'),\n\t\t'registroCom' => array('controller' => 'ControladorSocio', 'action' => 'registroCompletado'),\n\t\t'login' => array('controller' => 'ControladorSocio', 'action' => 'iniciarSesion'),\n\t\t'logout' => array('controller' => 'ControladorSocio', 'action' => 'cerrarSesion'),\n\t\t'mostrarEsc' => array('controller' => 'ControladorEscuela', 'action' => 'mostrarEscuela'), //Sirve para listar todo y hacer busquedas por nombre\n\t\t'registroEsc' => array('controller' => 'ControladorEscuela', 'action' => 'registroEscuela'),\n\t\t'registroIns' => array('controller' => 'ControladorInstitucion', 'action' => 'registroInstitucion'), //Sirve para listar todo y hacer busquedas por nombre\n\t\t'mostrarIns' => array('controller' => 'ControladorInstitucion', 'action' => 'mostrarInstitucion')\n );\n\n // Parseo de la ruta\n if (isset($_GET['ctl'])) {\n if (isset($map[$_GET['ctl']])) {\n $ruta = $_GET['ctl'];\n } else {\n header('Status: 404 Not Found');\n echo '<html><body><h1>Error 404: No existe la ruta <i>' .\n $_GET['ctl'] .\n '</p></body></html>';\n exit;\n }\n } else {\n $ruta = 'inicio';\n }\n\n $controlador = $map[$ruta];\n // Ejecución del controlador asociado a la ruta\n\n if (method_exists($controlador['controller'],$controlador['action'])) {\n call_user_func(array(new $controlador['controller'], $controlador['action']), $directorio);\n } else {\n\n header('Status: 404 Not Found');\n echo '<html><body><h1>Error 404: El controlador <i>' .\n $controlador['controller'] .\n '->' .\n $controlador['action'] .\n '</i> no existe</h1></body></html>';\n }" }, { "alpha_fraction": 0.5406150221824646, "alphanum_fraction": 0.5533797740936279, "avg_line_length": 34.90625, "blob_id": "1f991e78b75778e8a3ec534989ed79a686df34b0", "content_id": "ee3901d8ad6475829fa1ad72fc258a71cc866e1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6910, "license_type": "permissive", "max_line_length": 168, "num_lines": 192, "path": "/public_html/app/templates/layout.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html class=\"\"><head>\n<meta charset=\"utf-8\">\n<title>AAPT | México</title>\n<link type=\"text/css\" rel=\"stylesheet\" href=\"app/templates/css/materialize.css\" media=\"screen,projection\" />\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js\"></script>\n\n<link rel=\"stylesheet\" href=\"web/css/estilo.css\" media=\"all\"> \n<link rel=\"stylesheet\" href=\"web/css/iconos.css\" media=\"all\"> \n<link rel=\"stylesheet\" href=\"web/css/popup.css\" media=\"all\">\n<link rel=\"shortcut icon\" href=\"web/img/aaptmx.ico\">\n<script type=\"text/javascript\" src=\"web/js/validaciones.js\"></script>\n\n<!-- Insert to your webpage before the </head> -->\n\n<script src=\"app/templates/carouselengine/amazingcarousel.js\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"app/templates/carouselengine/initcarousel-1.css\">\n<script src=\"app/templates/carouselengine/initcarousel-1.js\"></script>\n<!-- End of head section HTML codes -->\n\n<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\n\n\n\n\n</head>\n<script>\n\t$(document).ready(function() {\n\t\t\t// Show or hide the sticky footer button\n\t\t\t$(window).scroll(function() {\n\t\t\t\tif ($(this).scrollTop() > 200) {\n\t\t\t\t\t$('.go-top').fadeIn(200);\n\t\t\t\t} else {\n\t\t\t\t\t$('.go-top').fadeOut(200);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Animate the scroll to top\n\t\t\t$('.go-top').click(function(event) {\n\t\t\t\tevent.preventDefault();\n\n\t\t\t\t$('html, body').animate({scrollTop: 0}, 300);\n\t\t\t})\n\t\t});\n\t</script>\n\t\n\t<body>\n\t\t<nav class=\"Columnas\">\n\t\t\t<div class=\"nav-wrapper\">\n\t\t\t\t<ul id=\"menu\" id=\"nav-mobile\" class=\"right hide-on-med-and-down\" style=\"display:inherit !important;\">\n\t\t\t\t\t<li><a class=\"active\" href=\"index.php\">Inicio</a></li>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#eventosYavisos\">Eventos</a>\t \n\t\t\t\t\t\t<ul class=\"children\">\n\t\t\t\t\t\t\t<li><a href=\"#\">Pasados</a></li>\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t</li>\n\t\t\t\t\t<li><a href=\"index.php?ctl=normatividad\">Normatividad</a></li>\n\t\t\t\t\t\n\t\t\t\t\t<?php\n\t\t\t\t\t$sesion = new Sesion();\n\t\t\t\t\t$usuario = $sesion->getSesion('login');\n\n\t\t\t\t\tif($usuario == false){?>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#modal1\">Boletin</a>\n\t\t\t\t\t</li>\n\t\t\t\t\t<li><a href=\"index.php#Login\">Inicia Sesión</a></li>\n\n\t\t\t\t\t<?php }\telse{ \n\t\t\t\t\t\t$socio = $sesion->getSesion('socio');\n\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"index.php?ctl=boletin\">Boletin</a>\n\t\t\t\t\t\t</li>\n\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t<a href=\"index.php?ctl=material\">Material Didáctico</a> \n\n\t\t\t\t\t\t</li>\n\t\t\t\t\t\t<li style=\"width: 43px; text-align: right;\"><img class=\"perfil\" src=\"app/templates/css/imagenes/perfil.png\"></li>\n\t\t\t\t\t\t<li><a href=\"\"> <?php echo $socio->getPrefijo().' '.$socio->getNombreCompleto(); ?></a>\n\t\t\t\t\t\t\t<ul class=\"children\">\n\t\t\t\t\t\t\t\t<li><a href=\"index.php?ctl=logout\">Cerrar Sesión</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</li>\n\t\t\t\t\t\t<?php }\t?>\n\t\t\t\t\t</ul>\n\t\t\t\t</div>\n\t\t\t</nav>\n\n\t\t\t<header>\n\t\t\t\t<div class=\"slider\">\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li><a href=\"#\"><img src=\"web/img/bannerAaptMx.png\" alt=\"\"></a></li>\n\t\t\t\t\t\t<li><a href=\"#\"><img src=\"web/img/bannerAaptMx2.png\" alt=\"\"></a></li>\n\t\t\t\t\t\t<li><a href=\"#\"><img src=\"web/img/bannerAaptMx3.png\" alt=\"\"></a></li>\n\t\t\t\t\t\t<li><a href=\"#\"><img src=\"web/img/bannerAaptMx4.png\" alt=\"\"></a></li> \n\n\t\t\t\t\t</ul>\n\t\t\t\t</div>\n\t\t\t</header>\n\n\t\t\t<div id=\"contenido\">\n\n\t\t\t\t<!-- Aqui va el contenido del contenedor blanco-->\n\t\t\t\t<?php echo $contenido ?>\t\t\n\n\n\t\t\t\t<div id=\"eventosYavisos\">\n\t\t\t\t\t<div class=\"Columnas\"> \t\n\t\t\t\t\t\t<div class=\"columna2\">\n\t\t\t\t\t\t\t<h3>Proximos Eventos</h3>\n\t\t\t\t\t\t\t<div id=\"eventos\">\n\t\t\t\t\t\t\t\t<!-- --------------------EJEMPLO BLOQUE DE EVENTO-------------------------->\n\t\t\t\t\t\t\t\t<div class=\"Columnas\">\n\t\t\t\t\t\t\t\t\t<div class=\"calendarE\">\n\t\t\t\t\t\t\t\t\t\t<img src=\"web/img/calendar146.png\" class=\"centrado\">\n\t\t\t\t\t\t\t\t\t\t<p class=\"fecha\">17-18/Nov/2016</p>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<aside class=\"evento\">\n\t\t\t\t\t\t\t\t\t\t<p class=\"negritas\">Reunión Anual AAPT-MX 2016</p>\n\t\t\t\t\t\t\t\t\t\t<p>El evento se llevará acabo en el Centro de Educación Continua Unidad Cancún IPN. <a href=\"index.php?ctl=eventos\">Más información.</a></p>\n\t\t\t\t\t\t\t\t\t</aside>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<hr>\n\t\t\t\t\t\t\t\t<!-- ----------------------------------------------------------------- --> \n\t\t\t\t\t\t\t</div> \n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"columna2\">\n\t\t\t\t\t\t\t<h3>Avisos</h3>\n\t\t\t\t\t\t\t<div id=\"avisos\">\n\t\t\t\t\t\t\t\t<!-- ------------------------EJEMPLO BLOQUE AVISO------------------> \n\t\t\t\t\t\t\t\t<aside>\n\t\t\t\t\t\t\t\t\t<aside>\n\t\t\t\t\t\t\t\t\t\t<p class=\"negritas\"><span class=\"icon-announcement\"></span>Nuevo sitio WEB.</p>\n\t\t\t\t\t\t\t\t\t\t<p class=\"fechaAviso\">05/Septiembre/2016</p>\n\t\t\t\t\t\t\t\t\t\t<p>Les informamos que la fecha de recepción de trabajos ha sido extendida al día martes 20 de septiembre.<br>\n\t\t\t\t\t\t\t\t\t\t\tA todos aquellos que realizaron este proceso en la primera fecha estipulada (31 de agosto), recibirán el veredicto de su trabajo para el 7 de septiembre.</p>\n\t\t\t\t\t\t\t\t\t\t</aside>\n\t\t\t\t\t\t\t\t\t</aside>\n\t\t\t\t\t\t\t\t\t<hr>\n\t\t\t\t\t\t\t\t\t<!-- ---------------------------------------------------------- --> \n\n\n\t\t\t\t\t\t\t\t</div> \n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div> \n\t\t\t\t\t</div>\n\t\t\t\t</div> <!-- Terminacion div eventos-->\n\t\t\t\t<footer>\n\t\t\t\t\t<div class=\"Columnas\">\n\t\t\t\t\t\t<aside class=\"columna2\">\n\t\t\t\t\t\t\t<img class=\"social\" alt=\"YouTube\" src=\"web/img/youtube30.png\">\n\t\t\t\t\t\t\t<a href=\"https://www.facebook.com/AAPTMX\" target=\"_blank\"><img class=\"social\" alt=\"Facebook\" src=\"web/img/logotype15.png\"></a>\n\t\t\t\t\t\t</aside>\n\t\t\t\t\t\t<aside id=\"formContacto\" class=\"columna2\" style=\"min-height:350px\">\n\t\t\t\t\t\t\t<form method=\"post\" action=\"#\" name=\"contacto\" id=\"contacto\">\n\t\t\t\t\t\t\t\t<h2>Contacto Directo</h2>\n\t\t\t\t\t\t\t\t<input name=\"nombre\" placeholder=\"Su nombre...\" size=\"27\" maxlength=\"50\" required type=\"text\">\n\t\t\t\t\t\t\t\t<input name=\"email\" placeholder=\"Su email...\" size=\"27\" maxlength=\"50\" required type=\"email\">\n\t\t\t\t\t\t\t\t<p></p>\n\t\t\t\t\t\t\t\t<textarea name=\"mensaje\" rows=\"5\" placeholder=\"Escriba aquí su mensaje...\" required></textarea> <!-- Debe ir en una sola linea o no furula -->\n\t\t\t\t\t\t\t\t<input name=\"btnEnviar\" value=\"Enviar\" class=\"btn\" type=\"submit\">\n\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t</aside>\n\t\t\t\t\t</div>\n\t\t\t\t\t<hr>\n\t\t\t\t\t<span class=\"copy\"><br>Copyright © 2016 - Todos los derechos reservados. | Desarrollado por: RAM© <br><br></span>\n\t\t\t\t</footer>\n\n\n\t\t\t\t<div id=\"modal1\" class=\"modal\">\n\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t<h4>Acceso Restringido</h4>\n\t\t\t\t\t\t<p>Para poder ver nuestro bolet&iacute;n debe iniciar sesi&oacute;n</p>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t\t<a href=\"#!\" class=\"modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t</body></html>\n\n\t\t\t<script type=\"text/javascript\">\n\t\t\t\t $(document).ready(function(){\n\t\t\t\t // the \"href\" attribute of .modal-trigger must specify the modal ID that wants to be triggered\n\t\t\t\t $('.modal').modal();\n\t\t\t\t });\n\t\t\t</script>\n" }, { "alpha_fraction": 0.633728563785553, "alphanum_fraction": 0.633728563785553, "avg_line_length": 18.63793182373047, "blob_id": "7a373c1d19605e7faf16c6ad6ff753b1b031db92", "content_id": "173d4e46512365942595380f5da1c488de6e3317", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2277, "license_type": "permissive", "max_line_length": 137, "num_lines": 116, "path": "/public_html/app/bean/Evento.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\t\n\tclass Evento\n\t{\n\t\t//Atributos\n\t\tprivate $idEvento;\n\t\tprivate $nombreEvento;\n\t\tprivate $fechaInicio;\n\t\tprivate $fechaFin;\n\t\tprivate $sede;\n\t\tprivate $direccion;\n\t\tprivate $cartel;\n\t\tprivate $bases;\n\t\tprivate $hoteles;\n\t\tprivate $contacto;\n\t\t\n\t\tpublic function __construct($idEvento, $nombreEvento, $fechaInicio, $fechaFin, $sede, $direccion, $cartel, $bases, $hoteles, $contacto)\n\t\t{\n\t\t\t\t$this->idEvento =$idEvento;\n\t\t\t\t$this-> nombreEvento =$nombreEvento;\n\t\t\t\t$this->fechaInicio =$fechaInicio;\n\t\t\t\t$this-> fechaFin =$fechaFin;\n\t\t\t\t$this-> sede =$sede;\n\t\t\t\t$this-> direccion =$direccion;\n\t\t\t\t$this-> cartel=$cartel;\n\t\t\t\t$this-> bases =$bases;\n\t\t\t\t$this-> hoteles =$hoteles;\n\t\t\t\t$this-> contacto =$contacto;\n\t\t\t\t\n\t\t}\n\t\t\n\t\t//Metodos getters\n\t\tpublic function getIdEvento(){\n\t\t\treturn $this->idEvento;\n\t\t}\n\t\t\n\t\tpublic function getNombreEvento (){\n\t\t\treturn $this-> nombreEvento;\n\t\t}\n\t\t\n\t\tpublic function getFechaInicio (){\n\t\t\treturn $this-> fechaInicio;\n\t\t}\n\t\t\n\t\tpublic function getFechaFin (){\n\t\t\treturn $this-> fechaFin;\n\t\t}\n\t\t\n\t\tpublic function getSede (){\n\t\t\treturn $this->sede;\n\t\t}\n\t\t\n\t\tpublic function getDireccion (){\n\t\t\treturn $this->direccion ;\n\t\t}\n\t\t\n\t\tpublic function getCartel (){\n\t\t\treturn $this-> cartel;\n\t\t}\n\t\t\n\t\tpublic function getBases (){\n\t\t\treturn $this-> bases;\n\t\t}\n\n\t\tpublic function getHoteles (){\n\t\t\treturn $this->hoteles ;\n\t\t}\n\n\t\tpublic function getContacto (){\n\t\t\treturn $this-> contacto;\n\t\t}\n\n\t\t//Metodos setters\n\t\tpublic function setIdEvento($idEvento){\n\t\t\t$this -> idEvento = $idEvento;\n\t\t}\n\t\t\n\t\tpublic function setNombreEvento($nombreEvento){\n\t\t\t$this -> nombreEvento = $nombreEvento;\n\t\t}\n\t\t\n\t\tpublic function setFechaInicio($fechaInicio){\n\t\t\t$this -> fechaInicio = $fechaInicio;\n\t\t}\n\t\t\n\t\tpublic function setFechaFin($fechaFin){\n\t\t\t$this -> fechaFin = $fechaFin;\n\t\t}\n\t\t\n\t\tpublic function setSede($sede){\n\t\t\t$this -> sede = $sede;\n\t\t}\n\t\t\n\t\tpublic function setDireccion($direccion){\n\t\t\t$this -> direccion = $direccion;\n\t\t}\n\t\t\n\t\tpublic function setCatel($cartel){\n\t\t\t$this -> cartel = $cartel;\n\t\t}\n\t\t\n\t\tpublic function setBases($bases){\n\t\t\t$this -> bases= $bases;\n\t\t}\n\t\t\n\t\tpublic function setHoteles($hoteles){\n\t\t\t$this -> hoteles = $hoteles;\n\t\t}\n\t\t\n\t\tpublic function setContacto($contacto){\n\t\t\t$this -> contacto = $contacto;\n\t\t}\n\t\n\t}\n\t\n?>" }, { "alpha_fraction": 0.652830183506012, "alphanum_fraction": 0.652830183506012, "avg_line_length": 17.946428298950195, "blob_id": "a089c3fa7ac3d274321f1fcb133bc5db3f7aa84d", "content_id": "923ba7e3c5edb241305138eeffb09442e518eabc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 78, "num_lines": 56, "path": "/public_html/app/bean/Escuela.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\t\n\tclass Escuela\n\t{\n\t\t//Atributos\n\t\tprivate $idEscuela;\n\t\tprivate $nombre;\n\t\tprivate $direccion;\n\t\tprivate $idInstitucion;\n\t\t\n\t\t//Constructor\n\t\tpublic function __construct($idEscuela, $nombre, $direccion, $idInstitucion)\n\t\t{\n\t\t\t$this->idEscuela =$idEscuela;\n\t\t\t$this->nombre =$nombre;\n\t\t\t$this->direccion =$direccion;\n\t\t\t$this->idInstitucion =$idInstitucion;\t\n\t\t}\n\t\t\n\t\t//Metodos getters\n\t\t\n\t\tpublic function getIdEscuela (){\n\t\t\treturn $this->idEscuela ;\n\t\t}\n\t\t\n\t\tpublic function getNombre (){\n\t\t\treturn $this-> nombre;\n\t\t}\n\t\t\n\t\tpublic function getDireccion (){\n\t\t\treturn $this-> direccion;\n\t\t}\n\t\t\t\n\t\tpublic function getIdInstitucion (){\n\t\t\treturn $this-> idInstitucion;\n\t\t}\n\t\t\n\t\t//Metodos setters\n\t\tpublic function setIdEscuela ($idEscuela){\n\t\t\t$this-> idEscuela = $idEscuela;\n\t\t}\n\t\t\n\t\tpublic function setNombre($nombre){\n\t\t\t$this-> nombre = $nombre;\n\t\t}\n\t\t\n\t\tpublic function setDireccion ($direccion){\n\t\t\t$this-> direccion = $direccion;\n\t\t}\n\t\t\n\t\tpublic function setIdInstitucion ($idInstitucion){\n\t\t\t$this->idInstitucion = $idInstitucion;\n\t\t}\n\t\t\n\t}\n?>" }, { "alpha_fraction": 0.5439189076423645, "alphanum_fraction": 0.5472972989082336, "avg_line_length": 33.19230651855469, "blob_id": "c1fc6072e9a73fb2bbbe56afc17210347f63b8cd", "content_id": "b06341d16f9e5733a235a730df1c91bb416d83ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 890, "license_type": "permissive", "max_line_length": 198, "num_lines": 26, "path": "/public_html/app/templates/mostrarEscuelas.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<h2>Escuelas</h2>\n<table border=\"1\">\n\t<tr>\n \t<th>Nombre</th>\n <th>Institución</th>\n <th>Direccion</th>\n <th></th>\n\t</tr>\n <?php foreach ($parametros['escuelas'] as $school) :?>\n <tr>\n <td><?php echo $school['nombre'] ?></td>\n <td><?php echo $school['idInstitucion'] ?></td>\n <td><?php echo $school['direccion']?></td>\n <td><a href=\"index.php?ctl=registroCom&mem=<?php echo $_GET['mem']?>&idEsc=<?php echo $school['idEscuela']?>\">\n Seleccionar</a></td>\n </tr>\n <?php endforeach; ?>\n\n</table>\n<br>\n<p> *Si no encuentras la escuela a la que perteneces puedes registrarla presionando clic <a href=\"index.php?ctl=registroEsc&idIns=<?php echo $_GET['idIns']?>&mem=<?php echo $_GET['mem']?>\">aquí</a>.\n\n<?php $contenido .= ob_get_clean(); ?>\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.5196506381034851, "alphanum_fraction": 0.5389893651008606, "avg_line_length": 19.55128288269043, "blob_id": "b123600cdad1aecfa2f3bbe725be2eed48ce4fcc", "content_id": "19ef0125561b795e6ad467142a1c9a4affff24dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1603, "license_type": "permissive", "max_line_length": 206, "num_lines": 78, "path": "/controlador/Modificar.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire_once(\"./connection.php\");\n\trequire_once(\"./BeanUsuario.php\");\n\t//Conexion a la BD//\n\t$conexion = new connection();\n\n\t//Obtencion de datos del formulario\n\tsession_start();\n\t$usuario = $_SESSION[\"login\"];\n $usuario = unserialize($usuario);\n\t$idUsuario=$usuario->getId();\n\t$nombre = $_POST['txtNombre'];\n\t$nombre.=\" \".$_POST['txtApPat'];\n\t$nombre.=\" \".$_POST['txtApMat'];\n\t$fechaN = $_POST['txtFechaNac'];\n\t$ocup = $_POST['txtOcupacion'];\n\t$inst = $_POST['txtInstitucion'];\n\t$genero = $_POST['genero'];\n\t$email = $_POST['txtEmail'];\n\t$email2 = $_POST['txtEmail2'];\n\t\n\t\n\t$mes=implode( array ($fechaN));\n\t$separado=explode(\" \",$mes);\n\t\n\t$fechaN=$separado[2].\"-\";\n\tswitch($separado[1]){\n\t\t\tcase \"January,\":\n\t\t\t\t$m=\"01\";\n\t\t\t\tbreak;\n\t\t\tcase \"February,\":\n\t\t\t\t$m=\"02\";\n\t\t\t\tbreak;\n\t\t\tcase \"March,\":\n\t\t\t\t$m=\"03\";\n\t\t\t\tbreak;\n\t\t\tcase \"April,\":\n\t\t\t\t$m=\"04\";\n\t\t\t\tbreak;\n\t\t\tcase \"May,\":\n\t\t\t\t$m=\"05\";\n\t\t\t\tbreak;\n\t\t\tcase \"June,\":\n\t\t\t\t$m=\"06\";\n\t\t\t\tbreak;\n\t\t\tcase \"July,\":\n\t\t\t\t$m=\"07\";\n\t\t\t\tbreak;\n\t\t\tcase \"August,\":\n\t\t\t\t$m=\"08\";\n\t\t\t\tbreak;\n\t\t\tcase \"September,\":\n\t\t\t\t$m=\"09\";\n\t\t\t\tbreak;\n\t\t\tcase \"October,\":\n\t\t\t\t$m=\"10\";\n\t\t\t\tbreak;\n\t\t\tcase \"November,\":\n\t\t\t\t$m=\"11\";\n\t\t\t\tbreak;\n\t\t\tcase \"December,\":\n\t\t\t\t$m=\"12\";\n\t\t\t\tbreak;\n\t}\n\t$fechaN.=$m.\"-\".$separado[0];\n\t//echo $fechaN;\n\n\t//$p=md5($password);\n\t$query = \"update usuario set nombre=\\\"\".$nombre.\"\\\", fechaNac=\\\"\".$fechaN.\"\\\", sex=\\\"\".$genero.\"\\\", ocupacion=\\\"\".$ocup.\"\\\", institucion= \\\"\".$inst.\"\\\", email=\\\"\".$email.\"\\\" where idUsuario = \".$idUsuario;\n\t\n\t\n\t\t$conexion->conectar();\n\t\t$conexion->myQuery($query);\n\t\t$conexion->desconectar();\n\t\techo 1;\t\n\t\n\t\n?>\n" }, { "alpha_fraction": 0.500920832157135, "alphanum_fraction": 0.5199508666992188, "avg_line_length": 36.906978607177734, "blob_id": "fa0a5dd994ec9f461bc77ebc54659327e663d22d", "content_id": "c7351ce7ed7b454bbb07e39fdaabd98eabccb338", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1701, "license_type": "permissive", "max_line_length": 222, "num_lines": 43, "path": "/controlador/opinionGeneral.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t$_SESSION[\"acceso\"][10]=normaliza($_POST[\"text1\"]);\n\t$_SESSION[\"acceso\"][11]=normaliza($_POST[\"text2\"]);\n\t$_SESSION[\"acceso\"][12]=normaliza($_POST[\"text3\"]);\n\t$_SESSION[\"acceso\"][13]=normaliza($_POST[\"text4\"]);\n\t$_SESSION[\"acceso\"][14]=normaliza($_POST[\"text5\"]);\n\t$_SESSION[\"acceso\"][15]=normaliza($_POST[\"text6\"]);\n \n \n\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$sql=\" \";\n\tfor($x=0; $x<6; $x++){\n\t\t\n\t\t$sqlp=\"select * from opinionGeneral where id=\".$_SESSION[\"acceso\"][6].\" and orden=\".$x.\";\";\n\t\techo $sqlp;\n\t\t$paises=mysqli_query($conexion,$sqlp);\n\t\t$y=0;\n\t\t while($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t\t $y++;\n\t\t }\n\t\tif($y==0){\n\t\t\t$sql=\"insert into opinionGeneral values(\".$_SESSION[\"acceso\"][6].\", \".$x.\",'\".$_SESSION[\"acceso\"][10+$x].\"');\";\n\t\t\t$paises=mysqli_query($conexion,$sql);\n\t\t}\n\t\telse{\n\t\t\t$sql=\"update opinionGeneral set texto='\".$_SESSION[\"acceso\"][10+$x].\"' where id=\".$_SESSION[\"acceso\"][6].\" and orden=\".$x.\";\";\n\t\t\t$paises=mysqli_query($conexion,$sql);\n\t\t}\n\t\t\n\t\t\n\t}\n \n\n\n function normaliza($cadena) {\n$no_permitidas= array (\"á\",\"é\",\"í\",\"ó\",\"ú\",\"Á\",\"É\",\"Í\",\"Ó\",\"Ú\",\"ñ\",\"À\",\"Ã\",\"Ì\",\"Ò\",\"Ù\",\"Ù\",\"à \",\"è\",\"ì\",\"ò\",\"ù\",\"ç\",\"Ç\",\"â\",\"ê\",\"î\",\"ô\",\"û\",\"Â\",\"Ê\",\"ÃŽ\",\"Ô\",\"Û\",\"ü\",\"ö\",\"Ö\",\"ï\",\"ä\",\"«\",\"Ò\",\"Ï\",\"Ä\",\"Ë\");\n$permitidas= array (\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\",\"n\",\"N\",\"A\",\"E\",\"I\",\"O\",\"U\",\"a\",\"e\",\"i\",\"o\",\"u\",\"c\",\"C\",\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\",\"u\",\"o\",\"O\",\"i\",\"a\",\"e\",\"U\",\"I\",\"A\",\"E\");\n$texto = str_replace($no_permitidas, $permitidas ,$cadena);\nreturn $texto;\n}\n?>" }, { "alpha_fraction": 0.5452274084091187, "alphanum_fraction": 0.553723156452179, "avg_line_length": 43.488887786865234, "blob_id": "fb30318eda8de1ab442ff7b48eac0e3a49952890", "content_id": "946ec1df4a9098ec3ed21645915694a7db9bcea1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2073, "license_type": "permissive", "max_line_length": 229, "num_lines": 45, "path": "/controlador/registraRespuestaProfesor.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t//printArray($_POST);\n\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$opinion=normaliza($_POST[\"opinion\"]);\n\t$rango=$_POST[\"fader_\"];\n\t//contamos el numero de respuestas que ya existen para esa pregeunta\n\t$sqlp=\"select * from respuestaProfesor where IDPregunta=\".$_SESSION[\"acceso\"][7].\" and ID=\".$_SESSION[\"acceso\"][6].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t$x=0;\n\t while($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t $x++;\n\t }\n\tif($x==0){\n\t\t$sqlp=\"insert into respuestaProfesor (ID,IDPregunta,Opinion,Rango) values(\".$_SESSION[\"acceso\"][6].\",\".$_SESSION[\"acceso\"][7].\",'\".$opinion.\"',\".$rango.\");\";\n\t\t$paises=mysqli_query($conexion,$sqlp);\n \n\t\t\n\t}\n\telse{\n\t\t$sqlp=\"update respuestaProfesor set ID=\".$_SESSION[\"acceso\"][6].\", IDPregunta=\".$_SESSION[\"acceso\"][7].\", Opinion='\".$opinion.\"', Rango=\".$rango.\" where IDPregunta=\".$_SESSION[\"acceso\"][7].\" and ID=\".$_SESSION[\"acceso\"][6].\";\";\n\t\t$paises=mysqli_query($conexion,$sqlp);\n \n\t}\n\t\n\t$sqlp=\"update usuario set ultimapregunta=\".$_SESSION[\"acceso\"][7].\" where id=\".$_SESSION[\"acceso\"][6].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t$_SESSION[\"acceso\"][7]=$_SESSION[\"acceso\"][7]+1;\n\n\tfunction printArray($array){\n foreach ($array as $key => $value){\n echo \"$key => $value\";\n if(is_array($value)){ //If $value is an array, print it as well!\n printArray($value);\n } \n } \n}\nfunction normaliza($cadena) {\n$no_permitidas= array (\"á\",\"é\",\"í\",\"ó\",\"ú\",\"Á\",\"É\",\"Í\",\"Ó\",\"Ú\",\"ñ\",\"À\",\"Ã\",\"Ì\",\"Ò\",\"Ù\",\"Ù\",\"à \",\"è\",\"ì\",\"ò\",\"ù\",\"ç\",\"Ç\",\"â\",\"ê\",\"î\",\"ô\",\"û\",\"Â\",\"Ê\",\"ÃŽ\",\"Ô\",\"Û\",\"ü\",\"ö\",\"Ö\",\"ï\",\"ä\",\"«\",\"Ò\",\"Ï\",\"Ä\",\"Ë\");\n$permitidas= array (\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\",\"n\",\"N\",\"A\",\"E\",\"I\",\"O\",\"U\",\"a\",\"e\",\"i\",\"o\",\"u\",\"c\",\"C\",\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\",\"u\",\"o\",\"O\",\"i\",\"a\",\"e\",\"U\",\"I\",\"A\",\"E\");\n$texto = str_replace($no_permitidas, $permitidas ,$cadena);\nreturn $texto;\n}\n?>" }, { "alpha_fraction": 0.5823017954826355, "alphanum_fraction": 0.5838820338249207, "avg_line_length": 35.17142868041992, "blob_id": "804d9fc2de42adbeef9c2bbe7ce9e58b80231c8b", "content_id": "1c64276f4bcae1cdd25738b6fa698644f368f56c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3798, "license_type": "permissive", "max_line_length": 304, "num_lines": 105, "path": "/public_html/app/controlador/ControladorSocio.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ControladorSocio{\n\t\tpublic function registroSocio($dir){\n\t\t\t$parametros = array(\n\t\t\t\t'noMembresia' => '',\n\t\t\t\t'nombreCompleto' => '',\n\t\t\t\t'prefijo' => '',\n\t\t\t\t'email' => '',\n\t\t\t\t'estudProf' => '',\n\t\t\t\t'niClase' => '',\n\t\t\t\t'avisoBoletin' => '',\n\t\t\t\t'password' => '',\n\t\t\t\t'idEscuela' => '',\n\t\t\t\t'idTrabajo' => ''\n\t\t\t);\n\t\t\t\n\t\t\t$modSocio = new ModeloSocio();\n\t\t\t\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t//Creacion del beanSocio\n\t\t\t\t$socio = new Socio(0, htmlspecialchars($_POST['txtNombre']), htmlspecialchars($_POST['cboPrefijo']), htmlspecialchars($_POST['txtEmail']), htmlspecialchars($_POST['cboEstudiante']), htmlspecialchars($_POST['cboNivel']), htmlspecialchars($_POST['cboAviso']), htmlspecialchars($_POST['txtPass']), 0,0);\n\t\t\t\t//echo '<pre>';\n\t\t\t\t//print_r($socio);\n\t\t\t\t//echo '</pre>';\n\t\t\t\t// comprobar campos formulario\n\t\t\t\tif ($modSocio->validarDatosSocio($socio)){\n\t\t\t\t\t$modSocio->insertarSocio($socio);\n\t\t\t\t\t$socio = $modSocio->buscarPorEmail($socio->getEmail());\n\t\t\t\t\t$url = 'index.php?ctl=mostrarIns&mem='.$socio->getNoMembresia().'#RegistroP2';\n\t\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\telse {\n\t\t\t\t\t$parametros = array(\n\t\t\t\t\t\t'noMembresia' => '',\n\t\t\t\t\t\t'nombreCompleto' => htmlspecialchars($_POST['txtNombre']),\n\t\t\t\t\t\t'prefijo' => htmlspecialchars($_POST['cboPrefijo']),\n\t\t\t\t\t\t'email' => htmlspecialchars($_POST['txtEmail']),\n\t\t\t\t\t\t'estudProf' => htmlspecialchars($_POST['cboEstudiante']),\n\t\t\t\t\t\t'niClase' => htmlspecialchars($_POST['cboNivel']),\n\t\t\t\t\t\t'avisoBoletin' => htmlspecialchars($_POST['cboAviso']),\n\t\t\t\t\t\t'password' => htmlspecialchars($_POST['txtPass']),\n\t\t\t\t\t\t'idEscuela' => '',\n\t\t\t\t\t\t'idTrabajo' => ''\n\t\t\t\t\t);\n\t\t\t\t\t$parametros['mensaje'] = 'Alguno de los datos es incorrecto. Favor de revisar el formulario.';\n\t\t\t\t}\n\t\t\t}\n\t\t\trequire $dir.'/app/templates/inicio.php'; // <----------------------------------------REVISAR ESTA LINEA\n\t\t}\n\t\t\n\t\tpublic function registroCompletado(){\n\t\t\tif(isset($_POST['mem'], $_POST['idEsc'])){\n\t\t\t\t$modSocio = new ModeloSocio();\n\t\t\t\t$modSocio->actualizarEscuela($_POST['mem'], $_POST['idEsc']);\n\t\t\t\t$socio = $modSocio->buscarPorNoMem($_POST['mem']);\n\t\t\t\t\n\t\t\t\t$correo = new ControladorEmail($socio->getEmail(), 0);\n\t\t\t\t$correo->formarMensaje('Hola '.$socio->getPrefijo().' '.$socio->getNombreCompleto().'<br>'.'Correo: '.$socio->getEmail().'<br>'.'Contraseña: '.$socio->getPassword());\n\t\t\t\t$correo->enviarCorreo();\n\t\t\t\t$url = 'index.php#RegistroCompletado';\n\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t\t//header('Location: index.php');\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(isset($_GET['mem'], $_GET['idEsc'])){\n\t\t\t\t\t$modSocio = new ModeloSocio();\n\t\t\t\t\t$modSocio->actualizarEscuela($_GET['mem'], $_GET['idEsc']);\n\t\t\t\t\t$url = 'index.php';\n\t\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t\t\t//header('Location: index.php');\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic function iniciarSesion(){\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t\n\t\t\t\t$email = $_POST['txtEmailLogin'];\n\t\t\t\t$pwd = $_POST['txtPassLogin'];\n\t\t\t\t\n\t\t\t\t$modelo = new ModeloSocio();\n\t\t\t\t$socio = $modelo->buscarPorEmail($email);\n\t\t\t\tif($socio != NULL && strcmp($pwd, $socio->getPassword()) == 0){\n\t\t\t\t\t$sesion = new Sesion();\n\t\t\t\t\t$sesion->setSesion(\"login\", true);\n\t\t\t\t\t$sesion->setSesion(\"socio\", $socio/*->getNombreCompleto()*/);\n\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\techo '<br> Datos incorrectos';\n\t\t\t\t}\n\t\t\t\t$url = 'index.php';\n\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic function cerrarSesion(){\n\t\t\t$sesion = new Sesion();\n\t\t\t$sesion->eliminaSesion('login');\n\t\t\t$sesion->terminaSesion();\n\t\t\t$url = 'index.php';\n\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t}\n\t}" }, { "alpha_fraction": 0.5878754258155823, "alphanum_fraction": 0.5884315967559814, "avg_line_length": 22.064102172851562, "blob_id": "6a6f6db655a7d5188194b1f41b4fb699cdc5a4ec", "content_id": "0b420470142bf143beebce7f0be03a587daa9da7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1799, "license_type": "permissive", "max_line_length": 94, "num_lines": 78, "path": "/public_html/app/Model.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n/*\tclass Model{\n\t\tprotected $conexion;\n\t\t\n\t\tpublic function __construct($dbname,$dbuser,$dbpass,$dbhost){\n\t\t\t$mvc_bd_conexion = mysql_connect($dbhost, $dbuser, $dbpass);\n\t\t\t\n\t\t\tif (!$mvc_bd_conexion) {\n\t\t\t\tdie('No ha sido posible realizar la conexión con la base de datos: ' . mysql_error());\n\t\t\t}\n\t\t\t\n\t\t\tmysql_select_db($dbname, $mvc_bd_conexion);\n\t\t\tmysql_set_charset('utf8');\n\t\t\t\n\t\t\t$this->conexion = $mvc_bd_conexion;\n\t\t}\n\t\t\n\t\tpublic function bd_conexion(){\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic function dameAlimentos(){\n\t\t\t$sql = \"select * from alimentos order by energia desc\";\n\t\t\t$result = mysql_query($sql, $this->conexion);\n\t\t\t\n\t\t\t$alimentos = array();\n\t\t\twhile ($row = mysql_fetch_assoc($result)){\n\t\t\t\t$alimentos[] = $row;\n\t\t\t}\n\t\t\t\n\t\t\treturn $alimentos;\n\t\t}\n\t\t\n\t\tpublic function buscarAlimentosPorNombre($nombre){\n\t\t\t$nombre = htmlspecialchars($nombre);\n\t\t\t\n\t\t\t$sql = \"select * from alimentos where nombre like '\" . $nombre . \"' order by energia desc\";\n\t\t\t$result = mysql_query($sql, $this->conexion);\n\t\t\t\n\t\t\t$alimentos = array();\n\t\t\t\n\t\t\twhile ($row = mysql_fetch_assoc($result)){\n\t\t\t\t$alimentos[] = $row;\n\t\t\t}\n\t\t\t\n\t\t\treturn $alimentos;\n\t\t}\n\t\t\n\t\tpublic function dameAlimento($id){\n\t\t\t$id = htmlspecialchars($id);\n\t\t\t\n\t\t\t$sql = \"select * from alimentos where id=\".$id;\n\t\t\t$result = mysql_query($sql, $this->conexion);\n\t\t\t\n\t\t\t$alimentos = array();\n\t\t\t$row = mysql_fetch_assoc($result);\n\t\t\t\n\t\t\treturn $row;\n\t\t}\n\t\t\n\t\tpublic function insertarIns($n, $e){\n\t\t\t$n = htmlspecialchars($n);\n\t\t\t$e = htmlspecialchars($e);\n\t\t\t\n\t\t\t$sql = \"insert into institucion (nombre, siglas) values ('\" .$n. \"','\" . $e . \"')\";\n\t\t\t$result = mysql_query($sql, $this->conexion);\n\t\t\t\n\t\t\treturn $result;\n\t\t}\n\t\t\n\t\tpublic function validarDatos($n, $e){\n\t\t\treturn (is_string($n) &\n is_string($e)\n\t\t\t\t );\n\t\t}\n\t}\n\t*/\n?>" }, { "alpha_fraction": 0.5688430070877075, "alphanum_fraction": 0.5798376202583313, "avg_line_length": 30.280424118041992, "blob_id": "7235e9739476a22c3a91127be6a506748cf74144", "content_id": "4fadeb77ae23098670e6dd745a3b3f73eff7bee3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5921, "license_type": "permissive", "max_line_length": 178, "num_lines": 189, "path": "/modcontra.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nif(isset($_GET['id']))\n $idCuestionario=$_GET['id'];\nelse\n $idCuestionario=1;\n?>\n\t<!doctype html>\n\t<html lang=\"es\">\n\t<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n\t<head>\n\t\t<?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n\t\t\t<meta charset=\"utf-8\">\n\n\n\t\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t\t\t<!-- links-->\n\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\t\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\n\n\t\t\t<title>Grupo de investigación en la enseñanza de física</title>\n\t</head>\n\t<script>\n\t\t$(document).ready(function() {\n\n\t\t\t$('.modal').modal();\n\n\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t// Initialize collapse button\n\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t// Initialize collapsible (uncomment the line below if you use the dropdown variation)\n\t\t\t//$('.collapsible').collapsible();\n\t\t\t$(\"#btn-modificar\").click(function(e) {\n\t\t\t\t//alert($(\"#modificar\").serialize());\n\n\t\t\t\t$.ajax({\n\t\t\t\t\ttype: \"post\",\n\t\t\t\t\turl: \"controlador/modcontra.php\",\n\t\t\t\t\tdata: $(\"#modificar\").serialize(),\n\t\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t\t//alert(resp);\n\t\t\t\t\t\tif (resp == 1) {\n\t\t\t\t\t\t\t$('#modal1').modal('open');\n\n\t\t\t\t\t\t} \n\t\t\t\t\t\telse if(resp == 2) {\n\t\t\t\t\t\t\t$('#modal2').modal('open');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t$('#modal3').modal('open');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn false;\n\n\t\t\t});\n\t\t});\n\n\t</script>\n\n\t<body>\n\n\t\t<?php \n include(\"barra.html\");\n ?>\n\n\t\t\t<!-- InstanceBeginEditable name=\"Banner\" -->\n\t\t\t<div id='banner'>\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<header>\n\t\t\t\t\t\t<div class=\"col s12 m5 l6\">\n\t\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t\t<h2 style=\"padding:20%;\">Registro de usuario</h2>\n\t\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"col s12 m6 l6\">\n\t\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</header>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<!-- InstanceEndEditable -->\n\n\n\t\t\t<?php \n include(\"minibarra.php\");\n ?>\n\t\t\t\t\n\t\t\t\t<div class=\"contenido\">\n\t\t\t\t\t<article>\n\t\t\t\t\t\t<h3>Modifica tu contaseña</h3>\n\t\t\t\t\t\t<p>Cambia los datos que desees. Si quieres cambiar de correo, marca la casilla y coloca el nuevo correo. Recuerda que éste es el identificador para entrar a tu cuenta.</p>\n\t\t\t\t\t\t<p>Por motivos de seguridad, la contraseña no se incluye dentro del siguiente formulario.</p>\n\t\t\t\t\t\t<?php\n require_once('controlador/BeanUsuario.php');\n //require_once('../controlador/connection.php');\n //session_start();\n $usuario = $_SESSION[\"login\"];\n $usuario = unserialize($usuario);\n $nombre= $usuario->getNombre();\n $arrayNombre=explode(\" \",$nombre,3);\n ?>\n\n\t\t\t\t\t\t\t<div id=\"formRegistro\">\n\t\t\t\t\t\t\t\t<form name=\"formUsuario\" class=\"pure-form pure-form-stacked\" id=\"modificar\">\n\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">https</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"password\" name=\"txtPwd\" id=\"txtPwd\" oninput=\"pass()\" minlength=\"6\" maxlength=\"10\" placeholder=\"password\" required/>\n\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"txtEmail\" id=\"labelEmail\"><pre style='display:inline'>&#09;</pre></label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">https</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"password\" name=\"txtPwd2\" id=\"txtPwd2\" oninput=\"pass()\" min=\"6\" maxlength=\"10\" placeholder=\"Confirmar password\" required/>\n\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"txtPwd2\" id=\"labelPassC\" size=\"40\"><pre style='display:inline'>&#09;</pre></label>\n\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s6\" style=\"padding-left:45%;\">\n\t\t\t\t\t\t\t\t\t\t\t<button type=\"submit\" value=\"Registrar\" class=\"btn waves-effect waves-light\" style=\"color:white;\" id=\"btn-modificar\">Modificar <i class=\"material-icons right\">send</i>\n\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\n\n\n\t\t\t\t\t\t\t\t\t</div>\n\n\n\n\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t</article>\n\t\t\t\t</div>\n\n\t\t\t\t<!-- InstanceEndEditable -->\n\t\t\t\t<footer>\n\t\t\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t\t\t<br>\n\t\t\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t\t\t<br>\n\t\t\t\t</footer>\n\t\t\t\t<div id=\"modal1\" class=\"modal\">\n\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t<h4>Tus datos han sido actualizados con &eacute;xito!!</h4>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t\t<a href=\"controlador/logout.php\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div id=\"modal2\" class=\"modal\">\n\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t<h4>No hemos podido actualizar</h4>\n\t\t\t\t\t\t<p>Tus contraseñas est&aacute;n vac&iacute;as</p>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div id=\"modal3\" class=\"modal\">\n\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t<h4>No hemos podido actualizar</h4>\n\t\t\t\t\t\t<p>Tus contrase&ntilde;as no coinciden</p>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t</body>\n\t<!-- InstanceEnd -->\n\n\t</html>\n" }, { "alpha_fraction": 0.48898857831954956, "alphanum_fraction": 0.4946981966495514, "avg_line_length": 30.44871711730957, "blob_id": "4434f00975264441fba224f30951cb4a6916a922", "content_id": "e53b3118253211fec0d346447c423e88f7d6278f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2452, "license_type": "permissive", "max_line_length": 109, "num_lines": 78, "path": "/controlador/connection.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass connection{\n\t\t/****************CONEXION****************************/\n\t\tprivate $server;\n\t\tprivate $bd;\n\t\tprivate $user;\n\t\tprivate $pwd;\n\t\tprivate $conexion;\n\t\t/****************************************************/\n\t\t/*************Resultado de consulta******************/\n\t\tprivate $resultado;\n\t\tprivate $total_filas;\n\t\t/****************************************************/\n\t\t\n\t\tpublic function connection(){\n\t\t\t\t/*************************************************************/\n\t\t\t\t$this->server = \"mssql.tlamatiliztli.net\";\n\t\t\t\t$this->user = \"tlama_4mat_2\";\n\t\t\t\t$this->pwd = \"rszY7?75\";\n\t\t\t\t$this->bd = \"tlamatil_4mat_beta_2\";\n\t\t\t\t/*************************************************************\n\t\t\t\t$this->server = \"localhost\";\n\t\t\t\t$this->user = \"root\";\n\t\t\t\t$this->pwd = \"\";\n\t\t\t\t$this->bd = \"4mat\";\n\t\t\t\t/*************************************************************/\n\t\t}\n\t\t\n\t\tpublic function conectar(){\n\t\t\t$this->conexion = mysql_connect($this->server, $this->user, $this->pwd);\n\t\t\tmysql_select_db($this->bd, $this->conexion);\n\t\t\tif(!$this->conexion)\n\t\t\t\tdie(\"Error al conectar: \".mysql_error());\n\t\t\t//else\n\t\t\t\t//echo \"Conectado<br>\";\n\t\t}\n\t\t\n\t\tpublic function desconectar(){\n\t\t\tmysql_close($this->conexion);\n\t\t\t//echo \"Desconectado<br>\";\n\t\t}\n\t\t\n\t\tpublic function myQuery($query){\n\t\t\t$this->resultado = mysql_query($query, $this->conexion) or die(mysql_error());\n\t\t\t//$this->total_filas = mysql_num_rows($this->resultado);\n\t\t\t\n\t\t\t/*\n\t\t\tif ($this->total_filas > 0) {\n \t\t\t\twhile ($rowEmp = mysql_fetch_assoc($this->resultado)) {\n\t\t\t \techo \"<strong>\".$rowEmp['dni'].\"</strong><br>\";\n \t \t\t\techo \"Direccion: \".$rowEmp['nombre'].\"<br>\";\n\t \t\t\techo \"Telefono: \".$rowEmp['password'].\"<br><br>\";\n \t\t\t\t}\n\t\t\t}*/\n\t\t}\n\t\t\n\t\tpublic function getFilas(){\n\t\t\treturn mysql_num_rows($this->resultado);\n\t\t}\n\t\t\n\t\tpublic function getArrayFila(){\n\t\t\treturn mysql_fetch_assoc($this->resultado);\n\t\t}\n\t}\n\t\n/*\t$a = new connection();\n\t$a->conectar();\n\t\n\t//$a->myQuery(\"INSERT INTO usuario(dni,nombre,password,foto) VALUES(NULL,'marga123','marga23','jpg')\");\n\t$a->myQuery(\"SELECT * FROM tareas WHERE fechaentrega > '2013-06-14' ORDER BY fechaentrega asc\");\n\techo($a->getFilas().\"<br>\");\n\twhile ($rowEmp = $a->getArrayFila()) {\n\t\t\t \techo \"<strong>\".$rowEmp['materia'].\"</strong><br>\";\n \t \t\t\techo \"Direccion: \".$rowEmp['fechaentrega'].\"<br>\";\n\t \t\t\techo \"Telefono: \".$rowEmp['descripcion'].\"<br><br>\";\n \t\t\t\t}\n\t$a->desconectar();*/\n?>" }, { "alpha_fraction": 0.5699999928474426, "alphanum_fraction": 0.5899999737739563, "avg_line_length": 15.833333015441895, "blob_id": "c63e2840fbc0e2338070bc2e18e7e056ce546b08", "content_id": "f11cc3f3008e2a899375f3d493d7965143d96ae9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 100, "license_type": "permissive", "max_line_length": 31, "num_lines": 6, "path": "/controlador/asignaCuadro.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t$valor=$_POST[\"seleccion2\"];\n\t$_SESSION[\"acceso\"][8]=$valor;\n\techo \"si\";\n?>" }, { "alpha_fraction": 0.4271125793457031, "alphanum_fraction": 0.43489915132522583, "avg_line_length": 43.2598876953125, "blob_id": "bc707cdf09a3d3174dd5626ac13476388fa9ea80", "content_id": "e77b3a9fdefcaa3247b5797de6da1092d4b4453a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 7839, "license_type": "permissive", "max_line_length": 259, "num_lines": 177, "path": "/cuestionario.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nif(isset($_GET['id']))\n $idCuestionario=$_GET['id'];\nelse\n $idCuestionario=1;\n?>\n<!doctype html>\n<html lang=\"es\"><!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\n $('.modal').modal();\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n \n });\n\n </script>\n <body>\n <?php\n include(\"barra.html\");\n ?>\n <!-- InstanceBeginEditable name=\"encabezados\" -->\n <?php \n if($banderaSesion == false) //Verificas si no esta logueado\n {\n echo \"<script language='JavaScript' type='text/javascript'> \n \tlocation.href='4mat.php';\n </script>\";\t\n }\n //Si esta logueado entonces, verificas si ya contesto el cuestionario HOY!\n $conexion = new connection();\n $query=\"select * from cuestionarioResuelto where idUsuario=\".$usuario->getId().\" and idCuestionario=\".$idCuestionario.\" and fecha=CURDATE()\";\n $conexion->conectar();\n $conexion->myQuery($query);\n if($conexion->getFilas())//Si me regresa tuplas significa que ya lo contesto HOY y no lo puede volver a contestar\n {\n //Lo redirigimos a ver sus resultados\n echo \"<script language='JavaScript' type='text/javascript'> \n \tlocation.href='resultados.php?id=\".$idCuestionario.\"';\n </script>\"; ///////////////////////////////////////CAMBIAR AQUI LA ACCION!!!\n }\n ?> \n <!-- InstanceBeginEditable name=\"Banner\" -->\n <div id='banner'>\n <div class=\"row\"> \n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\" >Registro de usuario</h2> \n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\"/>\n </div>\n </header>\n </div>\n </div>\n <!-- InstanceEndEditable -->\n\n\n <!-- InstanceEndEditable -->\n\n <?php \n include(\"minibarra.php\");\n ?>\n\n <!-- InstanceBeginEditable name=\"content\" --> \n <?php \t\t\t\n $query=\"select * from cuestionario where idCuestionario=\".$idCuestionario.\"\";\n $conexion->conectar();\n $conexion->myQuery($query);\n $rs=$conexion->getArrayFila();\n\n ?>\n \n <div class=\"contenido\">\n <article> \t\n <?php\n echo \"<h4>\".$rs['nombre'].\"</h4>\\n\";\n echo \"<p>\".$rs['instrucciones'].\"</p>\\n\";\n $conexion->desconectar();\t\t\t\t\t\n ?>\n <div class=\"row\">\n\n <div <?php if($idCuestionario==1){?>class= <?php } ?>>\n <form action=\"controlador/procesaCuest.php\" method=\"POST\" id=\"formCuestionario\" onSubmit=\"return verificaEnvio(<?php echo $idCuestionario ?>)\">\n <?php\n $query=\"select * from pregunta where idCuestionario=\".$idCuestionario.\"\";\n $conexion->conectar();\n $conexion->myQuery($query);\n $cont=1;\n while($rs=$conexion->getArrayFila())\n {\n echo \"<div class='input-field col s12 l6 '>\";\n $query=\"select * from respuesta where idPregunta=\".$rs['idPregunta'].\"\";\n //echo \"Subquery: \".$query;\n echo \"<div>\n <input type=\\\"radio\\\" name=\\\"P-\".$cont.\"\\\" id=\\\"P-\".$cont.\"\\\" onclick=\\\"resetSelect('P-\".$cont.\"')\\\">\".$rs['descripcionP'].\"</div>\\n\";\n\n echo \"<div class='respuestas'>\\n\";\n echo \"<ul>\\n\";\n $conexion2 = new connection();\n $conexion2->conectar();\n $conexion2->myQuery($query);\n $contador=1;\n while($rs2=$conexion2->getArrayFila())\n {\n echo \"<li>\\n\";\n\n echo\"<select style='width: auto;display: -webkit-inline-box; border:1px solid #0f7196; height:26px;' name=\\\"\".$cont.\"-\".$contador.\"\\\" id=\\\"\".$cont.\"-\".$contador.\"\\\" onblur=\\\"validaSelect('\".$cont.\"-\".$contador.\"')\\\">\\n\";\n\n echo\"<option value=\\\"\\\">-</option>\\n\";\n for($i=1;$i<=4;$i++)\n {\n echo \"<option value=\\\"\".$rs2['idEstilo'].\"-\".$i.\"\\\">\".$i.\"</option>\\n\";\n }\n\n echo \"</select>\\n\";\n\n echo\"<label style=' font-size: 1rem; color: black; position:inherit;' for='\".$rs2['descripcionR'].\"'>\".$rs2['descripcionR'].\"</label>\\n\";\n echo \"</li>\\n\"; \n $contador++;\n }\n $conexion2->desconectar();\n echo \"</ul>\\n\";\n\n echo\"</div>\\n\";\n $cont++;\n echo\"</div>\\n\";\n }\n\n //$conexion->desconectar();\n\n\n ?>\n\n <br><br><br>\n\n <input type=\"submit\" id=\"Enviar\" value=\"Enviar\" class='btn'/>\n <input name=\"16-1\" type=\"hidden\" id=\"16-1\" value=\"<?php echo $idCuestionario; ?>-<?php echo $usuario->getId(); ?>\"/>\n <br><br><br>\n </form>\n </div>\n\n </div>\n\n </article>\n </div>\n\n <!-- InstanceEndEditable -->\n <footer> \n <!--Aqui va el pie de pagina-->\n <br><p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p><br>\n </footer> \t \t\n </body>\n <!-- InstanceEnd --></html>\n" }, { "alpha_fraction": 0.6176314353942871, "alphanum_fraction": 0.6208178400993347, "avg_line_length": 32.32743453979492, "blob_id": "c9ae9386c7da1e01de7b9ea77670dfa430f7417e", "content_id": "f9f61169822b97480671960125d772261579206d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3767, "license_type": "permissive", "max_line_length": 129, "num_lines": 113, "path": "/borrar/estilos.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php require_once('../Connections/rem.php'); ?>\n<?php\nif (!function_exists(\"GetSQLValueString\")) {\nfunction GetSQLValueString($theValue, $theType, $theDefinedValue = \"\", $theNotDefinedValue = \"\") \n{\n if (PHP_VERSION < 6) {\n $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;\n }\n\n $theValue = function_exists(\"mysql_real_escape_string\") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);\n\n switch ($theType) {\n case \"text\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break; \n case \"long\":\n case \"int\":\n $theValue = ($theValue != \"\") ? intval($theValue) : \"NULL\";\n break;\n case \"double\":\n $theValue = ($theValue != \"\") ? doubleval($theValue) : \"NULL\";\n break;\n case \"date\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break;\n case \"defined\":\n $theValue = ($theValue != \"\") ? $theDefinedValue : $theNotDefinedValue;\n break;\n }\n return $theValue;\n}\n}\n\n$editFormAction = $_SERVER['PHP_SELF'];\nif (isset($_SERVER['QUERY_STRING'])) {\n $editFormAction .= \"?\" . htmlentities($_SERVER['QUERY_STRING']);\n}\n\nif ((isset($_POST[\"MM_update\"])) && ($_POST[\"MM_update\"] == \"form2\")) {\n $updateSQL = sprintf(\"UPDATE estilo SET descripcionE=%s WHERE idEstilo=%s\",\n GetSQLValueString($_POST['descripcionE'], \"text\"),\n GetSQLValueString($_POST['idEstilo'], \"int\"));\n\n mysql_select_db($database_rem, $rem);\n $Result1 = mysql_query($updateSQL, $rem) or die(mysql_error());\n}\n\nmysql_select_db($database_rem, $rem);\n$query_verEstilos = \"SELECT * FROM estilo\";\n$verEstilos = mysql_query($query_verEstilos, $rem) or die(mysql_error());\n$row_verEstilos = mysql_fetch_assoc($verEstilos);\n$totalRows_verEstilos = mysql_num_rows($verEstilos);\n\n$colname_buscarEstilo = \"-1\";\nif (isset($_POST['idEstilo'])) {\n $colname_buscarEstilo = $_POST['idEstilo'];\n}\nmysql_select_db($database_rem, $rem);\n$query_buscarEstilo = sprintf(\"SELECT * FROM estilo WHERE idEstilo = %s\", GetSQLValueString($colname_buscarEstilo, \"int\"));\n$buscarEstilo = mysql_query($query_buscarEstilo, $rem) or die(mysql_error());\n$row_buscarEstilo = mysql_fetch_assoc($buscarEstilo);\n$totalRows_buscarEstilo = mysql_num_rows($buscarEstilo);\n?>\n<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Documento sin título</title>\n</head>\n\n<body>\n<form name=\"form1\" method=\"post\" action=\"\">\nidEstilo\n <input type=\"text\" name=\"idEstilo\" id=\"idEstilo\">\n <input type=\"submit\" name=\"buscar\" id=\"buscar\" value=\"Enviar\">\n</form>\n<form method=\"post\" name=\"form2\" action=\"<?php echo $editFormAction; ?>\">\n<table align=\"center\">\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">IdEstilo:</td>\n <td><?php echo $row_buscarEstilo['idEstilo']; ?></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap align=\"right\" valign=\"top\">DescripcionE:</td>\n <td><textarea name=\"descripcionE\" cols=\"50\" rows=\"5\"><?php echo $row_buscarEstilo['descripcionE']; ?></textarea></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">&nbsp;</td>\n <td><input type=\"submit\" value=\"Actualizar registro\"></td>\n </tr>\n </table>\n <input type=\"hidden\" name=\"MM_update\" value=\"form2\">\n <input type=\"hidden\" name=\"idEstilo\" value=\"<?php echo $row_buscarEstilo['idEstilo']; ?>\">\n</form>\n<table border=\"1\">\n <tr>\n <td>idEstilo</td>\n <td>descripcionE</td>\n </tr>\n <?php do { ?>\n <tr>\n <td><?php echo $row_verEstilos['idEstilo']; ?></td>\n <td><?php echo $row_verEstilos['descripcionE']; ?></td>\n </tr>\n <?php } while ($row_verEstilos = mysql_fetch_assoc($verEstilos)); ?>\n</table>\n</body>\n</html>\n<?php\nmysql_free_result($verEstilos);\n\nmysql_free_result($buscarEstilo);\n?>\n" }, { "alpha_fraction": 0.5952251553535461, "alphanum_fraction": 0.6185566782951355, "avg_line_length": 27.8125, "blob_id": "e6fe8b15ffc3d25b5957c916ff4da6ef72705918", "content_id": "899d238eddd6d099667dfdd5cf6e02afd1ffa615", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1848, "license_type": "permissive", "max_line_length": 193, "num_lines": 64, "path": "/controlador/login.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php \n\trequire_once(\"connection.php\");\n\trequire_once(\"BeanUsuario.php\");\n\t/***************************************************/\n\tlogin();\n\t// Algoritmo principal\n\t/*\n\t\n\t*/\n\t\n\t//Algoritmo de login\n\t/*\n\t1.- Obtener datos: nombre de usuario y contraseña\n\t2.- usuario = usuario de la bd & password = password de la bd\n\t\n\t2.1.- SI\n\t2.1.1.- Obtener datos del usuario para llenar el bean\n\t2.1.2.- Crear Sesion\n\t2.1.3.- Ir paso 3\n\t\n\t2.2.- NO\n\t2.2.1.- Mostrat \"Verificar datos\"\n\t2.2.2.- Regresar al paso 1\n\t\n\t3.- Tipo de usuario = 'ellos'\n\t\n\t3.1.- SI\n\t3.1.1.- Mostrar el menu de ellos\n\t3.1.2.- Ir a paso 4 \n\t\n\t3.2.- NO\n\t3.2.1.- Mostrar menu de administrador\n\t\n\t4.- Fin\n\t*/\n\t\n\tfunction login(){\n\t\t$email = $_POST['email'];\n\t\t$password = md5($_POST['pass']);\n\t\t\n\t\t$conexion = new connection();\n\t\t$conexion->conectar();\n\t\t$query = \"SELECT idUsuario, tipo, nombre,fechaNac, sex, ocupacion,institucion, email FROM usuario WHERE email = '$email' AND password='$password'\";\n\t\t$conexion->myQuery($query);\n\t\t$conexion->desconectar();\n\t\tif($conexion->getFilas() <= 0){\n\t\t\t//echo \"¡Error! verifica tu usuario y/o contraseña\";\n\t\t\techo \"<!doctype html><html lang='es'><head>\n\t\t<meta charset='utf-8'><script language='JavaScript' type='text/javascript'> \n \talert('¡Error! verifica tu usuario y/o contraseña'); location.href='javascript:history.back()';\n </script></head></html>\";\n\t\t\t//redireccionar al login\n\t\t}\n\t\telse{\n\t\t\t$resultado = $conexion->getArrayFila();\n\t\t\t$usuario = new BeanUsuario($resultado['idUsuario'],$resultado['nombre'],$resultado['fechaNac'],$resultado['sex'],$resultado['ocupacion'],$resultado['institucion'],$email,$resultado['tipo']);\n\t\t\techo \"Bienvenido homie \".$usuario->getNombre();\n\t\t\tsession_start();\n\t\t\t$usuario = serialize($usuario);\n\t\t\t$_SESSION[\"login\"] = $usuario;\n\t\t\theader('Location: ../4mat.php');\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.6858006119728088, "alphanum_fraction": 0.69486403465271, "avg_line_length": 32.20000076293945, "blob_id": "511099227a6d4617de797437d93696e743c8223f", "content_id": "7afc0ec7fded35f7cd6c641a2dfb3e2e7e16d698", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 331, "license_type": "permissive", "max_line_length": 113, "num_lines": 10, "path": "/Connections/rem.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n# FileName=\"Connection_php_mysql.htm\"\n# Type=\"MYSQL\"\n# HTTP=\"true\"\n$hostname_rem = \"mssql.tlamatiliztli.mx\";\n$database_rem = \"tlamatil_4mat_beta\";\n$username_rem = \"tlama_4mat2\";\n$password_rem = \"#4Math$.\";\n$rem = mysql_pconnect($hostname_rem, $username_rem, $password_rem) or trigger_error(mysql_error(),E_USER_ERROR); \n?>" }, { "alpha_fraction": 0.5531914830207825, "alphanum_fraction": 0.570035457611084, "avg_line_length": 30.33333396911621, "blob_id": "05e5dbff058083bf92c4720da7829401d52a55c2", "content_id": "60da49dccf0c04e6078f26054aa047fb257c5333", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2256, "license_type": "permissive", "max_line_length": 262, "num_lines": 72, "path": "/controlador/loginEncuesta.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n session_start();\n $user=$_POST[\"user\"];\n $pass=$_POST[\"pass\"];\n\t//echo $user;\n\t//echo $pass;\n $conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\t$pass=md5($pass);\n $sql=\"select * from usuario where email='$user' and passw='$pass';\";\n\tif($res=mysqli_query($conexion,$sql))//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\t//echo 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t echo \"Error: \" . $sql . \"<br>\" . mysqli_error($conexion);\n\t}\n\t\t\t\t\n $numrows=mysqli_num_rows($res);\n while($columna=mysqli_fetch_array($res)){\n $nombre=$columna['Nombre'];\n $apellido=$columna['ApPaterno'].\" \".$columna['ApMaterno'];\n\t\t$contesto=$columna['ContestoEncuesta'];\n\t\t$tipoUsuario=$columna['TipoUsuario'];\n\t\t$Area=$columna['idArea'];\n\t\t$idUsr=$columna['ID'];\n $edad=$columna['Edad'];\n }\n if($numrows==1){\n $_SESSION[\"acceso\"][1]=$nombre;\n $_SESSION[\"acceso\"][2]=$apellido;\n $_SESSION[\"acceso\"][3]=$contesto;\n $_SESSION[\"acceso\"][4]=$tipoUsuario;\n $_SESSION[\"acceso\"][5]=$Area;\n\t\t$_SESSION[\"acceso\"][6]=$idUsr;\n\t\t$_SESSION[\"acceso\"][7]=1;\n\t\t$_SESSION[\"acceso\"][10]=\" \";\n\t\t$_SESSION[\"acceso\"][11]=\" \";\n\t\t$_SESSION[\"acceso\"][12]=\" \";\n\t\t$_SESSION[\"acceso\"][13]=\" \";\n\t\t$_SESSION[\"acceso\"][14]=\" \";\n\t\t$_SESSION[\"acceso\"][15]=\" \";\n $_SESSION[\"acceso\"][16]=$edad;\n $_SESSION[\"acceso\"][17]=$user;\n \n //nuevo\n $sql=\"SELECT p.nombre as pais, n.nivel as nivel, i.nombre as institucion, a.nombre as area from usuario u, pais p, nivel n ,institucion i, area a where u.IDPais=p.IDPais and u.IDInst=i.IDInst and u.idArea=a.IDArea and u.idNivel=n.idNivel and u.ID='$idUsr';\";\n \nif($res=mysqli_query($conexion,$sql))//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\t//echo 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t echo \"Error: \" . $sql . \"<br>\" . mysqli_error($conexion);\n\t}\n \n while($columna=mysqli_fetch_array($res)){\n $_SESSION[\"acceso\"][18]=$columna['pais'];\n $_SESSION[\"acceso\"][19]=$columna['institucion'];\n $_SESSION[\"acceso\"][20]=$columna['area'];\n $_SESSION[\"acceso\"][21]=$columna['nivel'];\n }\n\n }\n\tif($numrows==0){\n\t\techo $numrows;\n\t}\n\telse{\n\t\techo \"1\";\n\t}\n \n \n?>\n" }, { "alpha_fraction": 0.5427661538124084, "alphanum_fraction": 0.5468607544898987, "avg_line_length": 29.957746505737305, "blob_id": "7642579beb5a7c3c385158c9cded71bd866011c1", "content_id": "26327a06156577552ab07bc2633edc8b850d5100", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2198, "license_type": "permissive", "max_line_length": 109, "num_lines": 71, "path": "/public_html/app/modelo/Connection.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass Connection{\n\t\t/****************CONEXION****************************/\n\t\tprivate $server;\n\t\tprivate $bd;\n\t\tprivate $user;\n\t\tprivate $pwd;\n\t\tprivate $conexion;\n\t\t/****************************************************/\n\t\t/*************Resultado de consulta******************/\n\t\tprivate $resultado;\n\t\tprivate $total_filas;\n\t\t/****************************************************/\n\t\t\n\t\tpublic function __construct(){\n\t\t\t\t$this->server = Config::$mvc_bd_hostname;\n\t\t\t\t$this->user = Config::$mvc_bd_usuario;\n\t\t\t\t$this->pwd = Config::$mvc_bd_clave;\n\t\t\t\t$this->bd = Config::$mvc_bd_nombre;\n\t\t}\n\t\t\n\t\tpublic function conectar(){\n\t\t\t$this->conexion = mysqli_connect($this->server, $this->user, $this->pwd, $this->bd);\n\t\t\t//mysql_select_db($this->bd, $this->conexion);\n\t\t\tif(!$this->conexion)\n\t\t\t\tdie(\"Error al conectar: \".mysql_error());\n\t\t\t//else\n\t\t\t\t//echo \"Conectado<br>\";\n\t\t}\n\t\t\n\t\tpublic function desconectar(){\n\t\t\tmysqli_close($this->conexion);\n\t\t\t//echo \"Desconectado<br>\";\n\t\t}\n\t\t\n\t\tpublic function myQuery($query){\n\t\t\t$this->resultado = mysqli_query($this->conexion, $query) or die(mysqli_error($this->conexion));\n\t\t\t//$this->total_filas = mysql_num_rows($this->resultado);\n\t\t\t\n\t\t\t/*\n\t\t\tif ($this->total_filas > 0) {\n \t\t\t\twhile ($rowEmp = mysql_fetch_assoc($this->resultado)) {\n\t\t\t \techo \"<strong>\".$rowEmp['dni'].\"</strong><br>\";\n \t \t\t\techo \"Direccion: \".$rowEmp['nombre'].\"<br>\";\n\t \t\t\techo \"Telefono: \".$rowEmp['password'].\"<br><br>\";\n \t\t\t\t}\n\t\t\t}*/\n\t\t}\n\t\t\n\t\tpublic function getFilas(){\n\t\t\treturn mysqli_num_rows($this->resultado);\n\t\t}\n\t\t\n\t\tpublic function getArrayFila(){\n\t\t\treturn mysqli_fetch_assoc($this->resultado);\n\t\t}\n\t}\n\t\n/*\t$a = new connection();\n\t$a->conectar();\n\t\n\t//$a->myQuery(\"INSERT INTO usuario(dni,nombre,password,foto) VALUES(NULL,'marga123','marga23','jpg')\");\n\t$a->myQuery(\"SELECT * FROM tareas WHERE fechaentrega > '2013-06-14' ORDER BY fechaentrega asc\");\n\techo($a->getFilas().\"<br>\");\n\twhile ($rowEmp = $a->getArrayFila()) {\n\t\t\t \techo \"<strong>\".$rowEmp['materia'].\"</strong><br>\";\n \t \t\t\techo \"Direccion: \".$rowEmp['fechaentrega'].\"<br>\";\n\t \t\t\techo \"Telefono: \".$rowEmp['descripcion'].\"<br><br>\";\n \t\t\t\t}\n\t$a->desconectar();*/\n?>\n" }, { "alpha_fraction": 0.5864474177360535, "alphanum_fraction": 0.5869457125663757, "avg_line_length": 31.387096405029297, "blob_id": "759b38747ddf3779aa9d894c53ea37a22af1b4f2", "content_id": "379266bf7470151cbb820ed71764d058018c953d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2007, "license_type": "permissive", "max_line_length": 220, "num_lines": 62, "path": "/public_html/app/modelo/ModeloSocio.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\t//require_once('../bean/Socio.php');\n\tclass ModeloSocio{\n\t\tprotected $db;\n\t\t\n\t\tpublic function __construct(){\n\t\t\t$this->db = new Connection();\n\t\t\t$this->db ->conectar();\n\t\t}\n\t\t\n\t\tpublic function validarDatosSocio($socio){\n\t\t\t//echo 'Desde el modelo: '.$socio->getNombreCompleto();\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tpublic function insertarSocio($socio){\n\t\t\t$query = 'insert into socio(nombreCompleto,prefijo,email,estudProf,niClase,avisoBoletin,password) ';\n\t\t\t$query .= 'values(\"'.$socio->getNombreCompleto().'\",\"'.$socio->getPrefijo().'\", \"'.$socio->getEmail().'\",\"'.$socio->getEstudProf().'\",\"';\n\t\t\t$query .= $socio->getNiClase().'\",\"'.$socio->getAvisoBoletin().'\",\"'.$socio->getPassword().'\")';\n\t\t\t$this->db -> myQuery($query);\n\t\t}\n\t\t\n\t\tpublic function buscarPorEmail($busqueda){\t\t\t\n\t\t\t$socio = NULL;\n\t\t\tif($busqueda == ''){\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$query = 'select * from socio';\n\t\t\t\t$query .= ' where email = \"'.$busqueda.'\"';\n\t\t\t\t$this->db -> myQuery($query);\n\t\t\t\n\t\t\t\twhile ($row = $this->db ->getArrayFila()) {\n\t\t\t\t\t$socio = new Socio($row['noMembresia'], $row['nombreCompleto'], $row['prefijo'], $row['email'], $row['estudProf'], $row['niClase'], $row['avisoBoletin'], $row['password'], $row['idTrabajo'], $row['idEscuela']);\t\t\t\t\t\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn $socio;\n\t\t}\n\t\t\n\t\tpublic function buscarPorNoMem($busqueda){\t\t\t\n\t\t\t$socio = NULL;\n\t\t\tif($busqueda == ''){\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$query = 'select * from socio';\n\t\t\t\t$query .= ' where noMembresia = '.$busqueda.'';\n\t\t\t\t$this->db -> myQuery($query);\n\t\t\t\n\t\t\t\twhile ($row = $this->db ->getArrayFila()) {\n\t\t\t\t\t$socio = new Socio($row['noMembresia'], $row['nombreCompleto'], $row['prefijo'], $row['email'], $row['estudProf'], $row['niClase'], $row['avisoBoletin'], $row['password'], $row['idTrabajo'], $row['idEscuela']);\t\t\t\t\t\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn $socio;\n\t\t}\n\t\t\n\t\tpublic function actualizarEscuela($noMembresia, $idEscuela){\n\t\t\t$query = 'update socio set idEscuela='.$idEscuela.\" where noMembresia=\".$noMembresia;\n\t\t\t$this->db->myQuery($query);\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.447388619184494, "alphanum_fraction": 0.4642857015132904, "avg_line_length": 46.3636360168457, "blob_id": "76384ab7c2ec75858fefafc42f5464405c6ebafe", "content_id": "1476aa65088238ce6c84c6688eb8644dec970a6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2606, "license_type": "permissive", "max_line_length": 171, "num_lines": 55, "path": "/menuLog.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!-- InstanceEndEditable -->\n<?php if($banderaSesion){ ?>\n<div id='menuLogueado'>\n <div id='menu2'>\n\n <ul>\n <!------PONER ID ACTUAL AL QUE ESTES EDITANDO---------------->\n <?php if($banderaEllos == false){ ?>\n <ul id=\"slide-out\" class=\"side-nav\">\n <li><div class=\"userView\">\n <div class=\"background\">\n <img src=\"images/fondo.png\">\n </div>\n <a href=\"#!user\" style=\"background-color:rgba(240, 248, 255, 0);\"><img class=\"circle\" src=\"images/persona.jpg\"></a>\n <a href=\"#!name\" style=\"background-color:rgba(240, 248, 255, 0);\"><span class=\"white-text name\"><?php echo \"\".$usuario->getNombre().\"\"; ?> </span></a>\n <a href=\"#!email\" style=\"background-color:rgba(240, 248, 255, 0);\"><span class=\"white-text email\"><?php echo \"\".$usuario->getEmail().\"\"; ?> </span></a>\n </div></li>\n <li><a href=\"administrador.php\"><i class=\"material-icons\">cloud</i>Administración</a></li>\n\n <?php } \n $conexion = new connection();\n $query=\"select * from cuestionario\";\n $conexion->conectar();\n $conexion->myQuery($query); \n ?>\n <li><div class=\"divider\"></div></li>\n <li><a href=\"#!\" class=\"subheader\"><i class=\"material-icons\">cloud</i></a></li>\n <?php\n while($rs=$conexion->getArrayFila())//Si me regresa tuplas significa que existen cuestionarios\n {\n echo \"<li><a href=\\\"cuestionario.php?id=\".$rs['idCuestionario'].\"\\\">\".$rs['nombre'].\"</a>\";\n ?>\n\n <li><a class=\"\" href=\"resultados.php?id=<?php echo $rs['idCuestionario'] ?>\">&#160; &#160; &#160; &#160; Resultado</a></li>\n\n\n <?php echo \"</li>\"; } $conexion->desconectar();?>\n <li><div class=\"divider\"></div></li>\n <li><a href=\"modificar.php\"><i class=\"material-icons\">cloud</i>Mi Perfil</a></li>\n\n <li><a href=\"controlador/logout.php\">Cerrar Sesión</a></li>\n <li><div class=\"divider\"></div></li>\n <li><a href=\"controlador/logout.php\"></a></li>\n </ul>\n </ul> \n <a href=\"#\" data-activates=\"slide-out\" class=\"button-collapse\"><i class=\"material-icons\" style=\"\n right: 5%; position: absolute;\">menu</i></a>\n\n\n\n\n\n </div>\n</div>\n<?php } ?>" }, { "alpha_fraction": 0.6684492230415344, "alphanum_fraction": 0.6684492230415344, "avg_line_length": 19.77777862548828, "blob_id": "f3749bf1abe8ab19db0ef8a1ef6e35b3239c4190", "content_id": "eb55482815bd0946dbae85a8d946cab58605cc0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 374, "license_type": "permissive", "max_line_length": 101, "num_lines": 18, "path": "/ObtieneNum.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n//recibo datos\n\n$seleccion=$_POST['seleccion'];\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n$query=\"SELECT IDPregunta from pregunta;\";\n$sth = mysqli_query($conexion,$query);\n\n$rows = array();\nwhile($r = $sth->fetch_assoc()) {\n\t$rows[] = $r;\n\t//echo $r;\n}\n\necho json_encode($rows);\n\nmysqli_close($conexion);\n?>\n" }, { "alpha_fraction": 0.5753346085548401, "alphanum_fraction": 0.5814531445503235, "avg_line_length": 28.206703186035156, "blob_id": "71b14db9d3ccd4ff74ee9964bf272246549834e8", "content_id": "88226782478ffea94ae13bb122ec9f8bc6726c99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5230, "license_type": "permissive", "max_line_length": 122, "num_lines": 179, "path": "/public_html/app/templates/docs/BluetoothComunication.java", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "package bluetoothled;\n\nimport javax.microedition.midlet.*;\nimport javax.microedition.lcdui.*;\nimport javax.bluetooth.*;\nimport java.io.*;\nimport javax.microedition.io.*;\n\n\npublic class BluetoothComunication extends MIDlet implements CommandListener, DiscoveryListener {\n\n private Display display;\n private Command conectar, desconectar, ok, comenzar,salir;\n private Form bienvenida;\n private List comandos;\n private StreamConnection con;\n private OutputStream outs;\n private InputStream ins;\n private LocalDevice localDevice = null;\n private DiscoveryAgent discoveryAgent = null;\n private ServiceRecord[] serviciosEncontrados = null;\n private String URL = \"btspp://201402181704:1;authenticate=false;encrypt=false;master=false\";\n\n\n public void startApp() {\n display = Display.getDisplay(this);\n conectar = new Command(\"Conectar\", Command.ITEM, 1);\n desconectar = new Command(\"Desconectar\", Command.ITEM, 1);\n ok = new Command(\"OK\", Command.OK, 1);\n comenzar = new Command(\"Comenzar\", Command.OK, 1);\n salir = new Command(\"Salir\", Command.EXIT, 1);\n\n bienvenida = new Form(\"Bienvenido\");\n comandos = new List(\"Escoja una accion\", List.EXCLUSIVE);\n\n bienvenida.addCommand(comenzar);\n bienvenida.setCommandListener(this);\n\n comandos.addCommand(conectar);\n comandos.addCommand(ok);\n comandos.addCommand(desconectar);\n comandos.append(\"Encender LED\", null);\n comandos.append(\"Apagar LED\", null);\n comandos.setCommandListener(this);\n\n display.setCurrent(bienvenida);\n }\n\n\n public void commandAction(Command c, Displayable d) {\n if (c == comenzar){\n comenzar();\n } else if(c == salir){\n destroyApp(false);\n notifyDestroyed();\n } else if (c == ok){\n enviar();\n } else if(c == conectar){\n conectar();\n } else if(c == desconectar){\n desconectar();\n }\n }\n\n\n public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {\n\n\n\n }\n\n\n public void inquiryCompleted(int discType) {\n\n }\n\n public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {\n\n }\n\n public void serviceSearchCompleted(int transID, int respCode) {\n\n }\n\n public void pauseApp() {\n }\n\n public void destroyApp(boolean unconditional) {\n }\n\n private void comenzar() {\n try {\n localDevice = LocalDevice.getLocalDevice();\n localDevice.setDiscoverable(DiscoveryAgent.GIAC);\n Display.getDisplay(this).setCurrent(comandos);\n } catch (BluetoothStateException e) {\n e.printStackTrace();\n Alert alerta = new Alert(\"Error\", \"No se puede hacer uso de Bluetooth\", null, AlertType.ERROR);\n alerta.setTimeout(Alert.FOREVER);\n Display.getDisplay(this).setCurrent(alerta);\n }\n }\n\n\n\n private void conectar(){\n try{\n con = (StreamConnection) Connector.open(URL);\n outs = con.openOutputStream();\n ins = con.openInputStream();\n }\n catch(IOException e){\n mostrarAlarma(e, comandos, 3);\n }\n }\n\n private void desconectar() {\n try {\n ins.close();\n outs.close();\n con.close();\n } catch (IOException e) {\n mostrarAlarma(e, comandos, 4);\n }\n }\n\n private void enviar(){\n conectar();\n int i = comandos.getSelectedIndex();\n String comando_elegido = comandos.getString(i);\n if(comando_elegido == \"Encender LED\"){\n String greeting = \"1\";\n try {\n outs.write(greeting.getBytes());\n mostrarAlarma(null, comandos, 5);\n }\n catch(IOException e){\n mostrarAlarma(e, comandos,2);\n }\n }\n else{\n String greeting = \"0\";\n try {\n outs.write(greeting.getBytes());\n mostrarAlarma(null, comandos, 5);\n }\n catch(IOException e){\n mostrarAlarma(e, comandos,2);\n }\n\n }\n desconectar();\n\n\n }\n\n\n\n public void mostrarAlarma(Exception e, Screen s, int tipo) {\n Alert alerta = null;\n if (tipo == 0) {\n alerta = new Alert(\"Excepcion\", \"Se ha producido la excepcion \" + e.getClass().getName(), null,\n AlertType.ERROR);\n } else if (tipo == 1) {\n alerta = new Alert(\"Info\", \"Se completo la busqueda de servicios\", null, AlertType.INFO);\n } else if (tipo == 2) {\n alerta = new Alert(\"ERROR\", \"No se pudo enviar\", null, AlertType.ERROR);\n } else if (tipo == 3) {\n alerta = new Alert(\"ERROR\", \"No se pudo establecer conexion\" + e.getClass().getName(), null, AlertType.ERROR);\n } else if (tipo == 4) {\n alerta = new Alert(\"ERROR\", \"No se pudo desconectar\" , null, AlertType.INFO);\n } else if (tipo == 5) {\n alerta = new Alert(\"INFO\", \"Se envio el comando\" , null, AlertType.INFO);\n }\n alerta.setTimeout(Alert.FOREVER);\n display.setCurrent(alerta, s);\n }\n\n}\n\n\n" }, { "alpha_fraction": 0.5173965096473694, "alphanum_fraction": 0.565500795841217, "avg_line_length": 65.42682647705078, "blob_id": "4fdd47447b6c2c4c9d8458bf2f3757741e8231e4", "content_id": "940b08836b061cbef4b69744e2d5a40836cd49ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10954, "license_type": "permissive", "max_line_length": 596, "num_lines": 164, "path": "/public_html/app/templates/eventos.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<!-- Aqui va el contenido del contenedor blanco-->\n<script type=\"text/javascript\" src=\"web/js/menuConvoca.js\"></script>\n<div class=\"menuConvoca\" id=\"menuConvoca\">\n\t<ul>\n\t\t<li><a href=\"#infoConvoca\"><span class=\" icon-info_outline\"></span>Información General</a></li>\n\t\t<li><a href=\"#basesConvoca\"><span class=\"icon-storage\"></span>Bases</a></li>\n\t\t<li><a href=\"#hotelesConvoca\"><span class=\"icon-location_city\"></span>Hoteles cercanos</a></li>\n <li><a href=\"#comiteConvoca\"><span class=\"icon-people\"></span>Comite local</a></li>\n <li><a href=\"#contactoConvoca\"><span class=\" icon-contact_mail\"></span>Contacto</a></li>\n\t</ul>\n</div>\n\n<div id=\"infoConvoca\" class=\"Columnas\">\n\t<div class=\"noColumna\">\n\t\t<h1>REUNIÓN ANUAL DE LA AAPT-Mx 2016 \"La Física en nuestro entorno\"</h1>\n\t\t<h2>Asociación American de Profesores de Física - Sección México</h2>\n <p><span class=\" icon-today\"></span>17 y 18 de Noviembre de 2016<br><span class=\"icon-room\"></span>Centro de Educación Continua - Unidad Cancún del IPN<br>\n <span class=\"icon-get_app\"></span>Descarga la convocatoría completa <a href=\"descargas/convocatoria2016.pdf\" target=\"_blank\">aquí.</a></P>\n\t</div>\n</div><!--infoConvoca-->\n\n<img src=\"web/img/CEC_CANCUN.svg\" alt=\"Sede CEC_CANCUN\" width=\"100%\">\n<div id=\"basesConvoca\">\n\t<div class=\"Columnas\"> \n\t\t<div class=\"noColumna\">\n\t\t\t<h1><span class=\"icon-storage\"></span>Bases</h1>\n\t\t</div>\n\t</div>\n\t<div class=\"Columnas\">\n\t\t<div class=\"columna2\">\n\t\t\t<ol>\n\t\t\t\t<li>Podrán participar estudiantes, técnicos, profesores e investigadores de los diversos niveles educativos, así como público en general, interesados en la enseñanza de la Física.</li>\n <li>Se podrá participar en tres modalidades:\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Asistente.</li>\n\t\t\t\t\t\t<li>Ponencia Oral.</li>\n\t\t\t\t\t\t<li>Presentación de Posters.</li>\n\t\t\t\t\t</ul>\n\t\t\t\t</li>\n\t\t\t\t<li>Se requiere que los participantes del evento, en cualquiera de las tres modalidades, realicen un pre-registro en la siguiente liga: <a href=\"http://goo.gl/forms/rcJ2kURzxt\" target=\"_blank\">GoogleForms.</a> La información del pre-registro servirá para realizar el sorteo de los trabajos presentados en las diferentes sesiones y modalidades.\n\t\t\t\t</li>\n <li>De las Ponencias Orales:\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Los participantes tendrán un tiempo de 10 minutos para exponer su tema y 5 minutos para responder a las preguntas que les hagan los asistentes a las mesas de trabajo.\n </li>\n\t\t\t\t\t</ul>\n\t\t\t\t</li> \n\t\t\t\t<li>De los posters:\n\t\t\t\t\t<ul>\n \t<li>Los participantes podrán exponer su tema, en un póster cuya medida no debe de exceder 90x120 cm (ancho y alto respectivamente), dentro de los horarios asignados.\n </li>\n </ul>\n\t\t\t\t</li> \n\t\t\t\t<li>\n\t\t\t\t\tLos participantes tanto de Ponencia Oral como póster, deberán enviar sus propuestas de trabajos mediante EasyChair (disponible en la siguiente liga: <a href=\"https://easychair.org/conferences/?conf=aaptmx2016\" target=\"_blank\">EasyChair.</a>) en el formato propuesto para ello. La propuesta debe incluir el título del trabajo, los autores y su afiliación, tres palabras clave y un resumen entre 100 y 250 palabras del trabajo que van a presentar a más tardar el 31 de agosto. El resultado del arbitraje de resúmenes se comunicará a más tardar el 7 de septiembre.\n\t\t\t\t</li> \n\t\t\t</ol>\n\t\t</div>\n\t\t<div class=\"columna2\">\n\t\t\t<ol>\n\t\t\t\t<li value=\"7\">Aquellos participantes a los que se les acepte su propuesta, tienen la opción de presentar sus trabajos en extenso, para que después de un proceso de arbitraje entre pares, puedan ser publicados en el Latin-American Journal of Physics Education. Los extensos deberán ser enviados a más tardar el 15 de enero de 2017 en el formato correspondiente de la revista (disponible en <a href=\"http://www.lajpe.org\" target=\"_blank\">http://www.lajpe.org</a> ). Los trabajos que no sean entregados en tiempo y forma de acuerdo a los lineamientos no serán considerados para su participación.\n\t\t\t\t</li>\n\t\t\t\t<li>Los extensos deben tener las características acordes a los criterios de Latin American Journal of Physics Education.</li>\n\t\t\t\t<li>El extenso deberá ser enviado a [email protected] con el asunto: Extenso (número de trabajo) AAPTMx 2016.</li>\n\t\t\t\t<li>De las inscripciones:\n\t\t\t\t\t<ul>\n \t<li>En este año, la cuota simbólica de recuperación será de $350.00 pesos mexicanos por participante (No se emitirán facturas). Incluye inscripción a la reunión y membresía anual de la AAPT-Mx. El pago se realizará en efectivo el día del evento.\n </li>\n\t\t\t\t\t</ul>\n\t\t\t\t</li>\n\t\t\t\t<li>Los casos no previstos en la presente convocatoria serán resueltos por el Comité Organizador.</li>\n\t\t\t</ol>\n\t\t</div> \n\t</div>\n</div><!--basesConvoca-->\n\n <div id=\"hotelesConvoca\">\n \t<div class=\"Columnas\">\n \t<div class=\"noColumna\">\n\t <h1><span class=\"icon-location_city\"></span>Hoteles cercanos</h1>\n </div>\n </div>\n <div class=\"Columnas\">\n \t<div class=\"columna2\">\n \t<h2>Hotel One Cancún Centro</h2>\n <p style=\"font-size:18px\"><span class=\"icon-room\" style=\"color:white\"></span>Av. Tulum esq. Banco Chinchorro, Lote 1-01, Manzana 2. Supermanzana 77504 Cancún, Q. R.<br>\n <span class=\"icon-phone\" style=\"color:white\"></span>+52 (998) 881 6940<br>\n <span class=\"icon-web\" style=\"color:white\"></span>www.fiestainn.com / www.onehotels.com</p>\n \n </div>\n <div class=\"columna2\">\n \t<iframe src=\"https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d1354.279375222834!2d-86.82854107976948!3d21.1351119780654!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8f4c2bdded94eb4b%3A0x906ee4e8e8dd3395!2sOne+Canc%C3%BAn+Centro!5e0!3m2!1ses!2smx!4v1465250628231\" width=\"100%\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>\n </div>\n </div>\n <div class=\"Columnas\">\n \t<div class=\"columna2\">\n \t<h2>Flamingo Cancun Resort</h2>\n <p style=\"font-size:18px\"><span class=\"icon-room\" style=\"color:white\"></span>Blvd. Kukulcán km 11, Zona Hotelera<br>\n <span class=\"icon-phone\" style=\"color:white\"></span>(998) 8 48 8870 Ext. 2613<br>\n <span class=\"icon-web\" style=\"color:white\"></span>www.flamingocancun.com</p>\n \n </div>\n <div class=\"columna2\">\n \t<iframe src=\"https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d465.2339363073808!2d-86.75675404856297!3d21.117688996994982!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8f4c2b0d61aaaaab%3A0x972182d84386ea65!2sHotel+Flamingo+Cancun+Resort!5e0!3m2!1ses!2smx!4v1465250677143\" width=\"100%\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>\n </div>\n </div>\n \n </div><!--hotelesConvoca-->\n <div id=\"comiteConvoca\">\n \t\t<div class=\"Columnas\">\n \t<div class=\"noColumna\">\n\t <h1><span class=\"icon-people\"></span>Comite Local</h1> \n </div>\n </div>\n <div class=\"Columnas\">\n \t<div class=\"columna2\">\n \t<p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>L.I. Alfredo González Estrada<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CEC/Cancún, IPN</p>\n <hr>\n <p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Dr. César Eduardo Mora Ley<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CICATA/Legaria, IPN</p>\n <hr>\n <p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Ing. Enrique Guadarrama López<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CEC/Cancún, IPN</p>\n <hr>\n </div>\n <div class=\"columna2\">\n \t <p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Lic. Hiram Valdez Flores<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CEC/Cancún, IPN</p>\n <hr>\n <p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Lic. Marco Antonio Padilla Villa<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CEC/Cancún, IPN</p>\n <hr> \n <p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Dr. Mario Humberto Ramírez Díaz<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CICATA/Legaria, IPN</p>\n <hr>\n </div>\n </div>\n </div><!--comiteConvoca\"-->\n <div id=\"contactoConvoca\">\n\t\t\t\t\t<div class=\"Columnas\">\n \t<div class=\"noColumna\">\n\t <h1><span class=\" icon-contact_mail\"></span>Contacto</h1>\n <h2 style=\"text-align:left\">Para mayor información, dirigirse a:</h2> \n </div>\n </div>\n <div class=\"Columnas\">\n \t<div class=\"columna2\">\n\t\t\t\t\t\t\t<p style=\"font-size:18px\"><span class=\"icon-people\" style=\"color:white\"></span>Dr. Mario Humberto Ramírez Díaz<br>\n <span class=\"icon-room\" style=\"color:white\"></span>CICATA/Legaria, IPN<br>\n <span class=\"icon-phone\" style=\"color:white\"></span>01 (55) 5729 6000, ext. 67748<br>\n <span class=\"icon-web\" style=\"color:white\"></span>[email protected]</p>\n </div>\n <div class=\"columna2\">\n \t<iframe src=\"https://www.google.com/maps/embed?pb=!1m10!1m8!1m3!1d559.2611455200396!2d-99.20965061464803!3d19.444977646263172!3m2!1i1024!2i768!4f13.1!5e0!3m2!1ses!2smx!4v1465249651944\" width=\"100%\" frameborder=\"0\" style=\"border:0\" allowfullscreen class=\"centrado\"></iframe>\n </div>\n </div>\n\n </div><!--comiteConvoca-->\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.5088105797767639, "alphanum_fraction": 0.5145713090896606, "avg_line_length": 43.712120056152344, "blob_id": "e77e7e645ee6993f37045fe9a04c07a586944b72", "content_id": "be5393198a64d8e2d681f82c3953e2e557742f83", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5911, "license_type": "permissive", "max_line_length": 342, "num_lines": 132, "path": "/resultados.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nif(isset($_GET['id']))\n $idCuestionario=$_GET['id'];\nelse\n $idCuestionario=1;\n?>\n<!doctype html>\n<html lang=\"es\"><!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\"> \t \t \t \t\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\n\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\n\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n $(\".button-collapse\").sideNav();\n // Initialize collapsible (uncomment the line below if you use the dropdown variation)\n //$('.collapsible').collapsible();\n });\n\n </script>\n <body>\n\n <?php \n include(\"barra.html\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"encabezados\" --> \n <?php \n if($banderaSesion == false)\n {\n echo \"<script language='JavaScript' type='text/javascript'> \n \tlocation.href='4mat.php';\n </script>\";\t\n }\n ?> \n <!-- InstanceBeginEditable name=\"Banner\" -->\n <div id='banner'>\n <div class=\"row\"> \n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\" >Registro de usuario</h2> \n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\"/>\n </div>\n </header>\n </div>\n </div>\n <!-- InstanceEndEditable -->\n\n\n <?php \n include(\"minibarra.php\");\n ?>\n\n <!-- InstanceBeginEditable name=\"content\" --> \n <div class=\"contenido\">\n <article> \n <?php\n $conexion = new connection();\t\n $query=\"select c.*,x.nombre from cuestionarioResuelto c,cuestionario x where c.idCuestionario=x.idCuestionario and c.idUsuario=\".$usuario->getId().\" and c.idCuestionario=\".$idCuestionario.\" and c.fecha=(select MAX(fecha) from cuestionarioResuelto where idUsuario=\".$usuario->getId().\" and idCuestionario=\".$idCuestionario.\")\";\n $conexion->conectar();\n $conexion->myQuery($query);\n if($conexion->getFilas())//Si me regresa tuplas significa que ya esta registrado\n {\n $rs=$conexion->getArrayFila();\n $combinacionEstilo=$rs['resultado'];\n $fechaCuestionario=$rs['fecha'];\n $conexion->desconectar();\n $nombreCuestionario=$rs['nombre'];\n $estiloPredominante=explode(\"-\",$combinacionEstilo); //$$estiloPredominante[0]; esta el predominante\n $query=\"select * from estilo where idEstilo=\".$estiloPredominante[0].\"\";\n $conexion->conectar();\n $conexion->myQuery($query);\n $rs=$conexion->getArrayFila();\n $descipcionE=$rs['descripcionE'];\n $conexion->desconectar();\n\n ?> \t\n <h4>Resultado de <?php echo $nombreCuestionario; ?></h4>\n <div id='resultado'>\n <p>Combinacion de estilos: <?php echo $combinacionEstilo; ?></p>\n </div> \n <fieldset>\n <legend>Estilo predominante \"<?php echo $estiloPredominante[0] ?>\" Fecha: <?php echo $fechaCuestionario; ?></legend>\n <p><?php echo $descipcionE; ?></p>\n </fieldset>\n <p>Para obtener más información acerca de los estilos de aprendizaje que emplea el sistema 4MAT o simplemente saber que significa su combinación de estilos resultante de <a href=\"#\" onclick=\"window.open('documentos/Libro_Sistema_4MAT.pdf')\">clic aquí</a></p>\n <?php \n }//Fin si me regresa tuplas\n else\n {\n echo \"<script language='JavaScript' type='text/javascript'> \n \tlocation.href='cuestionario.php?id=\".$idCuestionario.\"'; \n </script>\";\t ////////////////////////////CAMBIAR EL ACTION PARA MANDAR EL IDCUESTIONARIO\n }\n ?> \n </article>\n </div>\n\n <!-- InstanceEndEditable -->\n <footer> \n <!--Aqui va el pie de pagina-->\n <br><p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p><br>\n </footer> \t \t\n </body>\n <!-- InstanceEnd --></html>\n" }, { "alpha_fraction": 0.5154004096984863, "alphanum_fraction": 0.5266940593719482, "avg_line_length": 29.141592025756836, "blob_id": "6a6445a898a1e65c88179b9adc6137223ab1d91a", "content_id": "9520860321713aeb08809465991f2d1042223d7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6823, "license_type": "permissive", "max_line_length": 157, "num_lines": 226, "path": "/encuestaPreguntas.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tsession_start();\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\tmysqli_set_charset($conexion,\"utf8\");\n\t$contesto=$_SESSION[\"acceso\"][3];\n\t//echo $contesto;\n\t$Area=$_SESSION[\"acceso\"][5];\n\techo $_SESSION[\"acceso\"][5];\n\tif($_SESSION[\"acceso\"][7]==21){\n\t\t//checo que sea medico\n\t\tif($_SESSION[\"acceso\"][5]!=2){\n\t\t\t//NO ES MEDICO\n\t\t\techo \"entreeeee\";\n\t\t\t$sqlp=\"update usuario set contestoEncuesta='Si' WHERE id=\".$_SESSION[\"acceso\"][6].\";\";\n\t\t\t$contesto=\"Si\";\n\t\t\tunset($_SESSION[\"acceso\"]);\n\t\t\t$paises=mysqli_query($conexion,$sqlp);\n\t\t}\n\t}\n\tif($_SESSION[\"acceso\"][7]==26){\n\t\t//YA ACABO\n\t\t\n\t\t$sqlp=\"update usuario set contestoEncuesta='Si' WHERE id=\".$_SESSION[\"acceso\"][6].\";\";\n\t\t$contesto=\"Si\";\n\t\t$paises=mysqli_query($conexion,$sqlp);\n\t\tunset($_SESSION[\"acceso\"]);\n\t}\t\n\t//$_SESSION[\"acceso\"][7]=2;\n\t///////////////////////////////////////////////////////$_SESSION[\"acceso\"][7]=1;\n\t//// OBTENGO LA ULTIMA PREGUNTA QUE CONTESTO EL USUARIO\n\t//echo $_SESSION[\"acceso\"][6];\n\t$sql=\"select UltimaPregunta from usuario where id=\".$_SESSION[\"acceso\"][6].\";\";\n\t$pai=mysqli_query($conexion,$sql);\n\tif($pai)//Si me regresa tuplas significa que ya esta registrado\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\twhile($cuba=mysqli_fetch_array($pai,MYSQLI_BOTH)){\n\t\t\t\t\t\t\t$cuba[0]+=1;\n\t\t\t\t\t\t\t$_SESSION[\"acceso\"][7]=$cuba[0];\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t//echo $cuba[0];\n\t}\n\t\t\t\t\t\n\t\t\t\t}\n\telse{\n\t\techo mysqli_error($conexion);\n\t}\n\t\n\n\t$sqlp=\"select pregunta,pathImg from pregunta where idPregunta=\".$_SESSION[\"acceso\"][7].\";\";\n\t$paises=mysqli_query($conexion,$sqlp);\n\t$sql=\"select * from opciones where idPregunta=\".$_SESSION[\"acceso\"][7].\";\";\n\t$respuestas=mysqli_query($conexion,$sql);\n\t//echo $Area;\n\t\n\tif($Area==1 || $Area==2 || $Area==3)\n\t{\n\t\tif(strcmp(\"No\", $contesto)==0){\n\t\t\t\n\t\t\t\n?>\n\n\n<!doctype html>\n<html lang=\"es\">\n <!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\t\t\t//alert(\"Hola\");\n $('.modal').modal();\n \n $(\".button-collapse\").sideNav();\n // Initialize collapsible (uncomment the line below if you use the dropdown variation)\n //$('.collapsible').collapsible();\n \n\t\t$(\"#btn-Registrar\").click(function(e) {\n\t\t\t//alert(\"hola\");\t\n\t\t\t//alert($(\"#respuesta\").serialize());\n\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/registraRespuesta.php\",\n\t\t\t\tdata: $(\"#respuesta\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\talert(resp);\n\t\t\t\t\tlocation.reload();\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t\t});\n\t\t});\n\n\n </script>\n\n <body>\n\n <?php\n include (\"barra.html\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"encabezados\" -->\n <div id='banner'>\n <div class=\"row\">\n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n </div>\n </header>\n </div>\n </div>\n\n\n\n\n\n <?php \n include(\"BarraConfiguracion.php\");\n ?>\n\n <!-- InstanceBeginEditable name=\"content\" -->\n <div class=\"contenido\">\n <h2 style=\"color:black;\"><?php echo \"Pregunta \".$_SESSION[\"acceso\"][7];?></h2>\n \n \n <a><input type=\"text\" placeholder=\"username\" name=\"Empezar Encuesta\" href=\"encuesta.php\"></a>\n <ul>\n <li>\n <?php\n\t\t\t\t\t\twhile($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t\t\t\t\t\techo $pais[0];\n\n\t\t\t\t\t\t\n\t\t\t\t\t?>\n </li>\n </ul> \n <?php\n\t\t\t\t\t\techo \"<div class='row'><div class='col s6 offset-s4'><img src='$pais[1]' class='materialboxed'></div></div>\";\t\n\t\t\t\t\t\t}\n\t\t\t?>\n \n \n \n <form action=\"#\" id=\"respuesta\" name=respuesta>\n \t<?php\n\t\t\t \twhile($miau=mysqli_fetch_array($respuestas,MYSQLI_BOTH)){\n\t\t\t\t\techo \"<p><input name='group1' type='radio' id='\".$miau[0].\"' value='\".$miau[0].\"'><label for='\".$miau[0].\"'></label>\".$miau[1].\"</p>\";\n\t\t\t\t}\n\t\t\t ?>\n \n \n \n \n \n <div class=\"row\">\n \n <div class=\"row\">\n <div class=\"input-field col s12\">\n <textarea id=\"opinion\" class=\"materialize-textarea\" name=\"opinion\"></textarea>\n <label for=\"textarea1\">Opinion De la Pregunta</label>\n </div>\n </div>\n </div>\n </form>\n \n <div class=\"input-field col s6\" style=\"padding-left:45%;\">\n\t\t\t\t\t\t\t\t\t<a href=\"encuestaPreguntas.php\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" id=\"btn-Registrar\" name=\"btn-Registrar\" >Siguiente\n\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons right\">send</i>\n </button></a>\n\t\t\t\t\t\t\t\t</div>\n \n </div>\n <!-- InstanceEndEditable -->\n <footer>\n <!--Aqui va el pie de pagina-->\n <br>\n <p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n <br>\n </footer>\n </body>\n <!-- InstanceEnd -->\n\n</html>\n<?php\n\t\t\t\t\t\t }\n\t\telse{\n\t\t\techo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n\t\t}\n\t}\n\telse{\n\t\t\n\t\techo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n\t}\n\n?>\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7541609406471252, "alphanum_fraction": 0.7578813433647156, "avg_line_length": 73.02173614501953, "blob_id": "375126b7af6a61e43dbcb0d470421b65c6cac6bf", "content_id": "25d10085b2e93e6cfa7cae5c42b21ff53d28b54d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 10463, "license_type": "permissive", "max_line_length": 237, "num_lines": 138, "path": "/public_html/app/templates/normatividad.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n<div class=\"Columnas\">\n\t\t\t<!-- Aqui va el contenido del contenedor blanco-->\n <article class=\"noColumna\">\n\t\t<h1> Constitución de la AAPT-MX </h1>\n\t\t<h2> ARTÍCULO I: NOMBRE </h2>\n\t\t\t<p>El nombre de la Asociación es “Asociación Americana de Profesores de Física,\n\t\t\tSección México”. En todas sus actividades, se referirá a ella como la “AAPT-MX”.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO II: OBJETIVOS </h2>\n\t\t\t<p>\n\t\t\tLos objetivos de la Asociación serán mejorar la calidad de la educación en la Física\n\t\t\ten el país, incrementar la presencia del rol que cumplen las diversas actividades\n\t\t\trealizadas dentro de la Física en nuestro entorno y mantener una comunicación\n\t\t\tefectiva entre todos aquellos que se dediquen a la educación en Física, en todos\n\t\t\tlos niveles académicos. El trabajo de esta Asociación será estrictamente para\n\t\t\tfines educativos, tecnológicos y científicos.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO III: MEMBRESÍA </h2>\n\t\t\t<p>\n\t\t\tExistirán cuatro tipos diferentes de membresía: la membresía regular, la membresía estudiantil, la membresía emérita y la membresía honoraria.\n\t\t\t\t<ol>\n\t\t\t\t<li>La membresía regular se concederá a profesores de física en los todos los niveles educativos y a cualquier otra persona que, a juicio del Consejo (artículo VI), contribuya al cumplimiento de los objetivos de esta Asociación.</li>\n\t\t\t\t<li>La membresía estudiantil se concederá a estudiantes universitarios inscritos en cualquier institución educativa a partir de su segundo año de su programa de estudios.</li>\n\t\t\t\t<li>Serán miembros eméritos aquellas personas que sean miembros regulares antes de jubilarse y que, antes de su retiro, soliciten esta membresía al Consejo.</li>\n\t\t\t\t<li>Será prerrogativa del Consejo otorgar membresías honorarias. Los poseedores de dicha membresía tendrán todos los privilegios de un miembro regular, sin tener que cubrir ningún tipo de cuota.</li>\n\t\t\t\t</ol>\n\n\t\t\t</p>\n\t\t<h2> ARTÍCULO IV: DIRECTIVOS </h2>\n\t\t\t<p>Los directivos de la Asociación serán: Un Presidente, un Presidente Electo, un Vicepresidente, un Consejero asesor y un Tesorero.\n\t\t\t\t<ol>\n\t\t\t\t\t<li>El presidente será responsable de los asuntos que conciernen a la Asociación y deberá presidir todas las reuniones\n\t\t\t\t\tdel Consejo, así como cualquier otra reunión de los directivos o de la Asociación. El presidente tendrá el poder de nombrar\n\t\t\t\t\tcomités y remplazar a los miembros del Consejo según lo descrito en los artículos VI y VII de este documento. El Presidente\n\t\t\t\t\tserá quien autorice los gastos de los fondos de la Asociación. El periodo de mandato de un Presidente iniciará al final de \n\t\t\t\t\tla junta anual y durará un año. Después ocupará el puesto de Consejero asesor.</li>\n\t\t\t\t\t<li>El Presidente Electo asumirá la función de co-presidir en todas las reuniones y será el coordinador general de las \n\t\t\t\t\treuniones anuales de la sección. El Presidente Electo podrá tener otras funciones si el Consejo lo determina. Ocupará este\n\t\t\t\t\tcargo hasta el final de la junta anual, cuando asumirá el puesto de Presidente.</li>\n\t\t\t\t\t<li>El Consejero asesor será el representante oficial de la AAPT-MX frente a todas las sociedades designadas por el Consejo.\n\t\t\t\t\tEl Consejero asesor presidirá el Comité de Nominaciones, y podrá tener otras funciones si lo decide así el Consejo.\n\t\t\t\t\t</li>\n\t\t\t\t\t<li>El Vicepresidente apoyará al Presidente y al Presidente Electo en sus funciones, y podrá tener otras funciones si así\n\t\t\t\t\tlo decide el Consejo. El Vicepresidente tendrá este puesto durante un año, hasta el final de la junta anual, cuando tomará\n\t\t\t\t\tel puesto de Presidente Electo.\n\t\t\t\t\t</li>\n\t\t\t\t\t<li>5.\tEl Tesorero tendrá todas las funciones relacionadas con las finanzas de la Sección, en particular, deberá recolectar\n\t\t\t\t\tlas cuotas de los miembros, será quien administre los fondos y cubra los gastos generados por la Sección; deberá mantener un\n\t\t\t\t\tregistro de todos los gastos e ingresos de fondos y presentar un reporte del estado financiero de la Sección en cada junta\n\t\t\t\t\tregular. El Tesorero tendrá este puesto durante cuatro años, empezando al final de la junta anual que corresponda y podrá ser reelegido.\n\t\t\t\t\t</li>\n\t\t\t\t</ol>\n\t\t\t</p>\n\t\t<h2> ARTÍCULO V: REPRESENTANTE DE SECCIÓN </h2>\n\t\t\t<p>\n\t\t\tEl Representante de la Sección en el Consejo será responsable de representar a la Sección en todas las juntas de la AAPT y de servir\n\t\t\tcomo medio de comunicación entre la Sección y la AAPT. Además, fungirá como secretario del Sección y deberá llevar los registros de la\n\t\t\tSección. Podrá tener otras funciones si el Consejo de la Sección así lo dispone.<br>\n\t\t\tEl Representante de la Sección dirigirá el Comité de Premiación.<br>\n\t\t\tSi el Representante de Sección no puede asistir a una junta de Representantes de Sección de la AAPT, deberá designar un sustituto quien\n\t\t\tdeberá ser miembro de la Sección y de la AAPT. El Representante deberá notificar este cambio al Secretario de la AAPT por escrito antes\n\t\t\tde la junta. El Representante de la Sección tendrá este puesto durante cuatro años, empezando al final de la junta anual que corresponda\n\t\t\ty podrá ser reelegido. <br>\n\n\t\t\t</p>\n\t\t<h2> ARTÍCULO VI: EL CONSEJO </h2>\n\t\t\t<p>\n\t\t\tLa Asociación será gobernada por un Consejo que consistirá de los directivos, el Representante de Sección y 3 miembros generales quienes\n\t\t\tademás deberán ser miembros de la AAPT. Los miembros generales tomarán el cargo en la junta anual, después de las elecciones, por un \n\t\t\tperiodo de 3 años, de tal manera que un miembro sea elegido cada año. Los miembros generales podrán ser reelegidos. Los tres miembros\n\t\t\tgenerales deben ser representantes de cada uno de los siguientes niveles educativos: educación superior, media superior y básica. Si un\n\t\t\tmiembro del Consejo no puede fungir sus funciones deberá ser reemplazado, dicha acción requiere que dos terceras partes del Consejo estén\n\t\t\tde acuerdo. En el caso de que algún oficial o miembro del Consejo se vea imposibilitado de cumplir temporalmente sus funciones, el \n\t\t\tPresidente está facultado a nombrar un sustituto temporal. <br>\n\t\t\tEl quórum se definirá como la mayoría del Consejo, es decir cinco miembros de nueve que forman el consejo.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO VII: COMITÉS </h2>\n\t\t\t<p>\n\t\t\t\tExistirán dos comités: El Comité de Nominaciones al Consejo y el Comité de Premiación. <br>\n\t\t\t\tEl Comité de Nominaciones será presidido por el Consejero asesor, e incluye miembros representantes de los tres grupos mencionados\n\t\t\t\ten el Artículo VI, nominados por el Presidente y aprobados por el Consejo. El Comité de Nominaciones deberá recibir los resultados\n\t\t\t\tde la convocatoria realizada por el Presidente y, usando esta información y su propio criterio, presentar una lista de posiciones\n\t\t\t\tdisponibles y sus candidatos al Presidente. El Comité de Nominaciones tiene la responsabilidad de asegurarse de que los candidatos\n\t\t\t\tpropuestos estén de acuerdo en asumir los cargos para los que han sido nominados. El Presidente se asegurará de que todos los miembros\n\t\t\t\testén al tanto de esta información al menos tres meses antes de la junta anual. <br>\n\t\t\t\tEl Comité de Premiación será presidido por el Representante de Sección e incluirá a otros dos miembros escogidos y aprobados por el Consejo.<br>\n\t\t\t\tEl Presidente y el Consejo nombrarán otros comités con el número de miembros que ellos consideren pertinente para el posterior \n\t\t\t\tdesarrollo de la Asociación. Dichos comités dejarán de existir, a más tardar, en la junta anual. Los comités podrán ser reestablecidos.\n\n\t\t\t</p>\n\t\t<h2> ARTÍCULO VIII: ELECCIONES </h2>\n\t\t\t<p>\n\t\t\t\tLos directivos, miembros generales del Consejo y el Representante de Sección deberán ser elegidos por la mayoría de los miembros\n\t\t\t\tde la Asociación, presentes y votando en la junta anual. Los candidatos a cualquier posición deberán ser miembros de la Sección,\n\t\t\t\tnominados por el Comité de Nominaciones o directamente en una junta o por petición escrita del Presidente, firmada por al menos\n\t\t\t\tdiez miembros de la Sección, máximo 2 meses antes de la elección. La pluralidad de votos asegura la elección. En caso de empate, \n\t\t\t\tel Presidente decidirá quién es el ganador al azar. \n\t\t\t</p>\n\t\t<h2> ARTÍCULO IX: CUOTAS </h2>\n\t\t\t<p>\n\t\t\t\tLas cuotas serán establecidas por el Consejo de Sección y se usarán para cubrir los gastos generados por la Asociación. El año fiscal \n\t\t\t\tde la Asociación comenzará el 1° de Mayo.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO X: JUNTAS </h2>\n\t\t\t<p>\n\t\t\t\tDeberá haber una junta anual, organizada por el Consejo. Todos los miembros de la Asociación deberán ser notificados oportunamente\n\t\t\t\tsobre la fecha, la hora y el lugar. El Consejo, junto con los presidentes, fijarán las cuotas de registro.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO XI: NO DISCRIMINACIÓN </h2>\n\t\t\t<p>\n\t\t\t\tLa Asociación no discriminará por raza, religión, color, nacionalidad o sexo.\n\t\t\t</p>\n\t\t<h2> ARTÍCULO XII: ORGANIZACIÓN SIN FINES DE LUCRO </h2>\n\t\t\t<p>\n\t\t\t\t<ol>\n\t\t\t\t\t<li>Sin contravenir ninguna disposición de la Constitución, esta Asociación no deberá realizar ninguna actividad con fines de lucro.</li>\n\t\t\t\t\t<li>Esta asociación continuará indefinidamente a menos que dos terceras partes de los miembros voten a favor de disolver la Asociación. \n\t\t\t\t\tDicha votación deberá ser llevada a cabo siguiendo las indicaciones del Consejo. Las propuestas para disolver la Asociación pueden ser \n\t\t\t\t\tpuestas a votación en cualquier momento. En el caso de que la Asociación sea disuelta, el Consejo, después de cubrir las cuentas pendientes,\n\t\t\t\t\tdistribuirá los fondos restantes entre organizaciones educativas, científicas o de caridad.</li>\n\t\t\t\t</ol>\n\t\t\t</p>\n\t\t<h2> ARTÍCULO XIII: MODIFICACIONES </h2>\n\t\t\t<p> Esta Constitución será modificada siempre y cuando:\n\t\t\t\t<ol>\n\t\t\t\t\t<li>Dos terceras partes de los miembros voten a favor y siempre y cuando los miembros hayan recibido información sobre la\n\t\t\t\t\tmodificación al menos dos semanas antes de la junta donde se realizará la votación.</li>\n\t\t\t\t\t<li>O que dos terceras partes de los miembros voten a favor en una votación por correo, organizada por el Consejo.</li>\n\t\t\t\t</ol>\n\t\t\t\tAdoptada por la Sección el 9 de agosto de 2008\n\t\t\t</p>\n\t\t\n\t</article> \n</div><!--Columnas-->\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.6412469744682312, "alphanum_fraction": 0.6522781848907471, "avg_line_length": 32.095237731933594, "blob_id": "a6cf14ef1da8b2f8a7713e8e5a5adb6213536477", "content_id": "5191419dce7ca431ee1075e0fe76fc3a95f79113", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4197, "license_type": "permissive", "max_line_length": 671, "num_lines": 126, "path": "/4mat.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html lang=\"es\">\n\t<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n\t<head>\n\t\t<?php require_once(\"controlador/verificar.php\");\n\t\trequire_once(\"controlador/connection.php\");\n\t\t?>\n\t\t<meta charset=\"utf-8\">\n\n\t\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\t\t<script src=\"https://code.jquery.com/jquery-3.0.0.js\"></script>\n\t\t<script src=\"https://code.jquery.com/jquery-migrate-3.0.0.js\"></script>\n\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n\t\t<!-- links-->\n\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n\t\t<title>Grupo de investigación en la enseñanza de física</title>\n\t</head>\n\t<script>\n\t\t$(document).ready(function() {\n\n\n\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t// Initialize collapse button\n\t\t\t\n\t\t});\n\n\n\n\t</script>\n\n\t<body>\n\n\t\t<?php\n\t\tinclude (\"barra.html\");\n\t\t?>\n\n\n\t\t<!-- InstanceBeginEditable name=\"encabezados\" -->\n\t\t<div id='banner'>\n\t\t\t<div class=\"row\">\n\t\t\t\t<header>\n\t\t\t\t\t<div class=\"col s12 m5 l6\">\n\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t<h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"col s12 m6 l6\">\n\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t</div>\n\t\t\t\t</header>\n\t\t\t</div>\n\t\t</div>\n\n\n\n\n\t\t<?php \n\t\tinclude(\"minibarra.php\");\n\t\t?>\n\n\n\t\t<!-- InstanceBeginEditable name=\"content\" -->\n\t\t<div class=\"contenido\">\n\t\t\t<?php if($banderaSesion == false){ ?>\n\t\t\t<div class=\"row\">\n\t\t\t\t<article>\n\t\t\t\t\t<div class=\"col s12 m10 l6\">\n\n\t\t\t\t\t\t<img src=\"images/Bienvenidos.png\" style=\" width: 60%;\" />\n\n\t\t\t\t\t\t<p>En esta página encontrará una serie de instrumentos para evaluar estilos de aprendizaje, estilos de enseñanza y hemisfericidad cerebral.</p>\n\t\t\t\t\t\t<p>Al contestarlo nos ayudaras en diversos proyectos de investigación educativa, tus datos se guardarán de manera confidencial.</p>\n\t\t\t\t\t\t<p>Siga las siguientes indicaciones:</p>\n\t\t\t\t\t\t<br />\n\t\t\t\t\t\t<ol>\n\t\t\t\t\t\t\t<li><strong>Si no se a registrado, se necesita crear una cuenta.</strong></li>\n\t\t\t\t\t\t\t<li><strong>Si esta registrado, por favor accese a su cuenta, con el login de usuario y su password.</strong></li>\n\t\t\t\t\t\t\t<li><strong>Ya dentro de su cuenta , por favor introduzca los datos que se le solicitan.</strong></li>\n\t\t\t\t\t\t</ol>\n\t\t\t\t\t</div>\n\t\t\t\t</article>\n\n\t\t\t\t<div class=\"col s12 m10 l6\">\n\t\t\t\t\t<?php\n\tinclude(\"login.html\");\n\t\t\t\t\t?>\n\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<?php }\n\t\t\telse\n\t\t\t{\n\t\t\t?> \n\t\t\t<br>\n\t\t\t<br>\n\t\t\t<br>\n\t\t\t<h4>Bienvenido</h4>\n\t\t\t<article>\n\n\t\t\t\t<p>Mario H. Ramírez Díaz. Actualmente es profesor titular en el programa de posgrado en Física Educativa del Centro de Investigación en Ciencia Aplicada y Tecnología Avanzada del Instituto Politécnico Nacional de México. Es Doctor en Física Educativa, Maestro en Ciencias con Especialidad en Física y Licenciado en Física y Matemáticas, todos por el Instituto Politécnico Nacional. Ha sido profesor en varias Universidades en México y es miembro del Sistema Nacional de Investigadores. Sus trabajos de investigación y publicaciones incluyen los Estilos de aprendizaje, el modelo de educación por competencias y la enseñanza de la física, además de trabajos sobre la sociofísica.</p>\n\t\t\t\t<div class=\"centrado\"><img src=\"images/bienvenida.jpg\" alt=\"Bienvenido\"></div>\n\t\t\t</article>\n\t\t\t<?php\n\t\t\t}\n\t\t\t?>\n\t\t</div>\n\t\t<!-- InstanceEndEditable -->\n\t\t<footer>\n\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t<br>\n\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t<br>\n\t\t</footer>\n\t</body>\n\t<!-- InstanceEnd -->\n\n</html>\n" }, { "alpha_fraction": 0.615695059299469, "alphanum_fraction": 0.6221973299980164, "avg_line_length": 35.557376861572266, "blob_id": "6394b3f429465f141f3e702c89b817a49580cbb6", "content_id": "6e0c4450d5d8976135dafc8de1ce557f5fcb030f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4461, "license_type": "permissive", "max_line_length": 133, "num_lines": 122, "path": "/borrar/cuestionario.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php require_once('../Connections/rem.php'); ?>\n<?php\nif (!function_exists(\"GetSQLValueString\")) {\nfunction GetSQLValueString($theValue, $theType, $theDefinedValue = \"\", $theNotDefinedValue = \"\") \n{\n if (PHP_VERSION < 6) {\n $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;\n }\n\n $theValue = function_exists(\"mysql_real_escape_string\") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);\n\n switch ($theType) {\n case \"text\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break; \n case \"long\":\n case \"int\":\n $theValue = ($theValue != \"\") ? intval($theValue) : \"NULL\";\n break;\n case \"double\":\n $theValue = ($theValue != \"\") ? doubleval($theValue) : \"NULL\";\n break;\n case \"date\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break;\n case \"defined\":\n $theValue = ($theValue != \"\") ? $theDefinedValue : $theNotDefinedValue;\n break;\n }\n return $theValue;\n}\n}\n\n$editFormAction = $_SERVER['PHP_SELF'];\nif (isset($_SERVER['QUERY_STRING'])) {\n $editFormAction .= \"?\" . htmlentities($_SERVER['QUERY_STRING']);\n}\n\nif ((isset($_POST[\"MM_update\"])) && ($_POST[\"MM_update\"] == \"form2\")) {\n $updateSQL = sprintf(\"UPDATE cuestionario SET nombre=%s, instrucciones=%s WHERE idCuestionario=%s\",\n GetSQLValueString($_POST['nombre'], \"text\"),\n GetSQLValueString($_POST['instrucciones'], \"text\"),\n GetSQLValueString($_POST['idCuestionario'], \"int\"));\n\n mysql_select_db($database_rem, $rem);\n $Result1 = mysql_query($updateSQL, $rem) or die(mysql_error());\n}\n\nmysql_select_db($database_rem, $rem);\n$query_verCuest = \"SELECT * FROM cuestionario\";\n$verCuest = mysql_query($query_verCuest, $rem) or die(mysql_error());\n$row_verCuest = mysql_fetch_assoc($verCuest);\n$totalRows_verCuest = mysql_num_rows($verCuest);\n\n$colname_buscarCuest = \"-1\";\nif (isset($_POST['idCuestionario'])) {\n $colname_buscarCuest = $_POST['idCuestionario'];\n}\nmysql_select_db($database_rem, $rem);\n$query_buscarCuest = sprintf(\"SELECT * FROM cuestionario WHERE idCuestionario = %s\", GetSQLValueString($colname_buscarCuest, \"int\"));\n$buscarCuest = mysql_query($query_buscarCuest, $rem) or die(mysql_error());\n$row_buscarCuest = mysql_fetch_assoc($buscarCuest);\n$totalRows_buscarCuest = mysql_num_rows($buscarCuest);\n?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>Documento sin título</title>\n</head>\n\n<body>\n<form id=\"form1\" name=\"form1\" method=\"post\" action=\"\">\nid Cuestionario\n <input type=\"text\" name=\"idCuestionario\" id=\"idCuestionario\" />\n <input type=\"submit\" name=\"buscar\" id=\"buscar\" value=\"Enviar\" />\n</form>\n<p>&nbsp;</p>\n<form action=\"<?php echo $editFormAction; ?>\" method=\"post\" name=\"form2\" id=\"form2\">\n <table align=\"center\">\n <tr valign=\"baseline\">\n <td nowrap=\"nowrap\" align=\"right\">IdCuestionario:</td>\n <td><?php echo $row_buscarCuest['idCuestionario']; ?></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap=\"nowrap\" align=\"right\">Nombre:</td>\n <td><input type=\"text\" name=\"nombre\" value=\"<?php echo $row_buscarCuest['nombre']; ?>\" size=\"32\" /></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap=\"nowrap\" align=\"right\">Instrucciones:</td>\n <td><textarea name=\"instrucciones\" rows=\"15\" cols=\"100\"><?php echo $row_buscarCuest['instrucciones']; ?></textarea></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap=\"nowrap\" align=\"right\">&nbsp;</td>\n <td><input type=\"submit\" value=\"Actualizar registro\" /></td>\n </tr>\n </table>\n <input type=\"hidden\" name=\"MM_update\" value=\"form2\" />\n <input type=\"hidden\" name=\"idCuestionario\" value=\"<?php echo $row_buscarCuest['idCuestionario']; ?>\" />\n</form>\n<p>&nbsp;</p>\n<table border=\"1\">\n <tr>\n <td>idCuestionario</td>\n <td>nombre</td>\n <td>instrucciones</td>\n </tr>\n <?php do { ?>\n <tr>\n <td><?php echo $row_verCuest['idCuestionario']; ?></td>\n <td><?php echo $row_verCuest['nombre']; ?></td>\n <td><?php echo $row_verCuest['instrucciones']; ?></td>\n </tr>\n <?php } while ($row_verCuest = mysql_fetch_assoc($verCuest)); ?>\n</table>\n</body>\n</html>\n<?php\nmysql_free_result($verCuest);\n\nmysql_free_result($buscarCuest);\n?>\n" }, { "alpha_fraction": 0.48435544967651367, "alphanum_fraction": 0.4997914135456085, "avg_line_length": 32.7746467590332, "blob_id": "1838b73bb2afee54547c39757f876244279e579e", "content_id": "20b319491765648822809e07bcdc2ed82f1e411d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2400, "license_type": "permissive", "max_line_length": 174, "num_lines": 71, "path": "/minibarra.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<script>\n $(document).ready(function() {\n\n $(document).ready(function(){\n $('.collapsible').collapsible();\n });\n });\n</script>\n<?php if($banderaSesion){ ?>\n<div class=\"row\">\n<div class=col s20 style=\"float:right;\">\n<div id='menu2'>\n\n\n <!------PONER ID ACTUAL AL QUE ESTES EDITANDO---------------->\n <div class=\"chip\">\n <img src=\"images/persona.jpg\" alt=\"Contact Person\">\n <?php echo \"\".$usuario->getNombre().\"\"; ?>\n </div>\n <ul class=\"collapsible\" data-collapsible=\"accordion\" style=\"display:inline-block;\">\n <?php if($banderaEllos == false){ ?>\n\n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">supervisor_account\n </i><a href=\"administrador.php\">Administración</a></div>\n\n </li>\n <?php } \n $conexion = new connection();\n $query=\"select * from cuestionario\";\n $conexion->conectar();\n $conexion->myQuery($query); \n ?> \n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">message</i>Responder cuestionario</div>\n <div class=\"collapsible-body\">\n\n <?php\n while($rs=$conexion->getArrayFila())//Si me regresa tuplas significa que existen cuestionarios\n {\n echo \" <p ><a style='border-bottom:1px solid #ddd;' href=\\\"cuestionario.php?id=\".$rs['idCuestionario'].\"\\\">\".$rs['nombre'].\"</a></p>\";\n ?>\n\n <a class=\"\" href=\"resultados.php?id=<?php echo $rs['idCuestionario'] ?>\"> &#160; &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#160; &#160; Resultado</a>\n\n\n <?php echo \"\"; } $conexion->desconectar();?>\n </div>\n </li>\n\n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">person_pin</i>\n Mi Perfil\n </div>\n <div class=\"collapsible-body\"><p><a href=\"modificar.php\">Modificar Datos</a><br> <a href=\"modcontra.php\">Modificar Contraseña</a></p></div>\n </li>\n\n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">settings_power</i><a href=\"controlador/logout.php\">Cerrar Sesión</a></div>\n\n </li>\n </ul>\n\n\n\n\n</div>\n </div>\n</div>\n\n<?php } ?>" }, { "alpha_fraction": 0.5734346508979797, "alphanum_fraction": 0.5831031203269958, "avg_line_length": 48.931034088134766, "blob_id": "d67ddde7f3e6702985f1d814124a5660ae964387", "content_id": "d076ada88b80f1ae1f0399e1148217db81351856", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4373, "license_type": "permissive", "max_line_length": 823, "num_lines": 87, "path": "/index.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html lang=\"es\"><!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n\n <meta charset=\"utf-8\">\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\"> \n\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\n\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n \n <script>\n \n $(document).ready(function(){\n // the \"href\" attribute of the modal trigger must specify the modal ID that wants to be triggered\n $('.modal').modal();\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n });\n \n </script>\n \n <body>\n <?php\n include (\"barra.html\");\n ?>\n <!-- InstanceBeginEditable name=\"encabezados\" --> \n\n <div id='banner'>\n <div class=\"row\">\n <header>\n <div class=\"col s12 m5 l6\">\n <h2>Bienvenidos <img src=\"images/corazonazul.png\" alt=\"logo\" width=\"80%\" /></h2>\n </div>\n <div class=\"col s12 m5 l6\">\n <img src=\"images/logoIndex.png\" alt=\"logo\" width=\"80%\" />\n </div>\n </header>\n </div>\n </div>\n <!-- Si tiene una sesion abierta -->\n <?php\n include(\"minibarra.php\");\n ?>\n\n <!-- InstanceBeginEditable name=\"content\" --> \n <div class=\"contenido\">\n <div class=\"row\">\n <article>\n <div class =\"col s12 m12 l6\">\n <p>Esta es la página del Grupo de Investigación en Física Educativa. Este grupo está formado por investigadores interesados en los procesos de aprendizaje, enseñanza, evaluación, gestión administrativa e investigación educativa alrededor de la física. Somos profesores de nivel bachillerato, universitario y posgrado que hemos tenido la oportunidad de retroalimentar nuestras experiencias docentes y de investigación en la enseñanza de la física. Nuestro grupo trabajan invegadores de diferentes centros educativos distribuidos en la república Mexicana como son: IPN, UNAM, ITESM, Universidad de Coahuila, UANL, Universidad Politécnica del Centro, Universidad de la Ciudad de México entre otros y estamos abiertos a profesores e investigadores de todo el país que deseen integrarse con nosotros.</p>\n\n </div>\n <div class=\"col s15 m11 l5\">\n <div class =\"imagen\">\n <img src=\"images/lapIma.png\" />\n </div>\n </div>\n <div class=\"col s12 m12 l10\">\n <p>En este portal hallaras cuestionarios, artículos de interés, ligas y otros tópicos que te pueden ser de interés si estas en el área de la docencia de la física, como profesor o investigador. Nuestro objetivo final es la mejora del aprendizaje de la física a todos los niveles y modalidades, esperamos que esta página sea de tu interés y te agradecemos el colaborar con nosotros.</p>\n </div>\n </article>\n\n </div>\n\n </div>\n <!-- InstanceEndEditable -->\n <footer> \n <!--Aqui va el pie de pagina-->\n <br><p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p><br>\n </footer> \t \t\n </body>\n <!-- InstanceEnd --></html>\n" }, { "alpha_fraction": 0.5721518993377686, "alphanum_fraction": 0.5825086236000061, "avg_line_length": 33.07843017578125, "blob_id": "95415403314b44651c4e38247d17af5c134d26ab", "content_id": "ef1661b434503f9f4206edb9ee8317920192a55a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8694, "license_type": "permissive", "max_line_length": 296, "num_lines": 255, "path": "/controlador/busqueda.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\t\n\tclass Busqueda{\n\t\tprivate $txtBuscar;\n\t\tprivate $idCuestionario;\n\t\tprivate $sexo;\n\t\tprivate $txtFechaNac1;\n\t\tprivate $txtFechaNac2;\n\t\tprivate $txtFechaRe1;\n\t\tprivate $txtFechaRe2;\n\t\t\n\t\tprivate $query;\n\t\tprivate $matrizResultados;\n\t\tprivate $banderaImprimir;\n\t\t\n\t\tpublic function Busqueda(){\n\t\t\t$this->txtBuscar = \"\";\n\t\t\t$this->idCuestionario = 1;\n\t\t\t$this->sexo = \"\";\n\t\t\t$this->txtFechaNac1 = \"\";\n\t\t\t$this->txtFechaNac2 = \"\";\n\t\t\t$this->txtFechaRe1 = \"\";\n\t\t\t$this->txtFechaRe2 = \"\";\n\t\t\t\n\t\t\t$this->query = \"\";\n\t\t\t$this->banderaImprimir = false;\n\t\t}\n\t\t\n\t\tpublic function principal(){\n\t\t\tif(isset($_POST['btnALL'])){\n\t\t\t\t$this->mostrarTodos();\n\t\t\t\t$_SESSION['ma'] = serialize($this->matrizResultados);\n\t\t\t}\n\t\t\tif(isset($_POST['btnBuscar'])){\n\t\t\t\t$this->busquedaFiltrada();\n\t\t\t\t$_SESSION['ma'] = serialize($this->matrizResultados);\n\t\t\t}\n\t\t\tif(isset($_GET['cr'])){\n\t\t\t\t$this->matrizResultados = unserialize($_SESSION['ma']);\n\t\t\t\t$this->matrizResultados = $this->ordenarTuplas($this->matrizResultados,$_GET['cr']);\n\t\t\t\t$this->banderaImprimir = true;\n\t\t\t}\n\t\t\t\n\t\t\tif($this->banderaImprimir){\n\t\t\t\t$this->llenarTabla($this->matrizResultados, count($this->matrizResultados));\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic function mostrarTodos(){\n\t\t\t$this->idCuestionario = $_POST['idCuest'];\n\t\t\t$this->query = \"SELECT u.nombre, u.fechaNac, u.sex, u.ocupacion, u.institucion, r.fecha, r.resultado, TIMESTAMPDIFF(YEAR,u.fechaNac, CURRENT_DATE) as edad FROM usuario u, cuestionarioResuelto r WHERE u.idUsuario = r.idUsuario AND r.idCuestionario = \".$this->idCuestionario.\" ORDER BY r.fecha\";\n\t\t\t$conexion = new connection();\n\t\t\t$conexion->conectar();\n\t\t\t$conexion->myQuery($this->query);\n \t\t\t\n\t\t\tif($conexion->getFilas() > 0){\n\t\t\t\t$this->matrizResultados = $this->getMatrizResultados($conexion);\n\t\t\t\t$this->banderaImprimir = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\techo \"<p><strong>No hay resultados para mostrar :(</strong></p>\";\n\t\t\t\t$this->banderaImprimir = \"false\";\n\t\t\t}\n\t\t\t$conexion->desconectar();\n\t\t}\n\t\t\n\t\tpublic function busquedaFiltrada(){\n\t\t\t$banderaError = false;\n\t\t\t$this->idCuestionario = $_POST['idCuest'];\n\t\t\t$this->query = \"SELECT u.nombre, u.fechaNac, u.sex, u.ocupacion, u.institucion, r.fecha, r.resultado, TIMESTAMPDIFF(YEAR,u.fechaNac, CURRENT_DATE) as edad FROM usuario u, cuestionarioResuelto r WHERE u.idUsuario = r.idUsuario AND r.idCuestionario = \".$this->idCuestionario.\" \";\n\t\t\t$var_desicion = 0;\n\t\t\tif($_POST['fechaNac2'] != \"\"){\n\t\t\t\t$var_desicion += 1;\n\t\t\t}\n\t\t\tif($_POST['fechaNac1'] != \"\"){\n\t\t\t\t$var_desicion += 2;\n\t\t\t}\n\t\t\tif($_POST['fechaCuest2'] != \"\"){\n\t\t\t\t$var_desicion += 4;\n\t\t\t}\n\t\t\tif($_POST['fechaCuest1'] != \"\"){\n\t\t\t\t$var_desicion += 8;\n\t\t\t}\n\t\t\tif($_POST['txtBuscar'] != \"\"){\n\t\t\t\t$var_desicion += 16;\n\t\t\t}\n\t\t\t//echo \"<h1>$var_desicion</h1>\";\n\t\t\tswitch($var_desicion){\n\t\t\t\tcase 0:\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaNac1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaNac2']);\n\t\t\t\t\t$this->query .= \"AND u.fechaNac BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaCuest1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaCuest2']);\n\t\t\t\t\t$this->query .= \"AND r.fecha BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaCuest1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaCuest2']);\n\t\t\t\t\t$fecha3 = $this->convertirFecha($_POST['fechaNac1']);\n\t\t\t\t\t$fecha4 = $this->convertirFecha($_POST['fechaNac2']);\n\t\t\t\t\t$this->query .= \"AND u.fechaNac BETWEEN '\".$fecha3.\"' AND '\".$fecha4.\"' \";\n\t\t\t\t\t$this->query .= \"AND r.fecha BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\t\t\t\t\t\t\t\t\n\t\t\t\tcase 16:\n\t\t\t\t\t$var_busqueda = $_POST['txtBuscar'];\n\t\t\t\t\t$this->query .= \"AND (u.nombre LIKE '%$var_busqueda%' or u.institucion LIKE '%$var_busqueda%') \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\t\t$var_busqueda = $_POST['txtBuscar'];\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaNac1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaNac2']);\n\t\t\t\t\t$this->query .= \"AND (u.nombre LIKE '%$var_busqueda%' or u.institucion LIKE '%$var_busqueda%') \";\n\t\t\t\t\t$this->query .= \"AND u.fechaNac BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\t$var_busqueda = $_POST['txtBuscar'];\n\t\t\t\t\t$this->query .= \"AND (u.nombre LIKE '%$var_busqueda%' or u.institucion LIKE '%$var_busqueda%') \";\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaCuest1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaCuest2']);\n\t\t\t\t\t$this->query .= \"AND r.fecha BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\t$var_busqueda = $_POST['txtBuscar'];\n\t\t\t\t\t$this->query .= \"AND (u.nombre LIKE '%$var_busqueda%' or u.institucion LIKE '%$var_busqueda%') \";\n\t\t\t\t\t$fecha1 = $this->convertirFecha($_POST['fechaCuest1']);\n\t\t\t\t\t$fecha2 = $this->convertirFecha($_POST['fechaCuest2']);\n\t\t\t\t\t$fecha3 = $this->convertirFecha($_POST['fechaNac1']);\n\t\t\t\t\t$fecha4 = $this->convertirFecha($_POST['fechaNac2']);\n\t\t\t\t\t$this->query .= \"AND u.fechaNac BETWEEN '\".$fecha3.\"' AND '\".$fecha4.\"' \";\n\t\t\t\t\t$query .= \"AND r.fecha BETWEEN '\".$fecha1.\"' AND '\".$fecha2.\"' \";\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t$banderaError = true;\n\t\t\t\t\techo \"Error, revisa los campos de búsqueda.\";\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t\tif($_POST['sexo'] != 'A'){\n\t\t\t\t$this->query .= \"AND u.sex = '\".$_POST['sexo'].\"' \";\n\t\t\t}\n\t\t\tif($_POST['ocupacion'] != 'A'){\n\t\t\t\t$this->query .= \"AND u.ocupacion = '\".$_POST['ocupacion'].\"' \";\n\t\t\t}\n\t\t\t//echo $query;\n\t\t\tif($banderaError == false){\n\t\t\t\t$conexion = new connection();\n\t\t\t\t$conexion->conectar();\n\t\t\t\t$conexion->myQuery($this->query);\n\n\t\t\t\tif($conexion->getFilas() > 0){\n\t\t\t\t\t$this->matrizResultados = $this->getMatrizResultados($conexion);\n\t\t\t\t\t$this->banderaImprimir = true;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\techo \"<p><strong>No hay resultados para mostrar :(</strong></p>\";\n\t\t\t\t\t$this->banderaImprimir = false;\n\t\t\t\t}\n\t\t\t\t$conexion->desconectar();\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction getMatrizResultados($con){\t\n\t\t\t$contador = 0;\n\t\t\twhile($res = $con->getArrayFila()){\n\t\t\t\t$matriz[$contador][\"nombre\"] = $res['nombre'];\n\t\t\t\t$matriz[$contador][\"fechaNac\"] = $res['fechaNac'];\n\t\t\t\t$matriz[$contador][\"edad\"] = $res['edad'];\n\t\t\t\t$matriz[$contador][\"sexo\"] = $res['sex'];\n\t\t\t\t$matriz[$contador][\"ocupacion\"] = $res['ocupacion'];\n\t\t\t\t$matriz[$contador][\"institucion\"] = $res['institucion'];\n\t\t\t\t$matriz[$contador][\"fechaRe\"] = $res['fecha'];\n\t\t\t\t$matriz[$contador][\"resultado\"] = $res['resultado'];\n\t\t\t\t$contador += 1;\n\t\t\t}\n\t\t\treturn $matriz;\n\t\t}\n\t\n\t\tfunction imprime($matriz){\n\t\t\tforeach($matriz as $array){\n\t\t\t\tprint_r($array);\n\t\t\t\techo \"<br>\";\n\t\t\t}\n\t\t}\n\t\t\t\t\t\n\t\tfunction convertirFecha($fecha){\n\t\t\t$fecha = new DateTime($fecha);\n\t\t\t$fecha = $fecha->format('Y-m-d');\n\t\t\treturn($fecha);\n\t\t}\n\t\n\t\tfunction ordenarTuplas($matriz, $criterio){\n\t\t\tforeach($matriz as $clave => $fila){\n\t\t\t\t$array[$clave] = $fila[$criterio];\n\t\t\t}\n\t\t\tarray_multisort($array, SORT_ASC, $matriz);\n\t\t\treturn $matriz;\n\t\t}\n\t\t\n\t\tfunction getCoincidecias($valor_a_buscar){\n\t\t\t$matriz = $this->matrizResultados;\n\t\t\t$numero = 0;\n\t\t\tif($matriz != NULL){\n\t\t\t\tforeach($matriz as $array){\n\t\t\t\t\tif($valor_a_buscar == $array['ocupacion']){\n\t\t\t\t\t\t$numero = $numero + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn $numero;\n\t\t}\n\t\t\t\t\t\n\t\tfunction llenarTabla($matriz, $numTuplas){\n\t\t\techo \"<p><strong>Haga clic sobre el encabezado de una columna para ordenar los resultados.</strong></p>\";\n\t\t\techo \"<p><strong>Se han encontrado \".$numTuplas.\" coincidencias.</strong></p>\"; \n\t\t\t?>\n\t\t\t<table class=\"responsive-table\">\n\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th><a href=\"?cr=nombre#resultados\">Nombre</a></th>\n\t\t\t\t\t<th><a href=\"?cr=fechaNac#resultados\">Fecha de nacimiento</a></th>\n\t\t\t\t\t<th><a href=\"?cr=edad#resultados\">Edad</a></th>\n\t\t\t\t\t<th><a href=\"?cr=sexo#resultados\">Sexo</a></th>\n\t\t\t\t\t<th><a href=\"?cr=ocupacion#resultados\">Ocupación</a></th>\n\t\t\t\t\t<th><a href=\"?cr=institucion#resultados\">Institución</a></th>\n\t\t\t\t\t<th><a href=\"?cr=fechaRe#resultados\">Fecha de resolución</a></th>\n\t\t\t\t\t<th><a href=\"?cr=resultado#resultados\">Resultado</a></th>\n\t\t\t\t</tr>\n </thead>\n <tbody>\n\t\t\t\t<?php\n\t\t\t\t\tforeach($matriz as $res){\n\t\t\t\t\t\t$fechaNac = date_create($res['fechaNac']);\n\t\t\t\t\t\t$fechaRe = date_create($res['fechaRe']);\n\t\t\t\t\t\techo \"<tr>\";\n\t\t\t\t\t\techo \"<td>\".$res['nombre'].\"</td>\";\n\t\t\t\t\t\techo \"<td>\".date_format($fechaNac,\"d/F/Y\").\"</td>\";\n\t\t\t\t\t\techo \"<td>\".$res['edad'].\"</td>\";\n\t\t\t\t\t\techo \"<td>\".$res['sexo'].\"</td>\";\n\t\t\t\t\t\techo \"<td>\".$res['ocupacion'].\"</td>\";\n\t\t\t\t\t\techo \"<td>\".$res['institucion'].\"</td>\";\n\t\t\t\t\t\techo \"<td>\".date_format($fechaRe,\"d/F/Y\").\"</td>\";\n\t\t\t\t\t\techo \"<td>\".$res['resultado'].\"</td>\";\n\t\t\t\t\t\techo \"</tr>\";\t\n\t\t\t\t\t}\n\t\t\t ?>\n </tbody>\n\t\t\t</table> \t\t\t\t\t\t\n\t<?php \n\t\t}\n\t}\n?>\t" }, { "alpha_fraction": 0.5739948749542236, "alphanum_fraction": 0.5765611529350281, "avg_line_length": 35.5625, "blob_id": "20b942170f28dbe905c238e190500acdb85cd0ac", "content_id": "e261919e9519426bb80e10c1f6e17e80cc503432", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1171, "license_type": "permissive", "max_line_length": 168, "num_lines": 32, "path": "/public_html/app/templates/mostrarInstituciones.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<h2>Instituciones</h2>\n<table border=\"1\">\n\t<tr>\n \t<th>Nombre</th>\n <th>Siglas</th>\n <th></th>\n\t</tr>\n <?php foreach ($parametros['instituciones'] as $ins) :?>\n <tr>\n <td><?php echo $ins['nombre'] ?></td>\n <td><?php echo $ins['siglas']?></td>\n <td><a href=\"index.php?ctl=mostrarEsc&mem=<?php echo $_GET['mem']?>&idIns=<?php echo $ins['idInstitucion']?>\">\n Seleccionar</a></td>\n </tr>\n <?php endforeach; ?>\n\n</table>\n<br>\n<p> *Si no encuentras la institución a la que perteneces puedes registrarla presionando clic <a href=\"index.php?ctl=registroIns&mem=<?php echo $_GET['mem']?>\">aquí</a>.\n<form name=\"formElegirInstitucion\" method=\"post\" action=\"index.php?ctl=mostrarEsc\">\n\t<input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\">\n\t<select name=\"idIns\">\n <?php foreach ($parametros['instituciones'] as $ins) :?>\n \t<option value=\"<?php echo $ins['idInstitucion']?>\"><?php echo $ins['siglas']?> - <?php echo $ins['nombre'] ?></option>\n <?php endforeach; ?>\n\t</select>\n</form>\n\n<?php $contenido .= ob_get_clean() ?>\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.4986286461353302, "alphanum_fraction": 0.520021915435791, "avg_line_length": 18, "blob_id": "d9c0d24c35904dcd05d9883ade0b73fc86bef272", "content_id": "6efa11efad1d27d3df387ac40e4c665aef2d54b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1823, "license_type": "permissive", "max_line_length": 128, "num_lines": 96, "path": "/controlador/registro.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php \n\trequire_once(\"./connection.php\");\n\trequire_once(\"./BeanUsuario.php\");\n\t//Conexion a la BD//\n\t$conexion = new connection();\n\n\t//Obtencion de datos del formulario\n\t$nombre = $_POST['txtNombre'].\" \".$_POST['txtApPat'].\" \".$_POST['txtApMat'];\n\t$fechaN = $_POST['txtFechaNac'];\n\t$ocup = $_POST['txtOcupacion'];\n\t$inst = $_POST['txtInstitucion'];\n\t$genero = $_POST['genero'];\n\t$email = $_POST['txtEmail'];\n\t$email2 = $_POST['txtEmail2'];\n\t$pass = $_POST['txtPwd'];\n\t$pass2 = $_POST['txtPwd2'];\n\t$mes=implode( array ($fechaN));\n\t$separado=explode(\" \",$mes);\n\t\n\t$fechaN=$separado[2].\"-\";\n\tswitch($separado[1]){\n\t\t\tcase \"January,\":\n\t\t\t\t$m=\"01\";\n\t\t\t\tbreak;\n\t\t\tcase \"February,\":\n\t\t\t\t$m=\"02\";\n\t\t\t\tbreak;\n\t\t\tcase \"March,\":\n\t\t\t\t$m=\"03\";\n\t\t\t\tbreak;\n\t\t\tcase \"April,\":\n\t\t\t\t$m=\"04\";\n\t\t\t\tbreak;\n\t\t\tcase \"May,\":\n\t\t\t\t$m=\"05\";\n\t\t\t\tbreak;\n\t\t\tcase \"June,\":\n\t\t\t\t$m=\"06\";\n\t\t\t\tbreak;\n\t\t\tcase \"July,\":\n\t\t\t\t$m=\"07\";\n\t\t\t\tbreak;\n\t\t\tcase \"August,\":\n\t\t\t\t$m=\"08\";\n\t\t\t\tbreak;\n\t\t\tcase \"September,\":\n\t\t\t\t$m=\"09\";\n\t\t\t\tbreak;\n\t\t\tcase \"October,\":\n\t\t\t\t$m=\"10\";\n\t\t\t\tbreak;\n\t\t\tcase \"November,\":\n\t\t\t\t$m=\"11\";\n\t\t\t\tbreak;\n\t\t\tcase \"December,\":\n\t\t\t\t$m=\"12\";\n\t\t\t\tbreak;\n\t}\n\t$fechaN.=$m.\"-\".$separado[0];\n\tif(empty($nombre) || empty($email)){\n\t\techo 4;\n\t}\n\telse if($email==$email2)\n\t{\n\t\t$query=\"select * from usuario where email='\".$email.\"'\";\n\t\t$conexion->conectar();\n\t\t$conexion->myQuery($query);\n\t\tif($conexion->getFilas())//Si me regresa tuplas significa que ya esta registrado\n\t\t{\n\n\t\t\techo 3;\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(empty($pass)){\n\t\t\t\techo 2;\n\t\t\t}\n\t\t\telse if($pass==$pass2)\n\t\t\t{\n\t\t\t\t$pass = md5($pass);\n\t\t\t\t$query=\"call registro('Ellos','\".$nombre.\"','\".$fechaN.\"','\".$genero.\"','\".$ocup.\"','\".$inst.\"','\".$email.\"','\".$pass.\"');\";\n\t\t\t\t$conexion->myQuery($query);\n\t\t\t\n\t\t\t\techo 1;\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t$conexion->desconectar();\n\t\t\t\n\t}\n\telse\n\t\techo 2;\n \n?>" }, { "alpha_fraction": 0.5163493156433105, "alphanum_fraction": 0.5297777056694031, "avg_line_length": 60.30232620239258, "blob_id": "77840cf272df85b0b8da5d266dd59c60609d3e11", "content_id": "dd9438bceaef638b29f71157d0cc25d4dd6a17c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 13247, "license_type": "permissive", "max_line_length": 845, "num_lines": 215, "path": "/public_html/app/templates/inicio.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n \n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#boton\").click(function(e) {\n alert(\"Buscaremos la contraseña en nuestra base de datos, si logramos encontrarla le enviaremos un correo electrónico\")\n $.ajax({\n type: \"post\",\n url: \"app/templates/recover.php\",\n data: $(\"#formEmail\").serialize(),\n success: function(resp) {\n if(resp==1){\n alert(\"Se ha envidado un correo electronico con la contraseña a su cuenta\");\n }\n else{\n alert(resp);\n }\n }\n });\n return false;\n });\n });\n</script>\n\n<div class=\"Columnas\">\n\t<article class=\"columna3\">\n \t<img src=\"web/img/user91(1).png\" class=\"imgIndex\">\n <h2>¿Quienes Somos?</h2>\n <p>Grupo de profesores de física en el país que tiene como interés la promoción de la física en todos los niveles. En el ámbito académico en los diferentes niveles educativos, su interés radica en mejorar el aprendizaje de los alumnos para que tengan herramientas. <a href=\"#QuienesSomos\">Ver más</a></p>\n <!--#####################################################################################--> \n \n \n <div id=\"QuienesSomos\" class=\"modalDialog\">\n \t<div class=\"Columnas\">\n \t<div class=\"noColumna\">\n \t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <h1><span class=\"icon-people\"></span>¿QUIENES SOMOS?</h1> \n <p style=\"font-size:16px\">Grupo de profesores de física en el país que tiene como interés la promoción de la física en todos los niveles. En el ámbito académico en los diferentes niveles educativos, su interés radica en mejorar el aprendizaje de los alumnos para que tengan herramientas con que contribuir de una manera más significativa en el desarrollo del país. También se interesa en la capacitación de profesores y abastecimiento de recursos educativos alternos que lleven a una mejor comprensión por parte de los alum-nos de los temas de física. En el nivel de la sociedad en general, les interesa que las personas aprecien la importancia de la física en el país y que puedan inducir a las nuevas generaciones a tener interés en el estudio de carreras que tengan que ver con la ciencia, en particular con la física.<br>\nLas reuniones anuales buscan reunir a los profesores de Física de todos los niveles educativos para compartir experiencias, metodologías y avances de investigación.</p>\t\n\t\t\t\t\t<img src=\"web/img/aaptmx.png\" alt=\"AAPT-MX\" width=\"35%\" class=\"centrado\">\t\t\t\t\t\t\n </div>\n </div>\n </div>\n \n <!--#####################################################################################--> \n </article>\n <article class=\"columna3\">\n\t\t<img src=\"web/img/clock125.png\" class=\"imgIndex\">\n <h2>Historia</h2>\n <p>La primera reunión de la AAPT-Mx se realizó en el 2008 en el Tecnológico de Monterrey, Campus Monterrey, y se ha continuado de manera anual desde entonces. <a href=\"#Historia\">Ver más</a></p>\n <!--#####################################################################################--> \n \n <div id=\"Historia\" class=\"modalDialog\">\n \t<div class=\"Columnas\">\n \t<div class=\"noColumna\">\n \t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <h1><span class=\"icon-people\"></span>Historia</h1> \t\n\t\t\t\t\t<img src=\"web/img/EnConstruccion.png\" alt=\"AAPT-MX\" width=\"100%\" class=\"centrado\">\t\t\t\t\t\t\n \t\t</div>\n </div>\n </div>\n \n <!--#####################################################################################-->\n\t</article>\n \n <article class=\"columna3\">\n \t<img src=\"web/img/add199.png\" class=\"imgIndex\">\n \t<h2>Registro</h2>\n \t<p>Registrate en AAPT-MX para poder tener acceso a material exclusivo. También podras registrarte a nuestros eventos y conocer la información detallada de estos. <a href=\"#Registro\">Ver más</a></p>\n \t<!--#####################################################################################--> \n \n \t<div id=\"Registro\" class=\"modalDialog\">\n\t\t\t\t <a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <form name=\"formInsertar\" action=\"index.php?ctl=registroSoc\" method=\"POST\" onSubmit=\"return validarDatosSocio()\">\n \t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 1 de 3</h1> \t\n <h2>Datos Personales</h2>\n\t\t\t\t\t\t<select id=\"cboPrefijo\" name=\"cboPrefijo\">\n\t\t\t\t\t\t\t<option value=\"-1\">Seleccione una opción</option>\n <option value=\"Dr.\">Dr.</option>\n <option value=\"M. en C.\">M. en C.</option>\n <option value=\"Ing.\">Ing.</option>\n <option value=\"Lic.\">Lic.</option>\n <option value=\"C.\">C.</option>\n </select>\n <input id=\"txtNombre\" type=\"text\" placeholder=\"&#128054; Nombre completo\" name=\"txtNombre\" style=\"width: 95%\" required>\n <input id=\"txtEmail\" type=\"email\" placeholder=\"&#128231; Email\" name=\"txtEmail\" style=\"width: 95%\" required>\n <input id=\"txtPass\" type=\"password\" placeholder=\"&#128272; Password\" name=\"txtPass\" style=\"width: 95%\" required>\n <input id=\"txtPassConf\" type=\"password\" placeholder=\"&#128272; Confirmar password\" name=\"txtPassConf\" style=\"width: 95%\" required>\n <select id=\"cboEstudiante\" name=\"cboEstudiante\">\n \t<option value=\"-1\">¿Es estudiante o profesor?</option>\n <option value=\"0\">Profesor</option>\n <option value=\"1\">Estudiante</option>\n </select>\n <select id=\"cboNivel\" name=\"cboNivel\">\n \t<option value=\"-1\">¿En qué nivel imparte y/o toma clase?</option>\n <option value=\"posgrado\">Posgrado</option>\n <option value=\"ns\">Nivel Superior</option>\n <option value=\"nms\">Nivel Medio Superior</option>\n <option value=\"basico\">Básico</option> \n </select>\n <select id=\"cboAviso\" name=\"cboAviso\">\n \t<option value=\"-1\">¿Desea recibir nuestro boletín en su correo?</option>\n <option value=\"1\">Sí :D</option>\n <option value=\"0\">No :'(</option>\n </select>\n <input type=\"submit\" value=\"Siguiente\">\n <?php if(isset($parametros['mensaje'])) :?>\n \t\t\t\t\t\t\t<b><span style=\"color: red;\"><?php echo $parametros['mensaje'] ?></span></b>\n\t\t\t\t\t\t<?php endif; ?>\n\t\t\t\t\t</form>\t\t\t\t\t\t\n\t </div>\n \n <div id=\"RegistroP2\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n\t\t\t<form name=\"formElegirInstitucion\" method=\"post\" action=\"index.php?ctl=mostrarEsc#RegistroP3\" onSubmit=\"return validarDatosIns()\">\n\t\t\t\t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 2 de 3</h1>\n\t\t\t\t<h2>Selecciona tu Institución</h2>\n\t\t\t\t<input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\">\n\t\t\t\t<select id=\"idIns\" name=\"idIns\">\n\t\t\t \t<option value=\"-1\">Selecciona una opción...</option>\n\t\t\t\t <?php foreach ($parametros['instituciones'] as $ins) :?>\n\t\t\t\t \t<option value=\"<?php echo $ins['idInstitucion']?>\"><?php echo $ins['siglas']?> - <?php echo $ins['nombre'] ?></option>\n\t\t\t\t <?php endforeach; ?>\n\t\t\t\t</select>\n\t\t\t <input type=\"submit\" value=\"Siguiente\">\n\t\t\t <p> *Si no encuentras la institución a la que perteneces puedes registrarla presionando clic <a href=\"index.php?ctl=registroIns&mem=<?php echo $_GET['mem']?>#RegistroP2Ins\">aquí</a>.</p>\n\t\t\t</form>\n\t\t</div>\n \n <div id=\"RegistroP3\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n\t\t\t<form name=\"formElegirEscuela\" method=\"post\" action=\"index.php?ctl=registroCom\" onSubmit=\"return validarDatosEsc()\">\n\t\t\t\t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 3 de 3</h1>\n\t\t\t <h2>Selecciona tu Escuela</h2>\n\t\t\t <input name=\"mem\" type=\"hidden\" value=\"<?php echo $_POST['mem']; ?>\">\n\t\t\t\t<select id=\"idEsc\" name=\"idEsc\">\n\t\t\t \t<option value=\"-1\">Selecciona una opción...</option>\n\t\t\t\t <?php foreach ($parametros['escuelas'] as $school) :?>\n\t\t\t\t \t<option value=\"<?php echo $school['idEscuela']?>\"><?php echo $school['nombre'] ?> - <?php echo $school['direccion']?></option>\n\t\t\t\t <?php endforeach; ?>\n\t\t\t\t</select>\n\t\t\t <input type=\"submit\" value=\"Siguiente\">\n\t\t\t\t<p> *Si no encuentras la escuela a la que perteneces puedes registrarla presionando clic <a href=\"index.php?ctl=registroEsc&idIns=<?php echo $_POST['idIns']?>&mem=<?php echo $_POST['mem']?>#RegistroP3Esc\">aquí</a>.</p>\n\t\t\t</form>\n\t\t</div>\n \n <div id=\"RegistroP2Ins\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a>\n \t<form action=\"index.php?ctl=registroIns\" method=\"post\">\n \t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 2 de 3</h1>\n\t\t\t \t<h2>Registra tu institución</h2>\n\t\t\t <input type=\"text\" placeholder=\" &#127979; Nombre de la institución (Ej. Instituto Politécnico Nacional)\" name=\"txtInst\" style=\"width: 95%\" required> \n\t\t\t <input type=\"text\" placeholder=\" &#127979; Siglas (Ej. IPN)\" name=\"txtSiglas\" style=\"width: 95%\" required>\n\t\t\t <input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\"> \n\t\t\t <input type=\"submit\" value=\"Siguiente\">\n\t\t\t</form> \n\t\t</div>\n \n <div id=\"RegistroP3Esc\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <form action=\"index.php?ctl=registroEsc\" method=\"post\">\n \t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 3 de 3</h1>\n <h2>Registra tu escuela</h2>\n <input type=\"text\" placeholder=\" &#127979; Nombre de la escuela\" name=\"txtEsc\" style=\"width: 95%\" required> \n <input type=\"text\" placeholder=\" &#128506; Dirección\" name=\"txtDir\" style=\"width: 95%\" required>\n <input name=\"idIns\" type=\"hidden\" value=\"<?php if(isset($_GET['idIns'])) echo $_GET['idIns']; ?>\">\n <input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\">\n <input type=\"submit\" value=\"Siguiente\">\n </form>\n </div>\n \n <div id=\"RegistroCompletado\" class=\"modalDialog\">\n\t\t\t<form>\n \t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <h1><span class=\"icon-people\"></span>Registro Completado</h1> \n <p style=\"font-size:16px\">En breve te enviaremos un correo electrónico con tus datos.</p>\n </form>\n </div>\n \n <div id=\"Login\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <form name=\"formLogin\" action=\"index.php?ctl=login\" method=\"POST\">\n \t<h1><span class=\"icon-mode_edit\"></span>Inicia sesión</h1> \t\n <input id=\"txtEmailLogin\" type=\"email\" placeholder=\"&#128231; Email\" name=\"txtEmailLogin\" style=\"width: 95%\" required>\n <input id=\"txtPassLogin\" type=\"password\" placeholder=\"&#128272; Password\" name=\"txtPassLogin\" style=\"width: 95%\" required>\n <input type=\"submit\" value=\"Iniciar sesión\">\n \t<?php if(isset($parametros['mensaje'])) :?>\n\t \t\t\t<b><span style=\"color: red;\"><?php echo $parametros['mensaje'] ?></span></b>\n\t\t\t\t<?php endif; ?>\n <p>Si no tienes una cuenta, <a href=\"#Registro\">registrate.</a></p>\t\n <p><a href=\"#OlvideContra\">¿Has olvidado tu contraseña?</a></p>\n\t\t\t</form>\t\t\t\t\t\n\t </div>\n \n <div id=\"OlvideContra\" class=\"modalDialog\">\n\t\t\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n <form name=\"formEmail\" id=\"formEmail\" >\n <h1><span class=\"icon-mode_edit\"></span>Recuperar Contraseña </h1> \t\n <input id=\"txtEmailLogin\" type=\"email\" placeholder=\"&#128231; Email\" name=\"email\" style=\"width: 95%\" required>\n <input type=\"submit\" value=\"Enviar\" id=\"boton\">\n \t<?php if(isset($parametros['mensaje'])) :?>\n\t \t\t\t<b><span style=\"color: red;\"><?php echo $parametros['mensaje'] ?></span></b>\n\t\t\t\t<?php endif; ?>\n <p>Si no tienes una cuenta, <a href=\"#Registro\">registrate.</a></p>\t\n </form>\t\t\t\t\t\n\t </div>\n \n \t<!--#####################################################################################-->\n \n </article>\n</div>\n\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>\n\n" }, { "alpha_fraction": 0.5957446694374084, "alphanum_fraction": 0.6186579465866089, "avg_line_length": 33, "blob_id": "87390f17021da030dca28f58e022527a78e4c63d", "content_id": "45eb0ca723d8d268c7b5a6e45ba5646aac2c9e53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 613, "license_type": "permissive", "max_line_length": 89, "num_lines": 18, "path": "/public_html/app/templates/fomRegistroIns.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<?php if(isset($params['mensaje'])) :?>\n\t<b><span style=\"color: red;\"><?php echo $params['mensaje'] ?></span></b>\n<?php endif; ?>\n<br/>\n\n<form action=\"index.php?ctl=registroIns\" method=\"post\">\n \t<h2>Registra tu institución</h2>\n <input type=\"text\" placeholder=\" &#127979; Nombre de la institución\" name=\"txtInst\"> \n <input type=\"text\" placeholder=\" &#127979; Siglas\" name=\"txtSiglas\">\n <input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\"> \n <input type=\"submit\" value=\"Registrar\">\n</form>\n\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.6075471639633179, "alphanum_fraction": 0.6081761121749878, "avg_line_length": 26.912281036376953, "blob_id": "f77e3503581618cdcbb15a9c46adb5b7a146a14e", "content_id": "a31d2d94c0df278341f417d8546a69bea3425b75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1590, "license_type": "permissive", "max_line_length": 118, "num_lines": 57, "path": "/public_html/app/controlador/ControladorEscuela.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ControladorEscuela{\n\t\tpublic function registroEscuela($dir){\n\t\t\t$parametros = array(\n\t\t\t\t\n\t\t\t);\n\t\t\t\n\t\t\t$modelo = new ModeloEscuela();\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST') {\n\t\t\t\t//Creacion del bean Escuela\n\t\t\t\t$escuela = new Escuela(0, htmlspecialchars($_POST['txtEsc']),htmlspecialchars($_POST['txtDir']), $_POST['idIns']);\n\t\t\t\t\n\t\t\t\t//Validar datos\n\t\t\t\tif($modelo->validarDatos($escuela)){\n\t\t\t\t\t$modelo->insertar($escuela);\n\t\t\t\t\t$escuela->setIdEscuela($modelo->buscarPorNombre($escuela->getNombre(), $escuela->getDireccion()));\n\t\t\t\t\t\n\t\t\t\t\t$url = 'index.php?ctl=registroCom&mem='.$_POST['mem'].'&idEsc='.$escuela->getIdEscuela();\n\t\t\t\t\techo '<script type=\"text/javascript\">window.location=\"'.$url.'\";</script>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t//require $dir.'/app/templates/fomRegistroEscuela.php';\n\t\t\trequire $dir.'/app/templates/inicio.php';\n\t\t}\n\t\t\n\t\tpublic function mostrarEscuela($dir){\n\t\t\t$modelo = new ModeloEscuela();\n\t\t\t$busqueda = '';\n\t\t\t\n\t\t\tif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['txtBuscar'])) {\n\t\t\t\t//Se recupera el parametro de la busqueda\n\t\t\t\t$busqueda = $_POST['txtBuscar'];\n\t\t\t}\n\t\t\tif(isset($_POST['idIns'])){\n\t\t\t\t$busquedaIdIns = $_POST['idIns'];\n\t\t\t\t\n\t\t\t\t$parametros = array(\n\t\t\t\t\t'escuelas' => $modelo->buscarPorInstitucion($busquedaIdIns)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\telse{\n\t\t\t\t$parametros = array(\n\t\t\t\t\t'escuelas' => $modelo->getEscuelas($busqueda)\n\t\t\t\t);\n\t\t\t}\n\t\t\t\n\t\t\t//require $dir.'/app/templates/formBuscarEscuela.php';\n\t\t\t//require $dir.'/app/templates/mostrarEscuelas.php';\n\t\t\trequire $dir.'/app/templates/inicio.php';\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.7983871102333069, "avg_line_length": 40.33333206176758, "blob_id": "2a5a617b4409513564a677774ff4c43055c24314", "content_id": "025bfc721e87a0f56d6a77edf38a13079333cf11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 248, "license_type": "permissive", "max_line_length": 113, "num_lines": 6, "path": "/.user.ini", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "[PHP]\nmemory_limit=64M\nopen_basedir=\"D:/Inetpub/vhosts/tlamatiliztli.net\\;C:\\Windows\\Temp\\\"\npost_max_size=16M\nupload_max_filesize=16M\nerror_log=\"D:\\Inetpub\\vhosts\\tlamatiliztli.net\\logs\\php_errors\\physics-education.tlamatiliztli.net\\php_error.log\"\n" }, { "alpha_fraction": 0.6277928948402405, "alphanum_fraction": 0.6621253490447998, "avg_line_length": 41.67441940307617, "blob_id": "2a0261b1a59a6e90349c2ce21185dc98e982865a", "content_id": "7589a25423c5fc376251e7c9bf31f0be5f052c0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1851, "license_type": "permissive", "max_line_length": 166, "num_lines": 43, "path": "/public_html/app/templates/boletin.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n<?php \n\t$sesion = new Sesion();\n\t$usuario = $sesion->getSesion('login');\n\n if($usuario!=false){\n?>\n<div class=\"Columnas\">\n\t<!-- Aqui va el contenido del contenedor blanco-->\n\t<article class=\"columna2\">\n\t\t<h1>Boletín Volumen 2 / Número 1</h1>\n\t\t<p>Recuerda que para poder descargar el boletín deberás estar registrado en el sistema.</p>\n\t\t<p class=\"centrado\"><a href=\"web/descargas/Boletin201604.pdf\" target=\"_blank\"><img src=\"web/img/word-document1.png\" width=\"96\" height=\"96\" />Descargar</a></p>\n\t\t<p>&nbsp;</p>\n\t</article>\n <article class=\"columna2\">\n \t<h1>Boletín Volumen 2 / Número 2</h1>\n <p>Recuerda que para poder descargar el boletín deberás estar registrado en el sistema.</p>\n <p class=\"centrado\"><a href=\"web/descargas/Boletin201608.pdf\" target=\"_blank\"><img src=\"web/img/word-document1.png\" width=\"96\" height=\"96\" />Descargar</a></p>\n <p>&nbsp;</p>\n </article>\n <article class=\"columna2\">\n\t\t<h1>Boletín Volumen 3 / Número 1</h1>\n\t\t<p>Recuerda que para poder descargar el boletín deberás estar registrado en el sistema.</p>\n\t\t<p class=\"centrado\"><a href=\"web/descargas/Boletin20172.pdf\" target=\"_blank\"><img src=\"web/img/word-document1.png\" width=\"96\" height=\"96\" />Descargar</a></p>\n\t\t<p>&nbsp;</p>\n\t</article>\n <article class=\"columna2\">\n\t\t<h1>Boletín Volumen 3 / Número 2</h1>\n\t\t<p>Recuerda que para poder descargar el boletín deberás estar registrado en el sistema.</p>\n\t\t<p class=\"centrado\"><a href=\"web/descargas/BoletinAAPTMx201705.pdf\" target=\"_blank\"><img src=\"web/img/word-document1.png\" width=\"96\" height=\"96\" />Descargar</a></p>\n\t\t<p>&nbsp;</p>\n\t</article>\n</div><!--Columnas-->\n<?php\n\t}\n\telse{\n\t\t echo \"<script language=Javascript> location.href=\\\"index.php\\\"; </script>\"; \n\t}\n?>\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>\n" }, { "alpha_fraction": 0.6377464532852173, "alphanum_fraction": 0.6377464532852173, "avg_line_length": 22.0649356842041, "blob_id": "201ace2b2d970a9a4e084d61208bc116a34cac78", "content_id": "9ba8714a4145d02b4acf84f2d10099398ee982e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1775, "license_type": "permissive", "max_line_length": 217, "num_lines": 77, "path": "/public_html/app/bean/ComiteAAPT.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php \n\t\n\tclass ComiteAAPT extends Socio\n\t{\n\t\t\t//Atributos\n\t\t\tprivate $idComite;\n\t\t\tprivate $cargo;\n\t\t\tprivate $fechaInicio;\n\t\t\tprivate $fechaFin;\n\t\t\tprivate $urlFoto;\n\t\t\tprivate $semblanza;\n\t\t\t\n\t\t\t//Constructor\n\t\t\tpublic function __construct($noMembresia, $nombreCompleto, $prefijo, $email, $estudProf, $niClase, $avisoBoletin, $password, $idTrabajo, $idEscuela ,$idComite, $cargo, $fechaInicio, $fechaFin, $urlFoto, $semblanza)\n\t\t\t{\n\t\t\t\tparent::__construct($noMembresia, $nombreCompleto, $prefijo, $email, $estudProf, $niClase, $avisoBoletin, $password, $idTrabajo, $idEscuela);\n\t\t\t\t$this->idComite = $idComite;\n\t\t\t\t$this->cargo = $cargo;\n\t\t\t\t$this->fechaInicio = $fechaInicio;\n\t\t\t\t$this->fechaFin = $fechaFin;\n\t\t\t\t$this->urlFoto = $urlFoto;\n\t\t\t\t$this->semblanza = $semblanza;\n\t\t\t}\t\t\n\t\t\t\n\t\t\t//Metodos getters\n\t\t\tpublic function getIdComite(){\n\t\t\t\treturn $this->idComite;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function getCargo(){\n\t\t\t\treturn $this->cargo;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function getFechaInicio(){\n\t\t\t\treturn $this->fechaInicio;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function getFechaFin(){\n\t\t\t\treturn $this->fechaFin;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function getUrlFoto(){\n\t\t\t\treturn $this->urlFoto;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function getSemblanza(){\n\t\t\t\treturn $this->semblanza;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t//Metodos setters\n\t\t\tpublic function setIdComite($idComite){\n\t\t\t\t$this->idComite = $idComite;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function setCargo($cargo){\n\t\t\t\t$this->cargo = $cargo;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function setFechaInicio($fechaInicio){\n\t\t\t\t$this->fechaInicio = $fechaInicio;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function setFechaFin($fechaFin){\n\t\t\t\t$this->fechaFin = $fechaFin;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function setUrlFoto($urlFoto){\n\t\t\t\t$this->urlFoto = $urlFoto;\n\t\t\t}\n\t\t\t\n\t\t\tpublic function setSemblanza($semblanza){\n\t\t\t\t$this->semblanza = $semblanza;\n\t\t\t}\n\t}\n\t\n?>" }, { "alpha_fraction": 0.5782890319824219, "alphanum_fraction": 0.586776852607727, "avg_line_length": 36, "blob_id": "93e10b39f91154c250cf941aa2590f0471fb3a4c", "content_id": "cba99957926d69fc1fc3548e803b8ee2ee9f1b71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8964, "license_type": "permissive", "max_line_length": 220, "num_lines": 242, "path": "/modificar.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html lang=\"es\">\n<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n<head>\n\t<?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n\n ?>\n\t\t<meta charset=\"utf-8\">\n\n\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t\t<!-- links-->\n\n\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t\t<title>Grupo de investigación en la enseñanza de física</title>\n</head>\n<script>\n\t$(document).ready(function() {\n\t\t$('.modal').modal();\n\n\n\t\t$(\".button-collapse\").sideNav();\n\t\t// Initialize collapse button\n\t\t$(\".button-collapse\").sideNav();\n\t\t// Initialize collapsible (uncomment the line below if you use the dropdown variation)\n\t\t//$('.collapsible').collapsible();\n\t\t//para la fecha de nacimiento\n\t\t$('.datepicker').pickadate({\n\t\t\tselectMonths: true, // Creates a dropdown to control month\n\t\t\tselectYears: 15 // Creates a dropdown of 15 years to control year\n\t\t});\n\t\t\n\t\t//opcion \n\n\t\t$('select').material_select();\n\t\t$(\"#btn-modificar\").click(function(e) {\n\t\t\t//alert($(\"#modificar\").serialize());\n\n\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/Modificar.php\",\n\t\t\t\tdata: $(\"#modificar\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\t\t\t\t\tif (resp == 1) {\n\t\t\t\t\t\t$('#modal1').modal('open');\n\t\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$('#modal2').modal('open');\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn false;\n\n\t\t});\n\t});\n\n</script>\n\n<body>\n\t<?php\n include(\"barra.html\");\n ?>\n\t\t<!-- InstanceBeginEditable name=\"encabezados\" -->\n\t\t<div id='banner'>\n\t\t\t<div class=\"row\">\n\t\t\t\t<header>\n\t\t\t\t\t<div class=\"col s12 m8 l6\">\n\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t<h2 style=\"padding:20%;\">Registro de usuario</h2>\n\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"col s12 m8 l6\">\n\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t</div>\n\t\t\t\t</header>\n\t\t\t</div>\n\t\t</div>\n\n\n\t\t<!-- InstanceEndEditable -->\n\t\t<?php \n include(\"minibarra.php\");\n ?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"content\" -->\n\t\t\t<div class=\"contenido\">\n\t\t\t\t<article>\n\t\t\t\t\t<h3>Modifica tus datos</h3>\n\t\t\t\t\t<p>Cambia los datos que desees. Si quieres cambiar de correo, marca la casilla y coloca el nuevo correo. Recuerda que éste es el identificador para entrar a tu cuenta.</p>\n\t\t\t\t\t<p>Por motivos de seguridad, la contraseña no se incluye dentro del siguiente formulario.</p>\n\t\t\t\t\t<?php\n require_once('controlador/BeanUsuario.php');\n //require_once('../controlador/connection.php');\n //session_start();\n $usuario = $_SESSION[\"login\"];\n $usuario = unserialize($usuario);\n $nombre= $usuario->getNombre();\n $arrayNombre=explode(\" \",$nombre,3);\n ?>\n\n\t\t\t\t\t\t<div id=\"formRegistro\">\n\t\t\t\t\t\t\t<form name=\"formUsuario\" class=\"pure-form pure-form-stacked\" id=\"modificar\">\n\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t\t\t<input input type=\"text\" name=\"txtNombre\" id=\"txtNombre\" oninput=\"cnombre()\" value=\"<?php echo $arrayNombre[0];?>\" required/>\n\t\t\t\t\t\t\t\t\t\t\t<label>Nombre(s)</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t\t\t<input id=\"icon_telephone\" class=\"validate\" type=\"text\" name=\"txtApPat\" id=\"txtApPat\" oninput=\"capPaterno()\" placeholder=\"Ap. Paterno\" value=\"<?php echo $arrayNombre[1];?>\" required/>\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"icon_telephone\">Apellido paterno</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">account_circle</i>\n\t\t\t\t\t\t\t\t\t\t\t<input id=\"icon_prefix\" type=\"text\" class=\"validate\" name=\"txtApMat\" id=\"txtApMat\" oninput=\"capMaterno()\" placeholder=\"Ap. Materno\" value=\"<?php echo $arrayNombre[2];?>\" required>\n\t\t\t\t\t\t\t\t\t\t\t<label>Apellido materno:</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s6\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">today</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"date\" class=\"datepicker\" name=\"txtFechaNac\" id=\"txtFechaNac\" maxlength=\"10\" oninput=\"cfecha()\" required placeholder=\"dd-mm-yyyy\" value=\"<?php echo $usuario->getFechaNac(); ?>\">\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s6\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">perm_identity</i>\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"genero\" id=\"labelGenero\">Genero:</label>\n\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\t\t\t<input type=\"radio\" name=\"genero\" value=\"M\" id=\"genero_0\" class=\"tRadio\" <?php if($usuario->getSex() == 'M') echo \"checked\"; ?>/>\n\t\t\t\t\t\t\t\t\t\t\t\t<label for=\"genero_0\">Masculino</label>\n\t\t\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\t\t\t\t<input type=\"radio\" name=\"genero\" value=\"F\" id=\"genero_1\" class=\"tRadio\" <?php if($usuario->getSex() == 'F') echo \"checked\"; ?> />\n\t\t\t\t\t\t\t\t\t\t\t\t<label for=\"genero_1\">Femenino</label>\n\t\t\t\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12 l6 \">\n\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"txtOcupacion\" id=\"labelOcup\" class=\"pure-checkbox\">Ocupación:</label>\n\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">toc</i>\n\t\t\t\t\t\t\t\t\t\t\t<select name=\"txtOcupacion\" id=\"txtOcupacion\" style=\"display:none;\" required>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"\" disabled selected>Elija una opción ...</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"Estudiante\" <?php if($usuario->getOcupacion() == \"Estudiante\") echo \"selected\"; ?> >Estudiante</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"Egresado\" <?php if($usuario->getOcupacion() == \"Egresado\") echo \"selected\"; ?>>Egresado</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"Profesor\" <?php if($usuario->getOcupacion() == \"Profesor\") echo \"selected\"; ?>>Profesor</option>\n\t\t\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">label_outline</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"text\" class=\"materialize-textarea\" name=\"txtInstitucion\" id=\"txtInstitucion\" oninput=\"cinstitucion()\" placeholder=\"Escuela-Institución\" value=\"<?php echo $usuario->getInstitucion(); ?>\" required/>\n\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">email</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"email\" name=\"txtEmail\" id=\"txtEmail\" oninput=\"cemail()\" placeholder=\"Email\" value=<?php echo \"'\".$usuario->getEmail().\"'\"; ?> required/>\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"txtEmail\">Email</label>\n\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s12\">\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons prefix\">email</i>\n\t\t\t\t\t\t\t\t\t\t\t<input type=\"email\" name=\"txtEmail2\" id=\"txtEmail2\" oninput=\"cemail()\" placeholder=\"Confirmar email\" value=<?php echo \"'\".$usuario->getEmail().\"'\"; ?> required/>\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"txtEmail2\">Confirmar Email:</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\n\n\n\n\n\t\t\t\t\t\t\t\t\t\t<div class=\"input-field col s6\" style=\"padding-left:45%;\">\n\t\t\t\t\t\t\t\t\t\t\t<button type=\"submit\" value=\"Registrar\" class=\"btn waves-effect waves-light\" style=\"color:white;\" id=\"btn-modificar\">Modificar\n\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons right\">send</i>\n\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\n\n\n\t\t\t\t\t\t\t\t\t</div>\n\n\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t</div>\n\n\t\t\t\t</article>\n\t\t\t</div>\n\n\t\t\t<!-- InstanceEndEditable -->\n\t\t\t<footer>\n\t\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t\t<br>\n\t\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t\t<br>\n\t\t\t</footer>\n\t\t\t<div id=\"modal1\" class=\"modal\">\n\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t<h4>Tus datos han sido actualizados con &eacute;xito!!</h4>\n\t\t\t\t\t<p>Se cerrar&aacute; sesi&oacute;n para que pueda comprobar los nuevos datos</p>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t<a href=\"controlador/logout.php\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t<div id=\"modal2\" class=\"modal\">\n\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t<h4>No hemos podido actualizar</h4>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"modal-footer\">\n\t\t\t\t\t<a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn-flat\">Aceptar</a>\n\t\t\t\t</div>\n\t\t\t</div>\n</body>\n\n<!-- InstanceEnd -->\n\n</html>\n" }, { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 26.22222137451172, "blob_id": "d5ed2c321f31b6316090c908277d1a7749744cce", "content_id": "7d1114888e792811006d6644bac63a237d85c133", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 490, "license_type": "permissive", "max_line_length": 158, "num_lines": 18, "path": "/ObtieneProfesores.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n//recibo datos\n\n$seleccion=$_POST['seleccion'];\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n$query=\"SELECT ID,UPPER(ApPaterno) as ApPaterno, UPPER(ApMaterno) as ApMaterno, UPPER(Nombre) as Nombre FROM `usuario` WHERE TipoUsuario NOT LIKE('Default')\";\n$sth = mysqli_query($conexion,$query);\n\n$rows = array();\nwhile($r = $sth->fetch_assoc()) {\n\t$rows[] = $r;\n\t//echo $r;\n}\n\necho json_encode($rows);\n\nmysqli_close($conexion);\n?>\n" }, { "alpha_fraction": 0.5973154306411743, "alphanum_fraction": 0.6107382774353027, "avg_line_length": 21.11111068725586, "blob_id": "68d0d70649e09065e900d638e3e82d9a4781fb64", "content_id": "163543011d7e83f68cec71b9d4003d8133404715", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 596, "license_type": "permissive", "max_line_length": 82, "num_lines": 27, "path": "/controlador/modcontra.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire_once(\"./connection.php\");\n\trequire_once(\"./BeanUsuario.php\");\n\t//Conexion a la BD//\n\t$conexion = new connection();\n\tsession_start();\n\t$usuario = $_SESSION[\"login\"];\n $usuario = unserialize($usuario);\n\t$idUsuario=$usuario->getId();\n\t$pass = $_POST['txtPwd'];\n\t$pass2 = $_POST['txtPwd2'];\n\t\n\tif(empty($pass) || empty($pass2)){\n\t\techo 2;\n\t}\n\telse if($pass==$pass2){\n\t\t$p=md5($pass);\n\t\t$query = \"update usuario set password=\\\"\".$p.\"\\\" where idUsuario = \".$idUsuario;\n\t\t$conexion->conectar();\n\t\t$conexion->myQuery($query);\n\t\t$conexion->desconectar();\n\t\techo 1;\n\t}\n\telse\n\t\techo 3;\n\n?>" }, { "alpha_fraction": 0.5720702409744263, "alphanum_fraction": 0.5860555171966553, "avg_line_length": 25.91483497619629, "blob_id": "e70678f9f91c91749f2a49cb5ec3d095e64e2388", "content_id": "621732d401c2d22f04549e493d06ed2b69c0165e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 9801, "license_type": "permissive", "max_line_length": 168, "num_lines": 364, "path": "/datos2.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\nsession_start();\nif($_SESSION[\"acceso\"][5]==1 || $_SESSION[\"acceso\"][5]==2 || $_SESSION[\"acceso\"][5]==3 || $_SESSION[\"acceso\"][5]==4){\necho $_SESSION[\"acceso\"][8];\n$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n$sql=\"select distinct idpregunta from respuestaprofesor where idpregunta=\".$_SESSION[\"acceso\"][8].\";\";\n$result=mysqli_query($conexion,$sql);\n\n//obtengo el numero de profesores que contestaron la encuesta\n\n$sql2=\"select distinct id from respuestaprofesor;\";\n$result2=mysqli_query($conexion,$sql2);\n//genero n resulsets\n\n//parte pregunta\n\n$sqlp=\"select pregunta,pathImg from pregunta where idPregunta=\".$_SESSION[\"acceso\"][8].\";\";\n$paises=mysqli_query($conexion,$sqlp);\n$sql=\"select * from opciones where idPregunta=\".$_SESSION[\"acceso\"][8].\";\";\n$respuestas=mysqli_query($conexion,$sql);\n//fin parte pregunta\n\n$profes=0;\necho $profes;\n?>\n\n\n<span style=\"font-style:italic;\"><!doctype html>\n\t<html lang=\"es\">\n\t\t<style>\n\t\t\tcanvas {\n\t\t\t\t-moz-user-select: none;\n\t\t\t\t-webkit-user-select: none;\n\t\t\t\t-ms-user-select: none;\n\t\t\t}\n\t\t</style>\n\t\t<!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n\t\t<head>\n\t\t\t<?php require_once(\"controlador/verificar.php\");\n\t\t\trequire_once(\"controlador/connection.php\");\n\t\t\t?>\n\t\t\t<meta charset=\"utf-8\">\n\n\n\t\t\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n\t\t\t<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\t\t\t<script src=\"js/utils.js\"></script>\n\t\t\t<script src=\"js/Chart.bundle.js\"></script>\n\n\t\t\t<script\n\t\t\t\t\tsrc=\"https://code.jquery.com/jquery-3.2.1.min.js\"\n\t\t\t\t\tintegrity=\"sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=\"\n\t\t\t\t\tcrossorigin=\"anonymous\"></script>\n\t\t\t<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n\t\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\t\t\t<!-- links-->\n\t\t\t<link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n\t\t\t<script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n\t\t\t<title>Grupo de investigación en la enseñanza de física</title>\n\t\t</head>\n\t\t<script>\n\t\t\t$(document).ready(function() {\n\n\n\t\t\t\t$('.modal').modal();\n\t\t\t\t$(\".button-collapse\").sideNav();\n\t\t\t\t// Initialize collapsible (uncomment the line below if you use the dropdown variation)\n\t\t\t\t$('.collapsible').collapsible();\n\t\t\t\t$('select').material_select();\n\t\t\t});\n\n\n\t\t</script>\n\n\t\t<body>\n\n\t\t\t<?php\n\t\t\tinclude (\"barra.html\");\n\t\t\t?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"encabezados\" -->\n\t\t\t<div id='banner'>\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<header>\n\t\t\t\t\t\t<div class=\"col s12 m5 l6\">\n\t\t\t\t\t\t\t<!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n\t\t\t\t\t\t\t<h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n\t\t\t\t\t\t\t<!--------------------------------------------------------------->\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"col s12 m6 l6\">\n\t\t\t\t\t\t\t<img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</header>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\n\n\n\t\t\t<?php \n\t\t\tinclude(\"minibarra.php\");\n\t\t\t?>\n\n\n\t\t\t<!-- InstanceBeginEditable name=\"content\" -->\n\t\t\t<div class=\"contenido\">\n\t\t\t\t<!--nuevo-->\n\t\t\t<div class=\"container\">\n\t\t\t\t<h2 style=\"color: black;\">Pregunta <?php echo $_SESSION[\"acceso\"][8];?> </h2>\n\t\t\t\t\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t while($pais=mysqli_fetch_array($paises,MYSQLI_BOTH)){\n\t\t\t\t\t\t\t\t\t echo $pais[0];\n\n\n\t\t\t\t\t\t\t?>\n\t\t\t\t\t\t</li>\n\t\t\t\t\t</ul> \n\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t\t echo \"<div class='row'><div class='col s6 offset-s4'><img src='$pais[1]' class='materialboxed'></div></div>\";\t\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t?>\n\n\n\n\t\t\t\t\t<form action=\"#\" id=\"respuesta\" name=respuesta>\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\t\t while($miau=mysqli_fetch_array($respuestas,MYSQLI_BOTH)){\n\t\t\t\t\t\t\t\t\t echo \"<p><input name='group1' type='radio' id='\".$miau[0].\"' value='\".$miau[0].\"' disabled='disabled'><label for='\".$miau[0].\"'></label>\".$miau[1].\"</p>\";\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t?>\n\t\t\t</form>\n\t\t\t\n\t\t\t<!--fin nuevo-->\n\t\t\t\t<br>\n\t\t\t\t<br>\n\t\t\t\t<h3 style=\"color: black;\">Escala de dificultad para la pregunta <?php echo $_SESSION[\"acceso\"][8];?> </h3>\n\t\t\t\t<p>(En porcentaje)</p>\n\t\t\t\t<div id=\"container\" style=\"width: 75%;\">\n\t\t\t\t\t<canvas id=\"canvas\" ></canvas>\n\t\t\t\t</div>\n\n\t\t\t\t<table class=\"highlight\">\n\t\t\t\t\t<thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Profesor</th>\n\t\t\t\t\t\t\t<th>Opini&oacute;n</th>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</thead>\n\t\t\t\t\t<?php\n\t\t\t\t\t\t$consulta=\"select a.ApPaterno, a.ApMaterno, a.nombre, b.Opinion FROM usuario a, respuestaprofesor b where a.ID=b.ID and b.IDPregunta=\".$_SESSION[\"acceso\"][8].\";\";\n\t\t\t\t\t\t$html=\"<tbody>\";\n\t\t\t\t\t\techo $html;\n\t\t\t\t\t\t$jack=mysqli_query($conexion,$consulta);\n\t\t\t\t\t\twhile($REP=mysqli_fetch_array($jack)){\n\t\t\t\t\t\t\t//$html+=\"<tr><td>\".$REP[0] .\" \".$REP[1].\" \".$REP[2].\"</td><td>\".$REP[3].\"<td></tr>\";\n\t\t\t\t\t\t\techo \"<tr><td>\".$REP[0] .\" \".$REP[1].\" \".$REP[2].\"</td><td>\".$REP[3].\"<td></tr>\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$html=\"</tbody>\";\n\t\t\t\t\t\techo $html;\n\t\t\t\t\t?>\n\t\t\t\t\t\n\t\t\t\t</table>\n\n\t\t\t\t<br>\n\t\t\t<div class=\"row\">\n\t\t\t\t<a class=\"waves-effect waves-light btn-large offset-s5 col s2\" id=\"btnback\">Volver</a>\n\t\t\t</div>\n\t\t\t<br>\n\t\t\t<br>\n\t\t\t</div>\n\t\t\t<footer>\n\t\t\t\t<!--Aqui va el pie de pagina-->\n\t\t\t\t<br>\n\t\t\t\t<p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n\t\t\t\t<br>\n\t\t\t</footer>\n\t\t\t</div>\n\t\t\t\n\t\t</body>\n\t\t<script>\n\t\t\t\n\t\t\t$(\"#btnback\").click(function(e) {\n\t\t\t\t//alert($(\"#desp2\").serialize());\n\n\t\t\t\t$.ajax({\n\t\t\t\ttype: \"post\",\n\t\t\t\turl: \"controlador/asignaCuadro.php\",\n\t\t\t\tdata: $(\"#desp2\").serialize(),\n\t\t\t\tsuccess: function(resp) {\n\t\t\t\t\t//alert(resp);\n\t\t\t\t\twindow.location.replace(\"administracionEncuesta.php\");\n\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn false;\n\n\t\t\t});\n\t\t</script>\n\t\t<script>\n\t\t\tvar ctx = document.getElementById(\"canvas\");\n\t\t\tvar MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\t\t\tvar color = Chart.helpers.color;\n\t\t\t/*var barChart = new Chart(ctx, {\n\t\t\t\ttype: 'bar',\n\t\t\t\tdata: {\n\t\t\t\t\tlabels: [\"Dog\", \"Cat\", \"Pangolin\"],\n\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\tbackgroundColor: '#00ff00',\n\t\t\t\t\t\tlabel: '# of Votes 2016',\n\t\t\t\t\t\tdata: [12, 19, 3]\n\t\t\t\t\t}]\n\t\t\t\t}\n\t\t\t});*/\n\t\t\tvar barChartData = new Chart(ctx, {\n\t\t\t\ttype:'bar',\n\t\t\t\tdata:{\n\t\t\t\t\tlabels: [\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\twhile($registros=mysqli_fetch_array($result)){\n\t\t\t\t\t\t?>\n\n\t\t\t\t\t\t'<?php echo $registros[0]; ?>',\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t],\n\t\t\t\t\tdatasets: [{\n\t\t\t\t\t\tlabel: 'Dataset 1',\n\t\t\t\t\t\tbackgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),\n\t\t\t\t\t\tborderColor: window.chartColors.red,\n\t\t\t\t\t\tborderWidth: 1,\n\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t0,0\n\t\t\t\t\t\t]\n\t\t\t\t\t}]\n\n\t\t\t\t}});\n\n\t\t\t//un data set por cada profesor, cada dataset tiene las respuestas por pregunta\n\t\t\t<?php\n\t\t\twhile($registros2=mysqli_fetch_array($result2)){\n\t\t\t\t//ahora obtengo las respuestas\n\t\t\t\t$sql3=\"select rango from respuestaprofesor where id=\".$registros2[\"id\"].\" and idpregunta=\".$_SESSION[\"acceso\"][8].\" order by idpregunta;\";\n\t\t\t\t//echo $sql3;\n\t\t\t\t$result3=mysqli_query($conexion,$sql3);\n\t\t\t\t$sql4=\"select ApPaterno, ApMaterno, Nombre from usuario where id=\".$registros2[\"id\"].\";\";\n\t\t\t\t$result4=mysqli_query($conexion,$sql4);\n\t\t\t\twhile($registros4=mysqli_fetch_array($result4)){\n\t\t\t\t\t$nombre=$registros4[\"ApPaterno\"].\" \".$registros4[\"ApMaterno\"].\" \".$registros4[\"Nombre\"];\n\t\t\t\t}\n\t\t\t?>\n\n\t\t\taddData(barChartData,'<?php echo $nombre; ?>', '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6), [\n\t\t\t\t<?php\n\t\t\t\twhile($registro3=mysqli_fetch_array($result3)){\n\t\t\t\t?>\n\t\t\t\t<?php echo $registro3[\"rango\"]?>,\n\t\t\t\t<?php\n\t\t\t\t}\n\t\t\t\t?>\n\t\t\t]);\n\n\n\t\t\t<?php\n\t\t\t}\n\t\t\t?>\n\n\n\n\n\t\t\twindow.onload = function() {\n\t\t\t\tvar ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n\t\t\t\twindow.myBar = new Chart(ctx, {\n\t\t\t\t\ttype: 'bar',\n\t\t\t\t\tdata: barChartData,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tresponsive: true,\n\t\t\t\t\t\tlegend: {\n\t\t\t\t\t\t\tposition: 'top',\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttitle: {\n\t\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\t\ttext: 'Chart.js Bar Chart'\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t};\n\n\t\t\tdocument.getElementById('randomizeData').addEventListener('click', function() {\n\t\t\t\tvar zero = Math.random() < 0.2 ? true : false;\n\t\t\t\tbarChartData.datasets.forEach(function(dataset) {\n\t\t\t\t\tdataset.data = dataset.data.map(function() {\n\t\t\t\t\t\treturn zero ? 0.0 : randomScalingFactor();\n\t\t\t\t\t});\n\n\t\t\t\t});\n\t\t\t\twindow.myBar.update();\n\t\t\t});\n\n\t\t\tvar colorNames = Object.keys(window.chartColors);\n\n\n\t\t\tdocument.getElementById('addData').addEventListener('click', function() {\n\t\t\t\tif (barChartData.datasets.length > 0) {\n\t\t\t\t\tvar month = MONTHS[barChartData.labels.length % MONTHS.length];\n\t\t\t\t\tbarChartData.labels.push(month);\n\n\t\t\t\t\tfor (var index = 0; index < barChartData.datasets.length; ++index) {\n\t\t\t\t\t\t//window.myBar.addData(randomScalingFactor(), index);\n\t\t\t\t\t\tbarChartData.datasets[index].data.push(randomScalingFactor());\n\t\t\t\t\t}\n\n\t\t\t\t\twindow.myBar.update();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tdocument.getElementById('removeDataset').addEventListener('click', function() {\n\t\t\t\tbarChartData.datasets.splice(0, 1);\n\t\t\t\twindow.myBar.update();\n\t\t\t});\n\n\t\t\tdocument.getElementById('removeData').addEventListener('click', function() {\n\t\t\t\tbarChartData.labels.splice(-1, 1); // remove the label first\n\n\t\t\t\tbarChartData.datasets.forEach(function(dataset, datasetIndex) {\n\t\t\t\t\tdataset.data.pop();\n\t\t\t\t});\n\n\t\t\t\twindow.myBar.update();\n\t\t\t});\n\n\t\t\tfunction addData(chart, label, color, data) {\n\t\t\t\tchart.data.datasets.push({\n\t\t\t\t\tlabel: label,\n\t\t\t\t\tbackgroundColor: color,\n\t\t\t\t\tdata: data\n\t\t\t\t});\n\t\t\t\tchart.update();\n\t\t\t}\n\t\t</script>\n\t\t<!-- InstanceEnd -->\n\n\t</html>\n\t<?php\n\t }\n else{\n echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n }\n\t?>\n</span>" }, { "alpha_fraction": 0.5140923261642456, "alphanum_fraction": 0.5235692262649536, "avg_line_length": 37.85646057128906, "blob_id": "27718a1b1df2ae91c4dd03806a514d6a41ac04df", "content_id": "659de58432c2b17e1bfe61a283df32d6f5201730", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8164, "license_type": "permissive", "max_line_length": 777, "num_lines": 209, "path": "/controlador/EncuestaPiloto.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n session_start();\n\t$Area=$_SESSION[\"acceso\"][5];\n\t//echo $Area;\n\tif($Area==1 || $Area==2 || $Area==3)\n\t{\n\n?>\n<!doctype html>\n<html lang=\"es\">\n <!-- InstanceBegin template=\"/Templates/plantillaLogueado.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\n\n <head>\n <?php require_once(\"controlador/verificar.php\");\n require_once(\"controlador/connection.php\");\n ?>\n <meta charset=\"utf-8\">\n\n\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n\n <script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n <!-- links-->\n <link rel=\"shortcut icon\" href=\"images/atom.ico\" />\n <script type=\"text/javascript\" src=\"js/validaciones.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/estilo.css\">\n\n <title>Grupo de investigación en la enseñanza de física</title>\n </head>\n <script>\n $(document).ready(function() {\n\n\n $(\".button-collapse\").sideNav();\n // Initialize collapse button\n $('.modal').modal();\n });\n\n\n\n </script>\n\n <body>\n\n <?php\n include (\"barra.html\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"encabezados\" -->\n <div id='banner'>\n <div class=\"row\">\n <header>\n <div class=\"col s12 m5 l6\">\n <!--Aquí va el titulo de la pagina que aparece al lado del logo-->\n <h2 style=\"padding:20%;\">Sistema 4MAT</h2>\n <!--------------------------------------------------------------->\n </div>\n <div class=\"col s12 m6 l6\">\n <img src=\"images/4matl.png\" alt=\"logo\" class=\"imagenLogo\" />\n </div>\n </header>\n </div>\n </div>\n\n\n\n\n <?php \n include(\"BarraConfiguracion.php\");\n ?>\n\n\n <!-- InstanceBeginEditable name=\"content\" -->\n <div class=\"contenido\">\n <article>\n <div>\n <center>\n <img src=\"images/Bienvenidos.png\" style=\" width: 35%;\" />\n </center> \n\n \n </div>\n </article>\n <div class=\"row\">\n <div class=\"col s12 l6\">\n <iframe src=\"https://www.youtube.com/embed/kClegf3b984\" frameborder=\"0\" style=\" width: 100%; height: 320px;\" ></iframe>\n </div>\n \n <div class=\"col s12 l6\">\n\n <div>\n \n <p>\n Estimado(a) investigador(a), en esta página encontrará un cuestionario de 30 preguntas que tiene por objetivo conocer el grado de comprensión, principalmente, de los fenómenos de reflexión y refracción de ondas sonoras en estudiantes de pregrado (bachillerato y licenciatura). Las primeras 20 preguntas guardan relación con los fenómenos señalados desde un punto de vista general y las últimas diez incluyen aspectos relacionados con el ámbito de la salud, de tal manera que, si los estudiantes no pertenecen a carreras del área de la salud, solo serían aplicables las primeras 20 preguntas y si pertenecen, entonces sería aplicable la totalidad del cuestionario. Cada pregunta tiene cinco alternativas de respuesta, de las cuales una sola es correcta.</p>\n \t<p>\n\t\t\t\t\t\tCuando usted ingrese al cuestionario para su análisis, al final de cada pregunta, encontrará una escala que busca medir el grado de dificultad que usted considera que tiene cada pregunta, donde cero quiere decir que la pregunta es demasiado fácil y diez que es muy compleja. Elija el número que más se acerque a su percepción. Posteriormente, habrá un espacio donde podrá agregar algún comentario que considere pertinente a la pregunta, ya sea sobre la redacción, la misma dificultad de la pregunta, su coherencia, etc. </p>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\tAdicionalmente, en el lado derecho del cuestionario, encontrará seis preguntas que buscan obtener su impresión, no de cada pregunta en particular, sino del cuestionario en su conjunto. </p>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\tEl sistema guardará automáticamente todos sus comentarios al pasar de una pregunta a otra y usted podrá modificarlos, así como entrar y salir del cuestionario, la veces que estime conveniente.\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\tAgradecemos sinceramente su valiosa cooperación.\n </p>\n \n <br />\n\n </div>\n </div>\n </div>\n <?php\n\t\t\t\t//if($_SESSION[\"acceso\"][3]==\"No\"){\n\t\t\t\t\tif($_SESSION[\"acceso\"][4]==\"Default\"){\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t?>\n \n <div class=\"row\">\n <!-- para los alumnos --->\n <div class=\"input-field col s2\" style=\"padding-left:45%;\"> \n <!-- encuestaPreguntas.php-->\n\t\t\t\t\t\t\t\t\t<a href=\"#modalverifica\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Empezar Cuestionario\n\t\t\t\t\t\t\t\t\t\t<i class=\"material-icons right\">send</i>\n </button></a>\n </div>\n \n <?php\n\t\t\t \t}\n\t\t\t\t\telse if($_SESSION[\"acceso\"][4]==\"Administrador\"){\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t<div class=\"col s6\" style=\"padding-left:47.7%;\">\n <a href=\"administracionEncuesta.php\">\n <button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Administración\n\t\t\t\t\t\t\t\n </button></a>\n </div>\n\t\t\t\t\t\t<div class=\"input-field col s6\" style=\"padding-left:45%;\">\n <a href=\"todasPreguntas.php\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Empezar Cuestionario\n <i class=\"material-icons right\">send</i>\n </button></a>\n </div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t<?php\n\t\t\t\t\t}\n\t\t\t\telse{\n\t\t\t ?>\n <!--para los profesores--> \n <div class=\"input-field col s6\" style=\"padding-left:45%;\">\n <a href=\"todasPreguntas.php\"><button class=\"btn waves-effect waves-light\" style=\"color:white;\" >Empezar Cuestionario\n <i class=\"material-icons right\">send</i>\n </button></a>\n </div>\n \n </div>\n \n <?php\n\t\t\t\t\t}\n\t\t\t\t//}\n\t \t\t\t/*\n\t \t\t\telse{\n\t\t\t\t\t\n\t\t\t?>\n\t\t\t\t<div class=\"input-field col s6\" style=\"padding-left:45%;\">\n\t\t\t\t\t\t\t\t\t<p>Usted ya ha contestado anteriormente la encuesta.</p>\n\t\t\t</div>\n\t\t\t<?php\n\t\t\t\t\t\n\t\t\t\t}*/\n\t\t\t?>\n \n \n </div>\n \n <!--modal para verificar si es alumno o profesor-->\n <div id=\"modalverifica\" class=\"modal\">\n <div class=\"modal-content\">\n <h4>En construcción:</h4>\n <p>Esta sección no esta habilitada para los alumnos.</p>\n </div>\n <div class=\"modal-footer\">\n <a href=\"\" class=\"modal-action modal-close waves-effect waves-green btn-flat\"></a>\n </div>\n </div>\n \n \n <!-- InstanceEndEditable -->\n <footer>\n <!--Aqui va el pie de pagina-->\n <br>\n <p>2015 © physics-education.tlamatiliztli.mx | All Rights Reserved | Desarrollado por alumnos PIFI</p>\n <br>\n </footer>\n </body>\n <!-- InstanceEnd -->\n\n</html>\n\n<?php\n\t}\n\telse{\n\t\t echo \"<script language=Javascript> location.href=\\\"4mat.php\\\"; </script>\"; \n\t}\n?>\n\n\n\n\n" }, { "alpha_fraction": 0.5283706188201904, "alphanum_fraction": 0.5490196347236633, "avg_line_length": 23.84482765197754, "blob_id": "80ffff1029272fb263d3659dd24034322dcca76d", "content_id": "9a0c501462d03a7ba1c4bd73f18a927833027863", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5771, "license_type": "permissive", "max_line_length": 134, "num_lines": 232, "path": "/controlador/procesaCuest.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire_once(\"connection.php\");\n\t\n\t////////////////////////////////////////////////////////\n\t//Funciones para obtener todos los parametros del POST//\n\t////////////////////////////////////////////////////////\n\t$numero2 = count($_POST); //Obtniene el numero de variables totales\n\t$tags2 = array_keys($_POST); // obtiene los nombres de las varibles\n\t$valores2 = array_values($_POST);// obtiene los valores de las varibles\n\t////////////////////////////////////////////////////////\t\n\t\n\t/* Ejemplo 1 de como usar un 'SPLIT' en PHP 5\n\t$pizza = \"porción1 porción2 porción3 porción4 porción5 porción6\";\n\t$porciones = explode(\" \", $pizza);\n\techo $porciones[0]; // porción1\n\techo $porciones[1]; // porción2\n\t*/\n\t$matrizResultados=array(array()); //Creo una matriz donde iran los resultados\n\t$matrizResultados=iniMatrizR($matrizResultados); //Inicializo la matriz\n\t//imprimeMatrizR($matrizResultados);\n\t$idUsuario;\n\t$idCuestionario;\n\tfor($i=0;$i<$numero2;$i++)\n\t{\n\t\t//Recorro los reultados del POST y lleno la matriz\n\t\t$estilo_valor=explode(\"-\",$valores2[$i]);\n\t\t$valores2[$i]=$estilo_valor;\n\t\t$numPregunta_numOpcion=explode(\"-\",$tags2[$i]);\n\t\t$tags2[$i]=$numPregunta_numOpcion;\n\t\tif($i==($numero2-1))\n\t\t{\n\t\t\t$idCuestionario=$valores2[$i][0];;\n\t\t\t$idUsuario=$valores2[$i][1];\t\t\t\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t\t$matrizResultados=llenarMatriz($valores2[$i][0],$valores2[$i][1],$matrizResultados);\n\t\t\t//echo \"NumPregunta: \".$tags2[$i][0].\" NumOpcion: \".$tags2[$i][1].\" Estilo: \".$valores2[$i][0].\" Valor: \".$valores2[$i][1].\"<br>\";\n\t\t}\n\t}\n\t//echo \"<br><h1>La matriz llena</h1><br>\";\n\t//imprimeMatrizR($matrizResultados);\n\n\t//echo \"<br><h1>La matriz Multiplicada</h1><br>\";\n\t//imprimeMatrizR(multiplicaMatriz($matrizResultados));\n\t$tuplaResultado=sumaColumnas(multiplicaMatriz($matrizResultados));\n\t//echo \"<h1>Tupla Resultado</h1><br>\".$tuplaResultado[0].\"|\".$tuplaResultado[1].\"|\".$tuplaResultado[2].\"|\".$tuplaResultado[3].\"<br>\";\n\t/*\t Estilos\n\t\tR\t5 | 2 | 2 | 6 | \n\t\te \t1 | 6 | 4 | 4 | \n\t\ts \t6 | 3 | 5 | 1 | \n\t\tp \t3 | 4 | 4 | 4 | \n\t*/\n\t$combinacionEstilo=array();\n\tif(count(array_count_values($matrizResultados[3]))==4)\n\t{\t\t\n\t\tarsort($matrizResultados[3]);\n\t\t\n\t\tforeach($matrizResultados[3] as $key => $valor)\n\t\t{\n\t\t\tarray_push($combinacionEstilo,($key+1));\n\t\t}\n\t}\n\telse\n\t{\n\t\t$combinacionEstilo=obtCombEst($matrizResultados,$tuplaResultado);\n\t}\n\t\n\tguardaResultado($combinacionEstilo,$idUsuario,$idCuestionario);\t\n\t/************************************************ FUNCIONES ************************************************/\n\tfunction guardaResultado($r,$idU,$idC)\n\t{\n\t\t//Conexion a la BD//\n\t\t$conexion = new connection();\n\t\n\t\t$resultado=\"\";\n\t\tfor($i=0;$i<count($r);$i++)\n\t\t{\n\t\t\tif($i!=(count($r)-1))\n\t\t\t\t$resultado=$resultado.$r[$i].\"-\";\n\t\t\telse\n\t\t\t\t$resultado=$resultado.$r[$i];\n\t\t}\n\t\t\n\t\t$query=\"select * from cuestionarioResuelto where idUsuario=\".$idU.\" and idCuestionario=\".$idC.\" and fecha=CURDATE()\";\n\t\t//echo \"<h1>\".$query.\"</h1>\";\n\t\t$conexion->conectar();\n\t\t$conexion->myQuery($query);\n\t\tif($conexion->getFilas())//Si me regresa tuplas significa que ya esta registrado\n\t\t{\n\t\t\techo \"<script language='JavaScript' type='text/javascript'> \n \talert('Al parecer no puedes contestar de nuevo el cuestionario tan pronto.'); location.href='../4mat.php';\n </script>\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$query=\"insert into cuestionarioResuelto values(\".$idU.\",\".$idC.\",now(),'\".$resultado.\"')\";\n\t\t//echo \"<h1>\".$query.\"</h1>\";\n\t\t\t$conexion->myQuery($query);\n\t\t\techo \"<script language='JavaScript' type='text/javascript'> \n \tlocation.href='../resultados.php?id=\".$idC.\"'; \n \t </script>\"; /////////////////////////////////////CAMBIAR AQUI LA ACCION CON EL ID CUESTIONARIO\n\n\t\t\t\t\t\n\t\t}\n\t\t$conexion->desconectar();\n\t\t\n\t\t\n\t}\n\tfunction obtCombEst($matrizR,$tupla)\n\t{\n\t\t$combinacionEstilo=array();\n\t\t$mayor_pos=mayorPos($matrizR[3]);\n\t\t//Paso (2)\n\t\tfor($i=$mayor_pos[0];$i!=0;$i--)\n\t\t{\n\t\t\t$repetidos=obtenerRepet($matrizR[3],$i);\n\t\t\t\t\t\t\t\t\n\t\t\tif(count($repetidos)==0)\n\t\t\t{\n\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(count($repetidos)==1)//Si no hay repetidos\n\t\t\t\t{\t\t\n\t\t\t\t\tarray_push($combinacionEstilo,($repetidos[0]+1));\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tarsort($tupla);\n\t\t\t\t\tforeach($tupla as $key => $valor)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(in_array($key, $repetidos))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tarray_push($combinacionEstilo,($key+1));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn $combinacionEstilo;\n\t}\t\n\n\tfunction sumaColumnas($matriz)\n\t{\n\t\t$tupla=array(0,0,0,0);\n\t\tfor($i=0;$i<4;$i++)\n\t\t{\n\t\t\tfor($j=0;$j<4;$j++)\n\t\t\t{\n\t\t\t\t\n\t\t\t\t$tupla[$j]+=$matriz[$i][$j];\n\t\t\t}\n\t\t}\n\t\treturn $tupla;\n\t\t\n\t}\n\tfunction llenarMatriz($estilo,$valor,$matrizResultados)\n\t{\n\t\t$matrizResultados[$valor-1][$estilo-1]++;\n\t\treturn $matrizResultados;\n\t}\n\tfunction iniMatrizR($matrizResultados)\n\t{\n\t\tfor($i=0;$i<4;$i++)\n\t\t{\n\t\t\tfor($j=0;$j<4;$j++)\n\t\t\t{\n\t\t\t\t$matrizResultados[$i][$j]=0;\n\t\t\t}\n\t\t}\n\t\treturn $matrizResultados;\n\t}\n\tfunction imprimeMatrizR($matrizResultados)\n\t{\n\t\tfor($i=0;$i<4;$i++)\n\t\t{\n\t\t\tfor($j=0;$j<4;$j++)\n\t\t\t{\n\t\t\t\techo $matrizResultados[$i][$j].\" | \";\n\t\t\t}\n\t\t\techo \"<br>\";\n\t\t}\n\t}\n\tfunction multiplicaMatriz($matriz)\n\t{\n\t\tfor($i=0;$i<4;$i++)\n\t\t{\n\t\t\tfor($j=0;$j<4;$j++)\n\t\t\t{\n\t\t\t\t$matriz[$i][$j]*=($i+1);\n\t\t\t}\n\t\t}\n\t\treturn $matriz;\n\t}\n\tfunction mayorPos($m)\n\t{\n\t\t$mayor_pos=array(0,0);\n\t\t\n\t\tfor($i=0;$i<count($m);$i++)\n\t\t{\n\t\t\tif($m[$i]>$mayor_pos[0])\n\t\t\t{\n\t\t\t\t$mayor_pos[0]=$m[$i];\n\t\t\t\t$mayor_pos[1]=$i;\n\t\t\t}\n\t\t}\n\t\treturn $mayor_pos;\n\t}\n\tfunction obtenerRepet($matriz,$mayor)\n\t{\n\t\t$posiciones=array();\n\t\t$contador=0;\n\t\tfor($i=0;$i<count($matriz);$i++)\n\t\t{\n\t\t\tif($matriz[$i]==$mayor)\n\t\t\t{\n\t\t\t\t\n\t\t\t\t$posiciones[$contador]=$i;\n\t\t\t\t$contador++;\n\t\t\t}\n\t\t}\n\t\treturn $posiciones;\n\t}\n\t/***********************************************************************************************************/\n\t\n?>" }, { "alpha_fraction": 0.605042040348053, "alphanum_fraction": 0.6058823466300964, "avg_line_length": 26.06818199157715, "blob_id": "a35ef1d37322cf97f26fc61ff395a2ec77bb1c46", "content_id": "5c5435a961539d8370d761a4fcf3ffedb17ba218", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1190, "license_type": "permissive", "max_line_length": 114, "num_lines": 44, "path": "/public_html/app/modelo/ModeloInstitucion.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ModeloInstitucion{\n\t\tprotected $db;\n\t\t\n\t\tpublic function __construct(){\n\t\t\t$this->db = new Connection();\n\t\t\t$this->db ->conectar();\n\t\t}\n\t\t\n\t\tpublic function validarDatos($bean){\n\t\t\t//echo 'Desde el modelo: '.$socio->getNombreCompleto();\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tpublic function insertar($bean){\n\t\t\t$query = 'insert into institucion(nombre,siglas) ';\n\t\t\t$query .= 'values(\"'.$bean->getNombre().'\",\"'.$bean->getSiglas().'\")';\n\t\t\t$this->db -> myQuery($query);\n\t\t}\n\t\t\n\t\tpublic function getInstituciones($busqueda){\n\t\t\t$query = 'select * from institucion order by siglas';\n\t\t\t\n\t\t\tif($busqueda != ''){\n\t\t\t\t$query = 'select * from institucion where nombre LIKE \"%'.$busqueda.'%\" order by siglas';\n\t\t\t}\n\t\t\t$this->db -> myQuery($query);\n\t\t\t\n\t\t\t$datos = array();\n\t\t\twhile ($row = $this->db ->getArrayFila()) {\n\t\t\t\t$datos[] = $row;\n \t\t\t}\n\t\t\t\n\t\t\treturn $datos;\n\t\t}\n\t\t\n\t\tpublic function buscarPorNombre($nombre, $siglas){\n\t\t\t$query = 'select idInstitucion from institucion where nombre LIKE \"'.$nombre.'\" and siglas LIKE \"'.$siglas.'\"';\n\t\t\t$this->db -> myQuery($query);\n\t\t\t$datos = $this->db ->getArrayFila();\n\t\t\treturn $datos['idInstitucion'];// Regresa el id de una institucion\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.5233393311500549, "alphanum_fraction": 0.5278276205062866, "avg_line_length": 24.930233001708984, "blob_id": "23bc996d901390c7c65bf6b5b9e09a9560f3c50d", "content_id": "e68b2c5053381d6f58aaccf7d36995fac46c928c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1116, "license_type": "permissive", "max_line_length": 146, "num_lines": 43, "path": "/BarraConfiguracion.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<script>\n $(document).ready(function() {\n\n $(document).ready(function(){\n $('.collapsible').collapsible();\n });\n });\n</script>\n<?php //if($banderaSesion){ ?>\n<div class=\"row\">\n<div class=col s20 style=\"float:right;\">\n<div id='menu2'>\n\n\n <!------PONER ID ACTUAL AL QUE ESTES EDITANDO---------------->\n <div class=\"chip\">\n <img src=\"images/persona.jpg\" alt=\"Contact Person\">\n <?php echo $_SESSION[\"acceso\"][1].\" \".$_SESSION[\"acceso\"][2]; ?>\n </div>\n <ul class=\"collapsible\" data-collapsible=\"accordion\" style=\"display:inline-block;\">\n \n\n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">person_pin</i>\n Mi Perfil\n </div>\n <div class=\"collapsible-body\"><p> <a href=\"modificaContrasena.php\">Modificar Contraseña</a></p></div>\n </li>\n\n <li>\n <div class=\"collapsible-header\"><i class=\"material-icons\">settings_power</i><a href=\"controlador/logout.php\">Cerrar Sesión</a></div>\n\n </li>\n </ul>\n\n\n\n\n</div>\n </div>\n</div>\n\n<?php //} ?>" }, { "alpha_fraction": 0.5932415723800659, "alphanum_fraction": 0.5938673615455627, "avg_line_length": 25.649999618530273, "blob_id": "f17978c921a2ec37374944aa8f9b4fea521a0fc1", "content_id": "b6778793d12ce2fb324b035575e827bfded7a08d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 112, "num_lines": 60, "path": "/public_html/app/modelo/ModeloEscuela.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\tclass ModeloEscuela{\n\t\tprotected $db;\n\t\t\n\t\tpublic function __construct(){\n\t\t\t$this->db = new Connection();\n\t\t\t$this->db ->conectar();\n\t\t}\n\t\t\n\t\tpublic function validarDatos($bean){\n\t\t\t//echo 'Desde el modelo: '.$socio->getNombreCompleto();\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tpublic function insertar($bean){\n\t\t\t$query = 'insert into escuela(nombre,direccion,idInstitucion) ';\n\t\t\t$query .= 'values(\"'.$bean->getNombre().'\",\"'.$bean->getDireccion().'\",\"'.$bean->getIdInstitucion().'\")';\n\t\t\t$this->db -> myQuery($query);\n\t\t}\n\t\t\n\t\tpublic function getEscuelas($busqueda){\n\t\t\t$query = 'select * from escuela order by idInstitucion, nombre';\n\t\t\t\n\t\t\tif($busqueda != ''){\n\t\t\t\t$query = 'select * from escuela where nombre LIKE \"%'.$busqueda.'%\" order by idInstitucion, nombre';\n\t\t\t}\n\t\t\t$this->db -> myQuery($query);\n\t\t\t\n\t\t\t$datos = array();\n\t\t\twhile ($row = $this->db ->getArrayFila()) {\n\t\t\t\t$datos[] = $row;\n \t\t\t}\n\t\t\t\n\t\t\treturn $datos;\n\t\t}\n\t\t\n\t\tpublic function buscarPorInstitucion($busqueda){\n\t\t\t$query = 'select * from escuela';\n\t\t\t\n\t\t\tif($busqueda != ''){\n\t\t\t\t$query .= ' where idInstitucion = '.$busqueda.' order by nombre';\n\t\t\t}\n\t\t\t$this->db -> myQuery($query);\n\t\t\t\n\t\t\t$datos = array();\n\t\t\twhile ($row = $this->db ->getArrayFila()) {\n\t\t\t\t$datos[] = $row;\n \t\t\t}\n\t\t\t\n\t\t\treturn $datos;\n\t\t}\n\t\t\n\t\tpublic function buscarPorNombre($nombre, $direccion){\n\t\t\t$query = 'select idEscuela from escuela where nombre LIKE \"'.$nombre.'\" and direccion LIKE \"'.$direccion.'\"';\n\t\t\t$this->db -> myQuery($query);\n\t\t\t$datos = $this->db ->getArrayFila();\n\t\t\treturn $datos['idEscuela'];// Regresa el id de una escuela\n\t\t}\n\t}\n?>" }, { "alpha_fraction": 0.6016810536384583, "alphanum_fraction": 0.6103198528289795, "avg_line_length": 31.94615364074707, "blob_id": "3526a52dd000d3f1039d29d2511194a4887b3c90", "content_id": "c794686f0c99559eb92d74ef34f06c87d2284ac2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4291, "license_type": "permissive", "max_line_length": 150, "num_lines": 130, "path": "/public_html/app/templates/material.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Materil Didactico</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"jscripts/dropzone/min/dropzone.min.css\">\n<script language=\"javascript\" type=\"text/javascript\" src=\"jscripts/jquery-3.1.1.min.js\"></script>\n<script language=\"javascript\" type=\"text/javascript\" src=\"jscripts/dropzone/min/dropzone.min.js\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"css/material.css\">\n\n<link href=\"http://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"css/materialize.css\" media=\"screen,projection\" />\n\t\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n\t\t<script type=\"text/javascript\" src=\"js/materialize.min.js\"></script>\n<script>\n\t/* *****************************************\n\t//Tomado de: http://www.dropzonejs.com/\n\t*******************************************/\n\tDropzone.autoDiscover = false;\n\t$(document).ready(function(e) {\n\t\tvar myDropzone = new Dropzone(\"#myDropZone\", { \n\t\t\turl: \"material.php\",\n\t\t\tautoProcessQueue:false,\n\t\t\tinit:function(){\n\t\t\t\tthis.on(\"drop\",function(file){\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t\tthis.on(\"success\",function(file,resp){\n\t\t\t\t\t$(\"#resp_Upl\").html(resp);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t\t$(\"#btnFileUpl\").on(\"click\",function(e){\n\t\t\talert(\"Estamos subiendo su archivo, por favor espere\");\n\t\t\te.preventDefault();\n\t\t\tmyDropzone.processQueue(); \n\t\t}); \t\n });\n</script>\n</head>\n\n<?php\n\tfunction formatBytes($bytes, $precision ) { \n\t $units = array('B', 'KB', 'MB', 'GB', 'TB'); \n\n\t $bytes = max($bytes, 0); \n\t $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); \n\t $pow = min($pow, count($units) - 1); \n\t return round($bytes, $precision) . ' ' . $units[$pow]; \n\t} \n\n\trequire(\"../controlador/Sesion.php\");\n\trequire(\"../bean/Socio.php\");\n\tif(isset($_FILES[\"file\"])){\n\n\t\t//Directorio donde quiero 'subir' el archivo\n\t\t//$directorio = \"C:/wamp64/www/otros/sem20171/uploadFiles/\";;\n\t\tsession_start();\n\t\t$directorio = getcwd().\"/docs/\";\n\t\t$sesion = new Sesion();\n\t\t$usuario = $sesion->getSesion('login');\n\t\t$socio = $sesion->getSesion('socio');\n\t\t$mem=$socio->getNoMembresia();\n\n\t\t$nombreArchivo = basename($_FILES[\"file\"][\"name\"]);\n\t\t$filesize= round(($_FILES[\"file\"][\"size\"])/1024, 2);\n\t\t$filesize.=\" KB\";\n\n\t\t\n\t\t//Respetar el nombre original del archivo\n\t\t\n\t\t/*\n\t\t//Asignar un nombre fijo al archivo. Primero recupero la extensión del archivo\n\t\t\n\t\t$tmp = explode(\".\", $_FILES[\"archivoUpl\"][\"name\"]);\n\t\t$extensionArchivo = end($tmp);\n\t\t$nombreArchivo = \"archivoQueSubi.\".$extensionArchivo;\n\t\t\n\t\t\n\t\t//Asignar nombre dinamicamente. Primero recupero la extensión del archivo\n\t\t\n\t\t$tmp = explode(\".\", $_FILES[\"archivoUpl\"][\"name\"]);\n\t\t$extensionArchivo = end($tmp);\n\t\t$idArchivo = uniqid();\n\t\t$nombreArchivo = $idArchivo.\".\".$extensionArchivo;\n\t\t\n\t\t*/\t\n\t\t$rutaArchivo = $directorio.$nombreArchivo;\n\t\tif(move_uploaded_file($_FILES[\"file\"][\"tmp_name\"], $rutaArchivo)){\n\t\t\t$conexion=mysqli_connect(\"aapt-mx.org\",\"aaptmx\",\"ylatesis?\",\"aaptmx_db_prueba\");\n\t $sql=\"insert into material (Nombre, noMembresia, Tamano, Fecha, Paths) values ('$nombreArchivo',$mem,'$filesize',CURDATE(),'$rutaArchivo');\";\n\t //echo $sql;\n\t $res = mysqli_query($conexion, $sql);\n\t \n \n\t\t\n\t\t\t/*echo \"<h3 style='color:green'>= = = = El fichero es válido y se subió con éxito. = = = =</h3>\";\n\t\t\techo \"<code>\";\n\t\t\techo \"Nombre de archivo: \". $_FILES[\"file\"][\"name\"];\n\t\t\techo \"<br>\";\n\t\t\techo \"Tipo de archivo: \". $_FILES[\"file\"][\"type\"];\n\t\t\techo \"<br>\";\n\t\t\techo \"Tama&ntilde;o de archivo: \". round(($_FILES[\"file\"][\"size\"])/1024, 2).\" KB\";\n\t\t\techo \"</code>\";*/\n\t\t\t echo \"<script> alert (\\\"Se ha subido el archivo con éxito\\\"); </script>\"; \n\t\t} else {\n\t\t\techo \"<h3 style='color:red'>¡Posible ataque de subida de ficheros!</h3>\";\n\t\t}\n\t\t//echo \"<p><a href='material.php'>Regresar</a></p>\";\n }else{\n?>\n\n<body>\n\t<div id=\"myDropZone\" class=\"dropzone\" style=\"background:none;\">\n\t <span id=\"mispan\">\n\t <h5>Arrastre su archivo o de click aquí</h5>\n\t </span>\n\t</div>\n <center>\n <a class=\"waves-effect waves-light btn\"><i class=\"material-icons right\">cloud</i><input type=\"button\" id=\"btnFileUpl\" value=\"Enviar\"></a>\n <div id=\"resp_Upl\"></div>\n </center>\n \n</body>\n</html>\n<?php\n\t}\n?>\n" }, { "alpha_fraction": 0.5179216265678406, "alphanum_fraction": 0.5295915603637695, "avg_line_length": 35.35353469848633, "blob_id": "f38ae477f6342dfd252b570bfc755fa4109e006e", "content_id": "f341173ab91f392f2073d7efdfff525a50ffab4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3603, "license_type": "permissive", "max_line_length": 273, "num_lines": 99, "path": "/public_html/app/templates/mdidactico.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start(); \n //session_start();\n $sesion = new Sesion();\n $usuario = $sesion->getSesion('login');\n $socio = $sesion->getSesion('socio');\n $mem=$socio->getNoMembresia();\n if($usuario!=false){\n $tablasin=\"\";\n $tablacon=\"\";\n\n $tablasin=\"\n <table class='responsive-table'>\n <thead>\n <tr>\n <th data-field='material'>Material</th>\n <th data-field='usuario'>Subido por</th>\n <th data-field='tamano'>Tamaño</th>\n <th data-field='fecha'>Fecha</th>\n <th data-field='descarga'>Descarga</th>\";\n $tablacon.=$tablasin;\n $tablacon.=\"<th data-field='descarga'>Eliminar</th>\";\n $tablasin.=\"</tr></thead><tbody>\";\n $tablacon.=\" </tr></thead><tbody>\"; \n ?>\n <?php\n\t\t$mysqli= new mysqli(\"aapt-mx.org\",\"aaptmx\",\"ylatesis?\",\"aaptmx_db_prueba\") ;\n\t\tif (mysqli_connect_errno())\n\t\t{\n\t\t \tprintf(\"Falló la conexión failed: %s\\n\", $mysqli->connect_error);\n\t \t\texit();\n\t\t}\n\t\t$query = \"SELECT m.Nombre, s.prefijo, s.nombreCompleto, m.Tamano, m.Fecha, m.Paths FROM socio s, material m WHERE m.noMembresia = s.noMembresia order by m.Fecha;\";\n\t\t$result = mysqli_query($mysqli,$query);\n \n\t\twhile ($line = mysqli_fetch_array($result, MYSQLI_BOTH)) \n\t\t{\n\t\t//echo $line [0]; YA FUNCIONA \n\n //agrego un tokenizer para eliminar partes del path que no quiero\n \n\t\t $tablasin.=\"<tr>\";\n\t\t $tablasin.=\"<td>$line[0]</td><td>$line[1] $line[2]</td><td>$line[3]</td><td>$line[4]</td>\";\n\t\t $tablasin.=\"<td><a href='/app/templates/docs/$line[0]' download> <img style='width: 61px;' src='app/templates/css/imagenes/descarga.png'></a> </td>\";\n $tablacon.=\"<tr>\";\n $tablacon.=\"<td>$line[0]</td><td>$line[1] $line[2]</td><td>$line[3]</td><td>$line[4]</td>\";\n $tablacon.=\"<td><a href='/app/templates/docs/$line[0]' download> <img style='width: 61px;' src='app/templates/css/imagenes/descarga.png'></a> </td>\";\n $tablacon.=\"<td><form action='' method='POST' style=' margin: inherit; background: white; padding: initial; border: 0px; '><input type='image' style='width: 61px;' src='app/templates/css/imagenes/delete1.ico' name='valor' value='$line[5]' /> </form></td>\";\n $tablasin.=\"</tr>\";\n $tablacon.=\"</tr>\";\n\t\t}\n if($mem==9 || $mem==19 || $mem==22 || $mem==5){\n echo $tablacon;\n }\n else{\n echo $tablasin;\n }\n\n\t?>\t\t\n </tbody>\n </table>\n <?php\n\n \n\t\n\n if($mem==9 || $mem==19 || $mem==22 || $mem==5){\n\n ?>\n <center>\n <div class=\"amazingcarousel-item-container\">\n <div class=\"amazingcarousel-image\"><a href=\"app/templates/material.php\" title=\"\" class=\"html5lightbox\" data-group=\"amazingcarousel-1\" data-width=\"500\" data-height=\"350\">\n <img src=\"app/templates/css/imagenes/subirm.png\">\n </a></div>\n </div>\n </center> \n <?php\n if(isset($_POST['valor'])){\n // echo $_POST['valor'];\n if(unlink($_POST['valor'])){\n //echo \"lo logre\";\n $path=$_POST['valor'];\n $query=\"DELETE from material where Paths like('%$path%');\";\n $result = mysqli_query($mysqli,$query);\n echo \"<script> alert (\\\"Se ha eliminado el archivo con éxito\\\"); </script>\"; \n echo \"<script language=Javascript> location.href=\\\"index.php\\\"; </script>\"; \n die(); \n }\n \n }\n }\n }\n \n ?>\n \n\n\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>\n" }, { "alpha_fraction": 0.5676781535148621, "alphanum_fraction": 0.5813160538673401, "avg_line_length": 24.955751419067383, "blob_id": "974a41c4a47843af51dc913da6b36d0c8b98f20e", "content_id": "d7de72ccd76bd8c2b4d3ea0ba24c4c23b4a366bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2936, "license_type": "permissive", "max_line_length": 121, "num_lines": 113, "path": "/recuperaPass.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php\n\trequire 'PHPMailer-master/PHPMailerAutoload.php';\n \n\t$email = $_POST['email'];\n\t$conexion=mysqli_connect(\"mssql.tlamatiliztli.net\",\"tlama_Encuesta\",\"ylatesis?\",\"tlamatil_Encuesta\");\n\tmysqli_set_charset($conexion,\"utf8\");\n\t$query = \"SELECT Passw FROM usuario WHERE email = '$email'\";\n\t$pai=mysqli_query($conexion,$query);\n\t\t$xm=0;\n\t\twhile($cuba=mysqli_fetch_array($pai,MYSQLI_BOTH)){\n\t\t\t$xm++;\n\t\t\t$pass=$email;\n\t\t\t$pass.=rand(200,8000);\n\t\t}\n\t\tif($xm <= 0){\n\t\t\t$no=\"Error, la cuenta que usted ingres&oacute; no existe en nuestro sistema\";\n\t\t\techo $no;\n\t\t}\n\t\telse{\n\t\t\t\n\t\t\t$encrpass=md5($pass);\n\t\t\t$ques = \"UPDATE usuario SET passw='$encrpass' WHERE email='$email'\";\n\t\t\t$pai=mysqli_query($conexion,$ques);\n\t\t\tif(!$pai){\n\t\t\t\t echo(\"Error description: \" . mysqli_error($conexion));\n\t\t\t}\n\t\t\t\n\t\t\t$mail = new PHPMailer;\n//$mail->SMTPDebug = 3; // Enable verbose debug output\n\n$mail->isSMTP(); // Set mailer to use SMTP\n$mail->Host = 'tlamatiliztli.net'; // Specify main and backup SMTP servers\n$mail->SMTPAuth = true; // Enable SMTP authentication \n$mail->Username = '[email protected]'; // SMTP username\n$mail->Password = '147896325'; // SMTP password\n\n$mail->Port = 25; // TCP port to connect to\n\n$mail->setFrom('[email protected]', 'NoReply: Servicio de Email 4MAT');\n$mail->addAddress($email, 'Usuario'); // Add a recipient\n$mail->addReplyTo('[email protected]', 'NoReply: Servicio de Email 4MAT');\n$mail->addCC('[email protected]');\n$mail->addBCC($email); // Set email format to HTML\n\n$mail->Subject = 'Renvio de contraseña';\n$mail->Body = '\n<style type=\"text/css\">\n body,\n html, \n .body {\n background: #f3f3f3 !important;\n }\n\n .container.header {\n background: #f3f3f3;\n }\n\n .body-border {\n border-top: 8px solid #663399;\n }\n</style>\n\n<container class=\"header\">\n <row>\n <columns>\n <h1 class=\"text-center\"><center>Tlamatiliztli</center></h1>\n\n\n </columns>\n </row>\n</container>\n\n<container class=\"body-border\">\n <row>\n <columns>\n\n <spacer size=\"32\"></spacer>\n\n <center>\n <img src=\"http://physics-education.tlamatiliztli.net/images/logoIndex.png\">\n </center>\n\n <spacer size=\"16\"></spacer>\n\n <h4>Estimado usuario:</h4>\n <p>Agradecemos que haya preferido nuestra servicio de reposici&oacute;n de contraseñas, su nueva clave temporal es:\n \n <p>Contraseña: '.$pass.'</p>\n\n\t\t<p>Le recomendamos que a la brevedad la reestablezca dentro de: </p>\n\t\t<p>Menu --> Mi Perfil</p>\n \n\n </columns>\n </row>\n\n <spacer size=\"16\"></spacer>\n</container>\n';\n$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';\n\nif(!$mail->send()) {\n // echo 'Message could not be sent.';\n echo 'Mailer Error: ' . $mail->ErrorInfo;\n} else {\n echo 1;\n}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t}\n\n?>\n" }, { "alpha_fraction": 0.5919881463050842, "alphanum_fraction": 0.6127596497535706, "avg_line_length": 36.5, "blob_id": "ba5b66682d8eae901cd81e100acb05680504cda7", "content_id": "4e7dce31974ae145dea007c8e9982341f921af1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 675, "license_type": "permissive", "max_line_length": 84, "num_lines": 18, "path": "/public_html/app/templates/fomRegistroEscuela.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<?php if(isset($params['mensaje'])) :?>\n\t<b><span style=\"color: red;\"><?php echo $params['mensaje'] ?></span></b>\n<?php endif; ?>\n<br/>\n\n<form action=\"index.php?ctl=registroEsc\" method=\"post\">\n \t<h2>Registra tu escuela</h2>\n <input type=\"text\" placeholder=\" &#127979; Nombre de la escuela\" name=\"txtEsc\"> \n <input type=\"text\" placeholder=\" &#128506; Dirección\" name=\"txtDir\">\n <input name=\"idIns\" type=\"hidden\" value=\"<?php echo $_GET['idIns']; ?>\">\n <input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\">\n <input type=\"submit\" value=\"Registrar\">\n</form>\n<?php $contenido = ob_get_clean() ?>\n\n<?php include 'layout.php' ?>" }, { "alpha_fraction": 0.621337354183197, "alphanum_fraction": 0.633358359336853, "avg_line_length": 41.90322494506836, "blob_id": "9dd6752dcc80ab122384f9521b22119e4e84bf39", "content_id": "f6633398c1764e59ae0d80486494d3c867cb5e37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1337, "license_type": "permissive", "max_line_length": 177, "num_lines": 31, "path": "/public_html/app/templates/formBuscarInst.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php ob_start() ?>\n\n<?php if(isset($params['mensaje'])) :?>\n\t<b><span style=\"color: red;\"><?php echo $params['mensaje'] ?></span></b>\n<?php endif; ?>\n<br/>\n\n<!--\n<form action=\"index.php?ctl=mostrarIns\" method=\"post\">\n \t<h2>Busca tu Institución</h2>\n <input type=\"text\" placeholder=\" &#128270; Nombre de la institución\" name=\"txtBuscar\"> \n <input type=\"submit\" value=\"Buscar\">\n</form>\n-->\n<div id=\"RegistroP2\" class=\"modalDialog\">\n\t<a href=\"#\" title=\"Close\" class=\"close\">X</a> \n<form name=\"formElegirInstitucion\" method=\"post\" action=\"index.php?ctl=mostrarEsc\">\n\t<h1><span class=\"icon-mode_edit\"></span>Registro Paso 2 de 3</h1>\n <h2>Selecciona tu Institución</h2>\n\t<input name=\"mem\" type=\"hidden\" value=\"<?php echo $_GET['mem']; ?>\">\n\t<select name=\"idIns\">\n \t<option value=\"-1\">Selecciona una opción...</option>\n <?php foreach ($parametros['instituciones'] as $ins) :?>\n \t<option value=\"<?php echo $ins['idInstitucion']?>\"><?php echo $ins['siglas']?> - <?php echo $ins['nombre'] ?></option>\n <?php endforeach; ?>\n\t</select>\n <input type=\"submit\" value=\"Siguiente\">\n <p> *Si no encuentras la institución a la que perteneces puedes registrarla presionando clic <a href=\"index.php?ctl=registroIns&mem=<?php echo $_GET['mem']?>\">aquí</a>.</p>\n</form>\n</div>\n<?php $contenido = ob_get_clean() ?>\n\n" }, { "alpha_fraction": 0.6173713803291321, "alphanum_fraction": 0.6207039952278137, "avg_line_length": 35.371212005615234, "blob_id": "d30990c9a34ef9889390b5099f8309aac78f76ca", "content_id": "66b5a9cc332552b035bbcb51c9b39661a1c844e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4802, "license_type": "permissive", "max_line_length": 162, "num_lines": 132, "path": "/borrar/preguntas.php", "repo_name": "vickyleon/APTManualUsuario", "src_encoding": "UTF-8", "text": "<?php require_once('../Connections/rem.php'); ?>\n<?php\nif (!function_exists(\"GetSQLValueString\")) {\nfunction GetSQLValueString($theValue, $theType, $theDefinedValue = \"\", $theNotDefinedValue = \"\") \n{\n if (PHP_VERSION < 6) {\n $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;\n }\n\n $theValue = function_exists(\"mysql_real_escape_string\") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);\n\n switch ($theType) {\n case \"text\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break; \n case \"long\":\n case \"int\":\n $theValue = ($theValue != \"\") ? intval($theValue) : \"NULL\";\n break;\n case \"double\":\n $theValue = ($theValue != \"\") ? doubleval($theValue) : \"NULL\";\n break;\n case \"date\":\n $theValue = ($theValue != \"\") ? \"'\" . $theValue . \"'\" : \"NULL\";\n break;\n case \"defined\":\n $theValue = ($theValue != \"\") ? $theDefinedValue : $theNotDefinedValue;\n break;\n }\n return $theValue;\n}\n}\n\n$editFormAction = $_SERVER['PHP_SELF'];\nif (isset($_SERVER['QUERY_STRING'])) {\n $editFormAction .= \"?\" . htmlentities($_SERVER['QUERY_STRING']);\n}\n\nif ((isset($_POST[\"MM_update\"])) && ($_POST[\"MM_update\"] == \"form1\")) {\n $updateSQL = sprintf(\"UPDATE pregunta SET idCuestionario=%s, descripcionP=%s WHERE idPregunta=%s\",\n GetSQLValueString($_POST['idCuestionario'], \"int\"),\n GetSQLValueString($_POST['descripcionP'], \"text\"),\n GetSQLValueString($_POST['idPregunta'], \"int\"));\n\n mysql_select_db($database_rem, $rem);\n $Result1 = mysql_query($updateSQL, $rem) or die(mysql_error());\n}\n\nif ((isset($_POST[\"MM_update\"])) && ($_POST[\"MM_update\"] == \"form2\")) {\n $updateSQL = sprintf(\"UPDATE pregunta SET idCuestionario=%s, descripcionP=%s WHERE idPregunta=%s\",\n GetSQLValueString($_POST['idCuestionario'], \"int\"),\n GetSQLValueString($_POST['descripcionP'], \"text\"),\n GetSQLValueString($_POST['idPregunta'], \"int\"));\n\n mysql_select_db($database_rem, $rem);\n $Result1 = mysql_query($updateSQL, $rem) or die(mysql_error());\n}\n\nmysql_select_db($database_rem, $rem);\n$query_preguntas = \"SELECT * FROM pregunta ORDER BY idPregunta ASC\";\n$preguntas = mysql_query($query_preguntas, $rem) or die(mysql_error());\n$row_preguntas = mysql_fetch_assoc($preguntas);\n$totalRows_preguntas = mysql_num_rows($preguntas);\n\n$colname_buscarPregunta = \"-1\";\nif (isset($_POST['txtidPregunta'])) {\n $colname_buscarPregunta = $_POST['txtidPregunta'];\n}\nmysql_select_db($database_rem, $rem);\n$query_buscarPregunta = sprintf(\"SELECT * FROM pregunta WHERE idPregunta = %s\", GetSQLValueString($colname_buscarPregunta, \"int\"));\n$buscarPregunta = mysql_query($query_buscarPregunta, $rem) or die(mysql_error());\n$row_buscarPregunta = mysql_fetch_assoc($buscarPregunta);\n$totalRows_buscarPregunta = mysql_num_rows($buscarPregunta);\n?>\n<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Documento sin título</title>\n</head>\n\n<body>\n<form name=\"form1\" method=\"post\" action=\"\">\nidPregunta\n <input type=\"text\" name=\"txtidPregunta\" id=\"txtidPregunta\">\n <input type=\"submit\" name=\"Buscar\" id=\"Buscar\" value=\"Enviar\">\n</form>\n<p>&nbsp;</p>\n<form method=\"post\" name=\"form2\" action=\"<?php echo $editFormAction; ?>\">\n <table align=\"center\">\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">IdPregunta:</td>\n <td><?php echo $row_buscarPregunta['idPregunta']; ?></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">IdCuestionario:</td>\n <td><input type=\"text\" name=\"idCuestionario\" value=\"<?php echo htmlentities($row_buscarPregunta['idCuestionario'], ENT_COMPAT, 'utf-8'); ?>\" size=\"32\"></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">DescripcionP:</td>\n <td><textarea name=\"descripcionP\" size=\"32\"><?php echo $row_buscarPregunta['descripcionP']; ?></textarea></td>\n </tr>\n <tr valign=\"baseline\">\n <td nowrap align=\"right\">&nbsp;</td>\n <td><input type=\"submit\" value=\"Actualizar registro\"></td>\n </tr>\n </table>\n <input type=\"hidden\" name=\"MM_update\" value=\"form2\">\n <input type=\"hidden\" name=\"idPregunta\" value=\"<?php echo $row_buscarPregunta['idPregunta']; ?>\">\n</form>\n<p>&nbsp;</p>\n<table border=\"1\">\n <tr>\n <td>idPregunta</td>\n <td>idCuestionario</td>\n <td>descripcionP</td>\n </tr>\n <?php do { ?>\n <tr>\n <td><?php echo $row_preguntas['idPregunta']; ?></td>\n <td><?php echo $row_preguntas['idCuestionario']; ?></td>\n <td><?php echo $row_preguntas['descripcionP']; ?></td>\n </tr>\n <?php } while ($row_preguntas = mysql_fetch_assoc($preguntas)); ?>\n</table>\n</body>\n</html>\n<?php\nmysql_free_result($preguntas);\n\nmysql_free_result($buscarPregunta);\n?>\n" } ]
78
simranquirky/ExamResultGenerator
https://github.com/simranquirky/ExamResultGenerator
adf14a074d442d6df62f6571cbb4b3edb3050c7d
00d02b25d9e4fac03e44f284c9346911adc5fd32
e0de9febd4d90e52adb81368291c37c694805333
refs/heads/master
2023-06-29T13:42:56.320233
2021-08-02T06:13:01
2021-08-02T06:13:01
388,144,695
0
0
null
2021-07-21T14:32:11
2021-07-21T13:27:31
2021-07-13T05:55:26
null
[ { "alpha_fraction": 0.6327272653579712, "alphanum_fraction": 0.6618182063102722, "avg_line_length": 20.076923370361328, "blob_id": "252269d9b138c5acd534d644e26817b8bef99e90", "content_id": "6bf8044c895bfa78c58317f0474032acc8649532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 50, "num_lines": 13, "path": "/Backend/app.py", "repo_name": "simranquirky/ExamResultGenerator", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS, cross_origin\n\n\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return \"Hello From Flask Here\"\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", debug=True, port=5000)\n\n" } ]
1
mchelem/ml_class
https://github.com/mchelem/ml_class
50cef28e9e200931b139e9b23a9413a9674abd5b
93397d1eb247a74892df1c3e2a4b80bb26045fcb
b5497119ab0b3c4d54ebbd4d9af2cd28069bb1ba
refs/heads/master
2016-12-02T17:59:44.054551
2012-09-17T16:48:04
2012-09-17T16:48:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6728395223617554, "avg_line_length": 22.14285659790039, "blob_id": "7dd9a4b9fdbd6e6cf5c1ae5e03c438ed88c36223", "content_id": "61ddc12b97bb857b58ae57a5469032986f00801b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "no_license", "max_line_length": 53, "num_lines": 7, "path": "/intro_web_data/simple_clustering_demo.py", "repo_name": "mchelem/ml_class", "src_encoding": "UTF-8", "text": "import numpy\nimport Pycluster\n\ndata = numpy.array([(1, 1, 0), (1, 0, 0), (0, 0, 0)])\nprint data\nlabels, errors, nfound = Pycluster.kcluster(data, 2)\nprint labels\n" } ]
1
zvolsky/zitranavylet
https://github.com/zvolsky/zitranavylet
f1e2dc578fe03d9238ed0447f7d0f4e5f2831036
c1cd50bb89796511f809a90cbf4f50aeb09a7ce4
0c0701a858bf42fd56d223fb653c824d42366d23
refs/heads/master
2021-01-13T21:22:20.366342
2017-06-20T14:40:51
2017-06-20T14:40:51
53,584,556
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6572580933570862, "avg_line_length": 40.33333206176758, "blob_id": "7ef1794075e0f9e7ea4dc9688887c4540bc98faf", "content_id": "a0f0d080f7d76773c310fea3056f503ad5c6d32c", "detected_licenses": [ "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 56, "num_lines": 6, "path": "/models_disabled/0_portal.py", "repo_name": "zvolsky/zitranavylet", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nif 'mojeknihovna.eu' in request.env.http_host.lower():\n pass #redirect(URL('codex2020', 'default', 'index'))\nelif 'sluzbicka.eu' in request.env.http_host.lower():\n pass #redirect(URL('sluzbicka', 'default', 'index'))\n" } ]
1
amedumer/python-face-recognition
https://github.com/amedumer/python-face-recognition
99645cb29913f045e4cbb565d655916eac0d53a1
5cbf8eaf4f4c52512f1c2a4cfb395d1787258e1f
c4fea670f887660141c43358064744f7786ea21a
refs/heads/master
2022-12-15T14:29:41.705760
2020-09-03T19:42:18
2020-09-03T19:42:18
289,273,641
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6909999847412109, "alphanum_fraction": 0.7139999866485596, "avg_line_length": 29.24242401123047, "blob_id": "41ca76e771682e25e77ed8b71dc9ca03079d27a2", "content_id": "546312c245e6617aa5589c0271d51c35d599cba7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "permissive", "max_line_length": 113, "num_lines": 33, "path": "/find_face_by_photo/findFacesByPhoto.py", "repo_name": "amedumer/python-face-recognition", "src_encoding": "UTF-8", "text": "import cv2\nimport sys\nimport logging as log\nimport datetime as dt\nfrom time import sleep\n\n# This is our base recognition file, program recognizes faces by looking at this file\n# If you want to change the object you want to recognize, change the xml filename by looking at the cascades file\ncascPath = \"cascades\\\\haarcascade_frontalface_default.xml\"\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\n# choosing the source image file\nimgFile = cv2.imread(\"abba.png\")\n\n# Turning the frame into gray so our cascade file can recognize faces\ngray = cv2.cvtColor(imgFile, cv2.COLOR_BGR2GRAY)\n\n# Face detection funciton\nfaces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30)\n )\n\n# Draw a rectangle around the faces (w is for width, h is for height.) \nfor (x, y, w, h) in faces:\n cv2.rectangle(imgFile, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\ncaption = str(len(faces)) + \" Faces Found!\"\n\ncv2.imshow(caption, imgFile)\ncv2.waitKey(0)\n\n\n" }, { "alpha_fraction": 0.661575198173523, "alphanum_fraction": 0.6816229224205017, "avg_line_length": 29.823530197143555, "blob_id": "dec329f50cfabd7864a2be32fb012748243dff77", "content_id": "15be047d76d1c9b5b81540ded2e79f562d62b54f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2095, "license_type": "permissive", "max_line_length": 125, "num_lines": 68, "path": "/find_face_by_webcam/findFacesByWebcam.py", "repo_name": "amedumer/python-face-recognition", "src_encoding": "UTF-8", "text": "import cv2\nimport sys\nimport logging as log\nimport datetime as dt\nfrom time import sleep\nimport numpy as np\n\n# Basic face recognition with Python-OpenCV2\n# Don't forget to include cascade files in the project folder\n\n\n# Code below is for log creation, if you want to create logs, comment out the code block at line 50 and the below one.\n# log.basicConfig(filename='webcam.log',level=log.INFO)\n\n\n# This is our base recognition file, program recognizes faces by looking at this file\n# If you want to change the object you want to recognize, change the xml filename by looking at the cascades file\nfaceCascade = cv2.CascadeClassifier(\"cascades/haarcascade_frontalface_alt2.xml\")\n\n# This is the initialization for our video souce, if you have multiple cameras, you might want to change the index value (0) \nvideo_capture = cv2.VideoCapture(0)\n\n# Font for writing text on the screen\nfont = cv2.FONT_HERSHEY_COMPLEX\n\nwhile True:\n if not video_capture.isOpened():\n print('Unable to load camera.')\n sleep(5)\n pass\n\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n\n # Turning the frame into gray so our cascade file can recognize faces\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Face detection funciton\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30)\n )\n\n # Draw a rectangle around the faces (w is for width, h is for height.)\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n \"\"\"\n if len(faces) != 0:\n anterior = len(faces)\n log.info(\"faces: \"+str(len(faces))+\" at \"+str(dt.datetime.now()))\"\"\"\n\n # Writing a text on the frame\n cv2.putText(frame,\"Faces found: {}\".format(len(faces)),(5,30),font,1,255)\n\n # Display the resulting frame\n cv2.imshow('Video', frame)\n\n # Set the program to close when the key \"q\" is pressed\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.5806878209114075, "alphanum_fraction": 0.5952380895614624, "avg_line_length": 24.27118682861328, "blob_id": "59902b337db65f2324a0ae60e71d0f7b331eb0ba", "content_id": "ea70614720d5db2197aaba9235453fc443bc0415", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "permissive", "max_line_length": 132, "num_lines": 59, "path": "/extract_faces/extract_faces.py", "repo_name": "amedumer/python-face-recognition", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport cv2\nimport time\n# Takes image files from images folder and saves found objects under new foler\nface_cascade = cv2.CascadeClassifier(\"cascades/haarcascade_frontalface_alt2.xml\")\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nimage_dir = os.path.join(BASE_DIR, \"images\")\n\nfor root,dirs,files in os.walk(image_dir):\n\n\tlabel = os.path.basename(root).replace(\" \",\"-\").lower()\n\n\tif len(files) != 0:\n\t\tfor file in files:\n\t\t\tif file.endswith(\"png\") or file.endswith(\"jpg\"):\n\t\t\t\tpath = os.path.join(root,file)\n\n\t\t\t\tout_path = root[len(BASE_DIR) + 1 ::]\n\t\t\t\timg_path = path[len(BASE_DIR) + 1 ::]\n\n\t\t\t\timgFile = cv2.imread(img_path)\n\n\t\t\t\tnew_root = out_path + \"\\\\\" + label + \"_out\"\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tos.makedirs(new_root + \"_onlyFace\")\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\t\t\ttry:\n\t\t\t\t\tos.makedirs(new_root)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\t\t\tfaces = faces = face_cascade.detectMultiScale(\n\t\t\t\t\t\timgFile,\n\t\t\t\t\t\tscaleFactor=1.1,\n\t\t\t\t\t\tminNeighbors=5,\n\t\t\t\t\t\t)\n\n\t\t\t\tcounter = 0\n\n\t\t\t\tfor (x,y,w,h) in faces:\n\t\t\t\t\tout_faces = out_path + \"\\\\{}_out_onlyFace\\\\\".format(label) + file[0:file.find(\".\")] + \"-\" +str(counter) + file[file.find(\".\"):]\n\t\t\t\t\tprint(\"Created file: {}\".format(out_faces))\n\t\t\t\t\tcv2.imwrite(out_faces,imgFile[y:y+h,x:x+w])\n\n\t\t\t\t\tcv2.rectangle(imgFile, (x, y), (x+w, y+h), (255,0,0), 3)\n\t\t\t\t\tcounter += 1\n\t\t\t\t\t\n\n\t\t\t\tout = out_path + \"\\\\{}_out\\\\\".format(label) + file\n\t\t\t\tprint(\"Created file: {}\".format(out))\n\t\t\t\t\n\t\t\t\tcv2.imwrite(out,imgFile)\n\nprint(\"Process done!\")\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\n" }, { "alpha_fraction": 0.7435470223426819, "alphanum_fraction": 0.7593671679496765, "avg_line_length": 39.03333282470703, "blob_id": "020b91e6f34ac0cec053775f8f0217db46492292", "content_id": "37fdfbb206ba0e9de265367fd2beed080e0303eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1201, "license_type": "permissive", "max_line_length": 273, "num_lines": 30, "path": "/README.md", "repo_name": "amedumer/python-face-recognition", "src_encoding": "UTF-8", "text": "![An example](https://i.ibb.co/zht9YZ6/imgonline-com-ua-twotoone-Wh-CJu03i-Gkpe-Y8-KE.jpg)\n# Face Recognition with Python and openCV2\n Basic face recognition examples with python and openCV 2\n \n ## Required Libraries\n Required libraries are\n```\n os\n numpy\n cv2 (OpenCv2)\n```\n \n ## Examples\n \n### 1 - Find faces by photo\n\nThis program takes a single image file and marks the faces on it. Then shows it to the user.\n####\n\n### 2 - Find faces by webcam\n\nThis program takes live input from user's webcam and marks faces on it.\n\n### 3 - Extract images\n\nThis program takes image/images from the user and marks the faces. Then it saves both the full and the cropped image in a new folder. You can copy multiple folders into the images folder. Just be careful to not copy empty folders. Folder creation is handled by the program.\n\n## Possible Modifications\n- Any user can change the cascade classifier (xml file) and idenify any object they want.\n- User can create his/her own cascade classifier by creating and training a dataset. A great and useful guide to creating a cascade classifier can be found [here](https://medium.com/@toshyraf/train-dataset-to-xml-file-for-cascade-classifier-opencv-43a692b74bfe).\n" } ]
4
smtaha512/python-web-crawler
https://github.com/smtaha512/python-web-crawler
30b8a38626a6e28d68211a2e9df1e3ccb437841f
576a93c34ff21fedd52ff7fde4a0845a1022a80e
6f7c17705c8a218a64ee28fbf2ffaa6e928940c8
refs/heads/master
2021-06-01T05:58:07.975650
2016-06-15T21:50:32
2016-06-15T21:50:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5912194848060608, "alphanum_fraction": 0.6009756326675415, "avg_line_length": 33.20000076293945, "blob_id": "c7c119182d76bfda15266507ea33cd9a603f9239", "content_id": "9d27a07647f6ea88f9695065c66f34fc10c1be33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "no_license", "max_line_length": 100, "num_lines": 30, "path": "/web_crawler.py", "repo_name": "smtaha512/python-web-crawler", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\n\ndef trade_spider(max_pages):\n page = 1\n while page <= max_pages:\n url = 'https://www.olx.com.pk/all-results/q-raspberry-pi/?page=' + str(page)\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text)\n for link in soup.findAll('a', {'class' : 'detailsLink'}):\n href = link.get('href')\n title = link.span\n title = str(title)[6: -7]\n # print(href)\n # print(title)\n get_single_item_data(href)\n page += 1\n\n\ndef get_single_item_data(item_url):\n source_code = requests.get(item_url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text)\n for item_name in soup.findAll('h1', {'class': 'brkword lheight28'}):\n print('Name: ', item_name.string.strip())\n for item_price in soup.findAll('strong', {'class': 'xxxx-large margintop7 block not-arranged'}):\n print(item_price.string)\ntrade_spider(1)" } ]
1
lqy9860/qy_code
https://github.com/lqy9860/qy_code
362df2efc858c0102e3f7ff4dae8118f9a223e10
3a39688a282ce9b38873bc06784e78b5a6a1a47f
9b6f85b569ce1b9c59d630080703d3c959254483
refs/heads/master
2022-12-15T05:36:03.948317
2020-09-12T01:23:07
2020-09-12T01:23:07
294,844,171
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.40699636936187744, "alphanum_fraction": 0.4287092983722687, "avg_line_length": 30.08527183532715, "blob_id": "14346188454e2c8945c515b12cd95a9b66f4f656", "content_id": "b138253f7d832d2845a9cc48cef91890a2c4b5b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9810, "license_type": "no_license", "max_line_length": 67, "num_lines": 258, "path": "/网络双人对战五子棋/gobang2_client/engine.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/30 11:15\r\n# @Author : LQY\r\n\"\"\" engine\"\"\"\r\nimport random\r\nfrom chessman import *\r\nimport re\r\nfrom chessboard import *\r\n\r\nclass Engine():\r\n def __init__(self,chessboard):\r\n self.__chessboard = chessboard\r\n\r\n def computerGo(self,chessman):\r\n '''\r\n 电脑在随机位置下棋\r\n :param chessman: 棋子对象,里面已经设置好棋子颜色\r\n :return:\r\n '''\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n while True:\r\n # 电脑随机下棋\r\n posX = random.randint(1,15)\r\n posY = random.randint(1,15)\r\n # 判断位置是否为空\r\n if self.__chessboard.isEmpty((posX,posY)):\r\n print(f'电脑下棋的位置:({posX},{posY})')\r\n # 1如果下棋位置为空,则把位置写入棋子对象中\r\n chessman.setPos((posX,posY))\r\n # chessman.setColor('O') # 设置电脑下白棋\r\n # 退出循环\r\n break\r\n\r\n # def userGo(self,chessman):\r\n #\r\n # if not isinstance(chessman,ChessMan):\r\n # raise Exception('第一个参数必须为ChessMan对象')\r\n #\r\n # while True:\r\n # pos = input(\"请输入pos:\")\r\n # posX = int(pos[0]) # 转换为整型\r\n # posY = ord(pos[2])-ord('A') + 1 #转换成数字,注意pos[1]是‘,'\r\n # # 判断位置是否为空\r\n # if self.__chessboard.isEmpty((posX,posY)):\r\n # print(f'人下棋的位置:({posX},{posY})')\r\n # # 1如果下棋位置为空,则把位置写入棋子对象中\r\n # chessman.setPos((posX,posY))\r\n # chessman.setColor('X')\r\n # # 退出循环\r\n # break\r\n\r\n def userGo(self,chessman,userinput):\r\n '''\r\n 人下棋\r\n :param chessman: 棋子对象\r\n :param userinput: 用户输入的字符串,如’5,A'\r\n :return:\r\n '''\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n # 采用正则表达式进行匹配,一位数1-9或者两位数:1[0-5],要用括号括起来代表提取\r\n pattern = '^([1-9]|1[0-5]),([a-o])$'\r\n ret = re.findall(pattern,userinput)\r\n # print(ret)\r\n if re: #判断是否匹配成功\r\n posX,posY = ret[0] #ret[0]是一个元组,把值依次传递\r\n posX = int(posX)\r\n posY = ord(posY)-ord('a')+1\r\n # 判断是否为空\r\n if self.__chessboard.isEmpty((posX, posY)):\r\n chessman.setPos((posX, posY))\r\n # chessman.setColor('X')\r\n return True\r\n # 没有匹配到或者位置不空\r\n return False\r\n\r\n def isWon(self,pos,color):\r\n '''\r\n 判断当下某一颗棋子后是否赢棋\r\n :param pos:棋子的位置\r\n :param color:棋子的颜色\r\n :return:True为赢,False胜负未分\r\n '''\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception('第一个参数必须为元组或列表') # 抛出异常\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n\r\n # 上下方向: 范围(pos[0]-4,pos[1])--(pos[0] + 4,pos[1])\r\n start_x = 1\r\n end_x = ChessBoard.BOARD_SIZE\r\n if pos[0] - 4 >= 1:\r\n start_x = pos[0] - 4\r\n if pos[0] + 4 <= 15:\r\n end_x = pos[0] + 4\r\n\r\n count = 0\r\n for posX in range(start_x,end_x+1):\r\n if self.__chessboard.getChess((posX,pos[1])) == color:\r\n count += 1\r\n if count >= 5:\r\n return True\r\n else:\r\n count = 0\r\n\r\n # 左右方向:范围(pos[0],pos[1]-4)--(pos[0],pos[1] + 4)\r\n start_y = 1\r\n end_y = self.__chessboard.BOARD_SIZE\r\n if pos[1] - 4 >= 1:\r\n start_y = pos[1] - 4\r\n if pos[1] + 4 <= 15:\r\n end_y = pos[1] + 4\r\n\r\n count = 0\r\n for posY in range(start_y,end_y+1):\r\n if self.__chessboard.getChess((pos[0],posY)) == color:\r\n count += 1\r\n if count >= 5:\r\n return True\r\n else:\r\n count = 0\r\n\r\n # 左上右下\r\n count = 0\r\n s = pos[0] - pos[1] #计算行列间的差值\r\n start = 0\r\n end = 0\r\n if pos[0] < pos[1]: #行比列小,s是负数,加在列\r\n # 设取点为(5,6),从1开始到14结束,循环14次\r\n start = 1\r\n end = 15 + s\r\n if pos[0] == pos[1]: # 点都在对角线上,需要循环15次\r\n start = 1\r\n end = 15\r\n if pos[0] > pos[1]: # 行比列大,s是正数,加在行\r\n # 设取点(6,5),从2开始,15结束,循环14次\r\n start = 1 + s\r\n end = 15\r\n for i in range(start,end+1):\r\n if self.__chessboard.getChess((i,i-s)) == color:\r\n count += 1\r\n if count >= 5:\r\n return True\r\n else:\r\n count = 0\r\n\r\n # 左下右上\r\n count = 0\r\n s = pos[0] + pos[1]\r\n if s <= 16:\r\n # x+y<=16,设(5,6),循环10次,从1开始,到10,即(s-1)结束\r\n start = start_x\r\n end = s - start_y\r\n for i in range(start, end + 1):\r\n if self.__chessboard.getChess((i,s - i)) == color:\r\n count += 1\r\n if count >= 5:\r\n return True\r\n else:\r\n # 一旦断开 统计数清0\r\n count = 0\r\n if 16 < s <= 26:\r\n # x+y > 16,设(11,10),循环10次,从6,即(s%16+1)开始,15结束,\r\n start = s % 16 + 1\r\n end = 15\r\n for i in range(start, end + 1):\r\n if self.__chessboard.getChess((i,s - i)) == color:\r\n count += 1\r\n if count >= 5:\r\n return True\r\n else:\r\n # 一旦断开 统计数清0\r\n count = 0\r\n\r\n # 四个条件均不满足\r\n return False\r\n\r\n def isWonman(self,chessman):\r\n '''\r\n 判断当下某一颗棋子后是否赢棋\r\n :param chessman: 棋子对象,包括位置颜色\r\n :return: True为赢,False胜负未分\r\n '''\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n pos = chessman.getPos()\r\n color = chessman.getColor()\r\n return self.isWon(pos,color)\r\n\r\n def play(self):\r\n '''游戏主流程'''\r\n userBlack = True # 用户选择黑棋则为True 用户选择白棋则为False 每盘棋改变一次\r\n usergo = True # 轮到用户下则为True 轮到电脑下则为False 每步棋改变一次\r\n\r\n chessmanUser = ChessMan() # 创建棋子对象\r\n chessmanPc = ChessMan()\r\n while True: # 外循环\r\n # 用户选择先后\r\n user_sort = input(\"用户选择先后:(b代表黑棋先下,w代表白棋后下)\")\r\n if user_sort == 'b':\r\n userBlack = True\r\n usergo = True\r\n else:\r\n userBlack = False\r\n usergo = False\r\n\r\n # 初始化棋盘\r\n self.__chessboard.initBoard()\r\n # 方法不能直接Chessboard.initBoard(),因为定义的是实例方法,类只能用自己的类方法\r\n\r\n # 判断是否轮到用户下\r\n while True: # 内循环\r\n # 如果用户选b,则用户先,下黑棋\r\n if userBlack:\r\n chessmanUser.setColor('X')\r\n chessmanPc.setColor('O')\r\n else:\r\n chessmanUser.setColor('O')\r\n chessmanPc.setColor('X')\r\n\r\n if usergo: # 代表用户下\r\n userinput = input(\"请用户输入下棋坐标:\")\r\n user_ret = self.userGo(chessmanUser, userinput)\r\n if user_ret:\r\n # 返回真才把棋子传进chessman,并放置在棋盘上\r\n self.__chessboard.setChessMan(chessmanUser)\r\n else: # 轮到电脑下\r\n self.computerGo(chessmanPc)\r\n self.__chessboard.setChessMan(chessmanPc)\r\n self.__chessboard.printBoard()\r\n\r\n # 判断输赢\r\n if usergo:\r\n user_iswon = self.isWonman(chessmanUser)\r\n if user_iswon: # 如果赢了判断是否继续游戏\r\n print(\"你赢了\")\r\n break # 如果赢棋就跳出内循环\r\n else:\r\n com_iswon = self.isWonman(chessmanPc)\r\n if com_iswon:\r\n print(\"你输了\")\r\n break # 如果赢棋就跳出内循环\r\n\r\n usergo = not usergo\r\n\r\n # 判断是否继续游戏\r\n user_contin = input(\"是否继续游戏:(是为y,否为n):\")\r\n if user_contin == 'n':\r\n print(\"结束游戏\")\r\n break # 结束游戏则跳出外循环\r\n else:\r\n print(\"继续游戏\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5141242742538452, "alphanum_fraction": 0.5310734510421753, "avg_line_length": 30.842857360839844, "blob_id": "247b3d8b2f7fdb4267d1eefbec329dae29e0ba71", "content_id": "b1ffe637dc92858e6c4fc415138449289ba58eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2503, "license_type": "no_license", "max_line_length": 68, "num_lines": 70, "path": "/网络双人对战五子棋/Gobang_tcp/chessboard.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "from chessman import ChessMan\r\n\r\n\r\nclass ChessBoard(object):\r\n BOAED_SIZE=15\r\n\r\n def __init__(self):\r\n # 初始化\r\n self.__board=[[0 for i in range(ChessBoard.BOAED_SIZE+1)]\r\n for i in range(ChessBoard.BOAED_SIZE+1)]\r\n\r\n # 清空棋盘\r\n def initBoard(self):\r\n # 忽略第一行\r\n for i in range(1,ChessBoard.BOAED_SIZE+1):\r\n for j in range(1,ChessBoard.BOAED_SIZE+1):\r\n self.__board[i][j]='+'\r\n\r\n # 打印棋盘\r\n def printBoard(self):\r\n # 打印行号\r\n print(' ',end='')\r\n for i in range(1, ChessBoard.BOAED_SIZE + 1):\r\n print(chr(i+ord('a')-1),end='')\r\n print()\r\n\r\n for i in range(1, ChessBoard.BOAED_SIZE + 1):\r\n # 打印列号\r\n print('%2d'%i,end='')\r\n for j in range(1, ChessBoard.BOAED_SIZE + 1):\r\n print(self.__board[i][j],end='')\r\n print()\r\n\r\n\r\n def setChess(self,pos,color):\r\n # 放置棋子\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception(\"第一个参数被选为元组或列表\")\r\n if pos[0] <= 0 or pos[0]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n self.__board[pos[0]][pos[1]]=color\r\n\r\n\r\n def setChessMan(self,chessman):\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n pos=chessman.Pos\r\n color=chessman.Color\r\n self.setChess(pos,color)\r\n\r\n def getChess(self,pos):\r\n if not isinstance(pos, tuple) and not isinstance(pos, list):\r\n raise Exception(\"第一个参数被选为元组或列表\")\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n return self.__board[pos[0]][pos[1]]\r\n\r\n def isEmpty(self,pos):\r\n if not isinstance(pos, tuple) and not isinstance(pos, list):\r\n raise Exception(\"第一个参数被选为元组或列表\")\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n return self.getChess(pos)=='+'\r\n\r\n" }, { "alpha_fraction": 0.5749068856239319, "alphanum_fraction": 0.5835004448890686, "avg_line_length": 19.69565200805664, "blob_id": "f367d98ee5953317b15a25d02febf3d8ef751e3b", "content_id": "ad7d9f00a67a517d29695323ba96fc2dc2980098", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4087, "license_type": "no_license", "max_line_length": 48, "num_lines": 161, "path": "/网络双人对战五子棋/Gobang_tcp/main.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "from chessboard import ChessBoard\r\nfrom chessman import ChessMan\r\nfrom engine import Engine\r\nfrom usergothread import UserGoThread\r\nfrom computergothread import ComputerGoThread\r\n\r\ndef test1():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n chessboard.printBoard()\r\n\r\ndef test2():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 在3,5位置放置x\r\n chessboard.setChess((3,5),'x')\r\n\r\n # 用棋子类在4,7放置o\r\n # 初始化棋子类\r\n chessman=ChessMan()\r\n chessman.Pos=(4,7)\r\n chessman.Color='o'\r\n # 放置\r\n chessboard.setChessMan(chessman)\r\n\r\n chessboard.printBoard()\r\n # 测试获取指定棋子位置\r\n ret=chessboard.getChess((4,11))\r\n print(ret)\r\n # 测试是否为空\r\n ret= chessboard.isEmpty((1,1))\r\n print(ret)\r\n\r\ndef test3():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化棋子类\r\n chessman=ChessMan()\r\n chessman.Color='o'\r\n\r\n # 初始化引擎类\r\n engine=Engine(chessboard)\r\n # 获取电脑随机下棋位置\r\n engine.computerGo(chessman)\r\n # 放置电脑下棋位置\r\n chessboard.setChessMan(chessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\n\r\ndef test4():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化棋子类\r\n chessman=ChessMan()\r\n chessman.Color='o'\r\n\r\n # 初始化引擎类\r\n engine=Engine(chessboard)\r\n # 获取用户下棋位置\r\n userInput=input(\"请输入用户下棋位置:\")\r\n\r\n engine.userGo(chessman,userInput)\r\n # 放置用户下棋位置\r\n chessboard.setChessMan(chessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\n\r\ndef test5():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化棋子类\r\n chessman=ChessMan()\r\n chessman.Color='o'\r\n\r\n # 初始化引擎类\r\n engine=Engine(chessboard)\r\n\r\n while 1:\r\n # 获取用户下棋位置\r\n userInput=input(\"请输入用户下棋位置:\")\r\n\r\n engine.userGo(chessman,userInput)\r\n # 放置用户下棋位置\r\n chessboard.setChessMan(chessman)\r\n # 打印棋盘\r\n RET=engine.isWonMan(chessman)\r\n chessboard.printBoard()\r\n\r\n if RET:\r\n print('win')\r\n break\r\n\r\n\r\ndef main():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化引擎类\r\n engine = Engine(chessboard)\r\n engine.play()\r\n\r\n\r\ndef mainThread():\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化引擎类\r\n engine = Engine(chessboard)\r\n userchessman = ChessMan()\r\n userchessman.Color='x'\r\n computerchessman = ChessMan()\r\n computerchessman.Color = 'o'\r\n # 创建线程和开启线程\r\n tU=UserGoThread(userchessman,engine)\r\n tC=ComputerGoThread(computerchessman,engine)\r\n # z设置守护线程,主线程退出,子线程自动退出\r\n tU.setDaemon(True)\r\n tC.setDaemon(True)\r\n tU.start()\r\n tC.start()\r\n while 1:\r\n\r\n #1.用户wait\r\n userchessman.WAIT()\r\n #2.用户下子\r\n # 放置用户下棋位置\r\n chessboard.setChessMan(userchessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n # 判断用户是否赢\r\n if engine.isWonMan(userchessman):\r\n print(\"u win\")\r\n break\r\n #3.电脑notify\r\n computerchessman.NOTIFY()\r\n # 电脑子线程自动完成\r\n #4.1电脑wait\r\n computerchessman.WAIT()\r\n #5.1电脑下子\r\n # 放置电脑下棋位置\r\n chessboard.setChessMan(computerchessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n # 判断电脑是否赢\r\n if engine.isWonMan(computerchessman):\r\n print(\"c win\")\r\n break\r\n #6.1用户notify\r\n userchessman.NOTIFY()\r\n # 用户子线程自动完成\r\n\r\nif __name__ == '__main__':\r\n # mainThread()\r\n test5()" }, { "alpha_fraction": 0.4919431209564209, "alphanum_fraction": 0.4938388764858246, "avg_line_length": 17.07272720336914, "blob_id": "bf16a989977f155a7874ad195e34470b72bc88fc", "content_id": "5777a1cfba20e1c07157071aff107b16814b86e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1157, "license_type": "no_license", "max_line_length": 38, "num_lines": 55, "path": "/网络双人对战五子棋/Gobang_tcp/chessman.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import threading\r\n\r\nclass ChessMan(object):\r\n # 棋子类\r\n def __init__(self):\r\n self.__pos=[0,0]\r\n self.__color='+'\r\n self.con=threading.Condition()\r\n\r\n def NOTIFY(self):\r\n # 对notify进行封装\r\n self.con.acquire()\r\n self.con.notify()\r\n self.con.release()\r\n\r\n def WAIT(self):\r\n # 对wait进行封装\r\n self.con.acquire()\r\n self.con.wait()\r\n self.con.release()\r\n\r\n\r\n def setPos(self,pos):\r\n # 设置棋子位置\r\n self.__pos=pos\r\n\r\n def getPos(self):\r\n # 获取棋子位置\r\n return self.__pos\r\n\r\n def setColor(self, color):\r\n # 设置棋子颜色\r\n self.__color = color\r\n\r\n def getColor(self):\r\n # 获取棋子颜色\r\n return self.__color\r\n\r\n # 装饰器,先return再setter\r\n @property\r\n def Pos(self):\r\n return self.__pos\r\n\r\n # 根据前面的方法命名\r\n @Pos.setter\r\n def Pos(self,pos):\r\n self.__pos=pos\r\n\r\n @property\r\n def Color(self):\r\n return self.__color\r\n\r\n @Color.setter\r\n def Color(self,color):\r\n self.__color=color\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.733905553817749, "alphanum_fraction": 0.7811158895492554, "avg_line_length": 15.923076629638672, "blob_id": "ee4604e97bb6a7afa71da8a57bc5e5d290952e32", "content_id": "313dc136763f7a7dac28d6ecef4a7812402f518c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 625, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/README.txt", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "网络双人对战五子棋主要功能:\r\n1、可以实现网络对战\r\n2、(客户端)可以选择先后手\r\n3、棋盘同步\r\n4、判断输赢\r\n5、可以选择是否继续下一场游戏\r\n设计方案:\r\n1、视图控制模块:负责棋盘的显示和棋子的摆放\r\n2、游戏规则模块:负责判断游戏胜负\r\n3、网络通信模块:负责网络连接和传输对方棋子位置\r\n4、客户端模块:连接服务端,开始游戏,客户端输入\r\n5、服务端模块:监听客户端,服务端输入(此处承担另一方客户端的功能)和游戏流程的推进\r\n6、线程控制模块\r\n" }, { "alpha_fraction": 0.4555084705352783, "alphanum_fraction": 0.4729872941970825, "avg_line_length": 31.122806549072266, "blob_id": "bff7dd832cd6f65ef4344babc6f5c8d512d8efd2", "content_id": "91ac496c0d4ead2db397be74f557f113ed2885e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1982, "license_type": "no_license", "max_line_length": 82, "num_lines": 57, "path": "/网络双人对战五子棋/Gobang_tcp/computergothread.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import threading\r\nimport re\r\n\r\nclass ComputerGoThread(threading.Thread):\r\n def __init__(self, chessman, engine,client_socker):\r\n super().__init__()\r\n self.chessman = chessman\r\n self.engine = engine\r\n self.client_socker=client_socker\r\n self.con = threading.Condition()\r\n\r\n def run(self):\r\n while 1:\r\n # 1.wait\r\n self.chessman.WAIT()\r\n # 2.电脑下棋\r\n self.engine.computerGo(self.chessman)\r\n # 发送棋子位置\r\n msg = str(self.chessman.Pos[0]) + str(',') + str(self.chessman.Pos[1])\r\n self.client_socker.send(msg.encode('gbk'))\r\n # 3.notify\r\n self.chessman.NOTIFY()\r\n\r\n\r\n\r\n\r\nclass RECV_ComputerGoThread(threading.Thread):\r\n def __init__(self,chessman,engine,client_socker):\r\n super().__init__()\r\n self.chessman=chessman\r\n self.engine=engine\r\n self.client_socker=client_socker\r\n self.con=threading.Condition()\r\n\r\n def run(self):\r\n while 1:\r\n # 1.wait\r\n self.chessman.WAIT()\r\n # 2.接收电脑下棋\r\n recv_data = self.client_socker.recv(1024).decode('gbk')\r\n if len(recv_data) != 0 and recv_data != None:\r\n # 正则表达式判断输入的格式 (1-15,a-o或1-15)\r\n pattern = '^([1-9]|1[0-5]),([a-o]|[1-9]|1[0-5])$'\r\n ret = re.findall(pattern, recv_data)\r\n print(ret)\r\n if len(ret):\r\n posX, posY = ret[0]\r\n posX = int(posX)\r\n # 如果第二个参数是字母,进行转数字的处理\r\n if posY.isalpha():\r\n posY = ord(posY) - ord('a') + 1\r\n else:\r\n posY = int(posY)\r\n # print(posX,posY)\r\n self.chessman.Pos = (posX, posY)\r\n # 3.notify\r\n self.chessman.NOTIFY()\r\n" }, { "alpha_fraction": 0.46353837847709656, "alphanum_fraction": 0.48509830236434937, "avg_line_length": 30.102041244506836, "blob_id": "7d5ef9953fddee8d6aaa6834ffc243b77a90dcab", "content_id": "12c8e4144bc49a576d03f63e0cf6ec5686836da2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1719, "license_type": "no_license", "max_line_length": 87, "num_lines": 49, "path": "/网络双人对战五子棋/gobang2_client/clientRecv.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/8/1 12:58\r\n# @Author : LQY\r\n\"\"\" clientserverRecv\"\"\"\r\nimport threading\r\nfrom chessman import *\r\nfrom engine import *\r\nfrom chessboard import *\r\nimport re\r\n\r\nclass ClientRecvThread(threading.Thread):\r\n def __init__(self,chessboard,chesswhite,engine,client_socket): # 服务端收发要用客户端的socket\r\n '''初始化'''\r\n super().__init__()\r\n self.chessboard = chessboard\r\n self.chesswhite = chesswhite\r\n self.engine = engine\r\n self.client_socket = client_socket\r\n\r\n def run(self):\r\n # 等待主线程唤醒\r\n self.chesswhite.doWait()\r\n\r\n while True:\r\n # 接收服务端发来的坐标信息\r\n recv_pos = self.client_socket.recv(1024).decode('gbk')\r\n pattern = '^([1-9]|1[0-5]),([a-o]|[A-O]|[1-9]|1[0-5])$'\r\n ret = re.findall(pattern, recv_pos)\r\n if len(ret):\r\n posX, posY = ret[0]\r\n posX = int(posX)\r\n # 如果第二个参数是字母,进行转数字的处理\r\n if posY.isalpha() and ord(posY) >= 97:\r\n posY = ord(posY) - ord('a') + 1\r\n elif posY.isalpha() and ord(posY) >= 65:\r\n posY = ord(posY) - ord('A') + 1\r\n else:\r\n posY = int(posY)\r\n\r\n # 判断是否为空\r\n if self.chessboard.isEmpty((posX, posY)):\r\n self.chesswhite.setPos((posX, posY))\r\n print(\"对方发过来的坐标是:\", ret)\r\n\r\n # 3 电脑notify\r\n self.chesswhite.doNotify()\r\n\r\n # 1 电脑wait\r\n self.chesswhite.doWait()\r\n\r\n\r\n" }, { "alpha_fraction": 0.45299145579338074, "alphanum_fraction": 0.470085471868515, "avg_line_length": 18.024391174316406, "blob_id": "e84745c187fc025fa78f32dba18886b20f9b7b17", "content_id": "9a530e38d272d1ef7340a266473599bdbaeaf2a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 40, "num_lines": 41, "path": "/网络双人对战五子棋/gobang2_client/chessman.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/30 10:25\r\n# @Author : LQY\r\n\"\"\" chessname\"\"\"\r\n\r\nimport threading\r\n\r\nclass ChessMan(object):\r\n '''\r\n 棋子类\r\n '''\r\n def __init__(self):\r\n self.__pos = [0,0]\r\n self.__color = '+'\r\n self.con = threading.Condition()\r\n\r\n def setPos(self,pos):\r\n '''指定棋子位置'''\r\n self.__pos = pos\r\n\r\n def getPos(self):\r\n '''返回棋子的位置'''\r\n return self.__pos\r\n\r\n def setColor(self,color):\r\n '''指定棋子的颜色'''\r\n self.__color = color\r\n\r\n def getColor(self):\r\n '''返回棋子的位置'''\r\n return self.__color\r\n\r\n def doWait(self):\r\n self.con.acquire()\r\n self.con.wait()\r\n self.con.release()\r\n\r\n def doNotify(self):\r\n self.con.acquire()\r\n self.con.notify()\r\n self.con.release()" }, { "alpha_fraction": 0.45624467730522156, "alphanum_fraction": 0.4995751976966858, "avg_line_length": 26.33734893798828, "blob_id": "c229c020c9f95ce08cbc76d27ab789ebaffd730a", "content_id": "e35637693cc54b38f1a8b70fd1deb715de1a5b01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2770, "license_type": "no_license", "max_line_length": 105, "num_lines": 83, "path": "/网络双人对战五子棋/Gobang_tcp/test.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import pygame\r\nimport time\r\ndef isWon():\r\n bcolor=[(250, 198, 115, 255),(250, 199, 108, 255),(249, 201, 101, 255)]\r\n wcolor = [(195, 164, 142, 255), ]\r\nif __name__ == '__main__':\r\n\r\n # 初始化\r\n pygame.init()\r\n\r\n #创建窗口(必须)\r\n # set_mode会返回一个Surface对象,代表了在桌面上出现的那个窗口,三个参数第一个为元祖,代表分 辨率(必须);第二个是一个标志位,具体意思见下表,如果不用什么特性,就指定0;第三个为色深。\r\n # RESIZABLE\t创建一个可以改变大小的窗口\r\n screen=pygame.display.set_mode((500,481),pygame.RESIZABLE,32)\r\n # 每格大小33x32\r\n\r\n #获取背景图片\r\n background_img=pygame.image.load(r'H:\\pei_xun_python\\wenjiang\\0730\\wzq\\img\\board.jpg')\r\n\r\n # 设置时钟\r\n clock = pygame.time.Clock()\r\n # 棋子颜色切换\r\n chess_state=True\r\n i=0\r\n # 棋子图片字典\r\n w={}\r\n b={}\r\n # 棋子位置存储\r\n setwX=[]\r\n setwY=[]\r\n setbX=[]\r\n setbY=[]\r\n while True:\r\n # 监听事件\r\n for event in pygame.event.get():\r\n # 设置退出事件\r\n if event.type== pygame.QUIT:\r\n exit()\r\n\r\n # 设置背景图片位置\r\n screen.blit(background_img, (0, 0))\r\n w [i]= pygame.image.load(r'H:\\pei_xun_python\\wenjiang\\0730\\wzq\\img\\w_chess.png')\r\n b [i]=pygame.image.load(r'H:\\pei_xun_python\\wenjiang\\0730\\wzq\\img\\b_chess.png')\r\n x,y=pygame.mouse.get_pos()\r\n # 如果chess_state为True,白棋,否则黑棋\r\n if chess_state:\r\n screen.blit(w[0],(x-16.5,y-16))\r\n else:\r\n screen.blit(b[0], (x-16.5,y-16))\r\n # 获取键盘事件\r\n key = pygame.key.get_pressed()\r\n # 按下Enter键放置棋子\r\n if key[pygame.K_RETURN or pygame.K_SPACE]:\r\n x-=x%33 -5\r\n y-=y%32\r\n # 如果为True,白棋位置增加,否则黑棋位置增加\r\n if chess_state:\r\n setwX.append(x)\r\n setwY.append(y)\r\n print(setwX[len(setwX) - 1], setwY[len(setwX) - 1], i)\r\n else:\r\n setbX.append(x)\r\n setbY.append(y)\r\n print(setwX[len(setbX) - 1], setwY[len(setbX) - 1], i)\r\n chess_state=not chess_state\r\n col = screen.get_at((x, y))\r\n print(col)\r\n i+=1\r\n time.sleep(0.5)\r\n\r\n\r\n\r\n for j in range(len(setwX)):\r\n screen.blit(w[j],(setwX[j],setwY[j]))\r\n\r\n for j in range(len(setbX)):\r\n screen.blit(b[j],(setbX[j],setbY[j]))\r\n\r\n\r\n #刷新画面\r\n pygame.display.flip()\r\n # 设置刷新频率,每秒刷新n次\r\n clock.tick(10)\r\n\r\n" }, { "alpha_fraction": 0.4107883870601654, "alphanum_fraction": 0.4247453808784485, "avg_line_length": 31.987178802490234, "blob_id": "09ae4ab08fa9d7b20ec06a3f6e84b46831ff1f61", "content_id": "e3e29c3aad9796f166e7a2a4788fddc059c17a93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2885, "license_type": "no_license", "max_line_length": 75, "num_lines": 78, "path": "/网络双人对战五子棋/Gobang_tcp/usergothread.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import threading\r\nimport time\r\nimport re\r\n\r\nclass RECV_UserGoThread(threading.Thread):\r\n def __init__(self,chessman,engine,client_socker):\r\n super().__init__()\r\n self.chessman=chessman\r\n self.engine=engine\r\n self.client_socker=client_socker\r\n self.con=threading.Condition()\r\n\r\n\r\n def run(self):\r\n # 先等待,解决先后手问题\r\n self.chessman.WAIT()\r\n try:\r\n while 1:\r\n # 1.用户下棋\r\n print('轮到对方下棋')\r\n # 获取用户下棋位置\r\n recv_data = self.client_socker.recv(1024).decode('gbk')\r\n print('对方下棋位置:',recv_data)\r\n if len(recv_data) != 0 and recv_data != None:\r\n # 正则表达式判断输入的格式 (1-15,a-o或1-15)\r\n pattern = '^([1-9]|1[0-5]),([a-o]|[A-O]|[1-9]|1[0-5])$'\r\n ret = re.findall(pattern, recv_data)\r\n # print(ret)\r\n if len(ret):\r\n posX, posY = ret[0]\r\n posX = int(posX)\r\n # 如果第二个参数是字母,进行转数字的处理\r\n if posY.isalpha() and ord(posY)>=97 :\r\n posY = ord(posY) - ord('a') + 1\r\n elif posY.isalpha() and ord(posY)>=65:\r\n posY = ord(posY) - ord('A') + 1\r\n else:\r\n posY = int(posY)\r\n self.chessman.Pos = (posX, posY)\r\n # 2.notify\r\n self.chessman.NOTIFY()\r\n # 3.wait\r\n self.chessman.WAIT()\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nclass UserGoThread(threading.Thread):\r\n def __init__(self,chessman,engine,client_socker):\r\n super().__init__()\r\n self.chessman=chessman\r\n self.engine=engine\r\n self.client_socker=client_socker\r\n self.con=threading.Condition()\r\n\r\n\r\n def run(self):\r\n # 先等待,解决先后手问题\r\n self.chessman.WAIT()\r\n try:\r\n while 1:\r\n # time.sleep(1)\r\n print('轮到我方下棋')\r\n # 1.用户下棋\r\n # 获取用户下棋位置\r\n userInput = input(\"请输入下棋位置:\")\r\n ret=self.engine.userGo(self.chessman, userInput)\r\n if ret:\r\n # 发送棋子坐标\r\n self.client_socker.send(userInput.encode('gbk'))\r\n # 2.notify\r\n self.chessman.NOTIFY()\r\n # 3.wait\r\n self.chessman.WAIT()\r\n else:\r\n print('输入格式错误或棋子重复')\r\n except Exception as e:\r\n print(e)\r\n" }, { "alpha_fraction": 0.4137931168079376, "alphanum_fraction": 0.42241379618644714, "avg_line_length": 32.68041229248047, "blob_id": "88a35574c2480e0b7b26b18b3af7597522443dcc", "content_id": "d0f52e9f149df762456164783cc11c03b400077e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3796, "license_type": "no_license", "max_line_length": 81, "num_lines": 97, "path": "/网络双人对战五子棋/Gobang_tcp/main_tcpserver.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import socket\r\nimport threading\r\nfrom chessboard import ChessBoard\r\nfrom chessman import ChessMan\r\nfrom engine import Engine\r\nfrom usergothread import RECV_UserGoThread,UserGoThread\r\n\r\n\r\nif __name__ == '__main__':\r\n # tcp套接字\r\n server_socker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n # 绑定端口\r\n addr = ('', 8000)\r\n server_socker.bind(addr)\r\n\r\n # 开启监听\r\n server_socker.listen()\r\n print('开始准备,等待连接')\r\n # 接收客户端连接\r\n client_socker, client_info = server_socker.accept()\r\n print(\"客户端%s准备完毕\" % client_info[0])\r\n try:\r\n while 1:\r\n # 初始化棋盘\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n # 初始化引擎类\r\n engine = Engine(chessboard)\r\n # 初始化两个棋子类\r\n Firstchessman = ChessMan()\r\n Latterchessman = ChessMan()\r\n\r\n # 客户端选择先手或后手\r\n # '先手1,后手其他:'\r\n print('对方(用户)选择先后手:', end='')\r\n order = client_socker.recv(1024).decode()\r\n Firstchessman.Color = 'o'\r\n Latterchessman.Color = 'x'\r\n if order == '1':\r\n # 对方先手,开启用户接收线程\r\n print('对方先手')\r\n tU = RECV_UserGoThread(Firstchessman, engine, client_socker)\r\n tC = UserGoThread(Latterchessman, engine, client_socker)\r\n else:\r\n print('我方先手')\r\n tU = UserGoThread(Firstchessman, engine, client_socker)\r\n tC = RECV_UserGoThread(Latterchessman, engine, client_socker)\r\n\r\n # 设置守护线程,主线程退出,子线程自动退出\r\n tU.setDaemon(True)\r\n tC.setDaemon(True)\r\n tU.start()\r\n tC.start()\r\n # 先手notify一下\r\n Firstchessman.NOTIFY()\r\n\r\n while 1:\r\n # 1.先手等待\r\n Firstchessman.WAIT()\r\n # 2.先手下子\r\n # 放置先手下棋位置\r\n chessboard.setChessMan(Firstchessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n # 判断先手是否赢\r\n if engine.isWonMan(Firstchessman):\r\n print(\"先手 win\")\r\n break\r\n # 3.后手notify\r\n Latterchessman.NOTIFY()\r\n # 后手子线程自动完成\r\n # 4.1电脑wait\r\n Latterchessman.WAIT()\r\n # 5.1后手下子\r\n # 放置对方下棋位置\r\n chessboard.setChessMan(Latterchessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n # 判断后手是否赢\r\n if engine.isWonMan(Latterchessman):\r\n print(\"后手 win\")\r\n break\r\n # 6.1先手notify\r\n Firstchessman.NOTIFY()\r\n # 用户子线程自动完成\r\n\r\n print(\"是否继续,继续选1(对方选择)\")\r\n cont = client_socker.recv(1024).decode()\r\n if not (cont == '1'):\r\n print('退出')\r\n break\r\n else:\r\n print('继续')\r\n except Exception as e:\r\n print(e)\r\n # print(client_info[0], \"断开连接\")\r\n" }, { "alpha_fraction": 0.5263465046882629, "alphanum_fraction": 0.5403590798377991, "avg_line_length": 23.095237731933594, "blob_id": "b446420cdd0b95b04fbc270d32e73ffc652661b2", "content_id": "ce0bf5d23928740f2b34e1e6e3e4b67b5e5589d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8097, "license_type": "no_license", "max_line_length": 130, "num_lines": 273, "path": "/网络双人对战五子棋/gobang2_client/main.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/30 9:27\r\n# @Author : LQY\r\n\"\"\" main\"\"\"\r\nfrom chessboard import *\r\nfrom chessman import *\r\nfrom engine import *\r\nimport threading\r\nimport time\r\nimport random\r\n\r\ndef test1():\r\n chessboard = ChessBoard()\r\n chessboard.initBoard()\r\n chessboard.printBoard()\r\n\r\ndef test2():\r\n chessboard = ChessBoard() # 创建棋盘类对象\r\n chessman = ChessMan() # 创建棋子类对象\r\n\r\n # 清空棋盘\r\n chessboard.initBoard()\r\n # 在(3,5)位置上放一颗黑棋\r\n chessboard.setChess((3,5),'X')\r\n\r\n # 在(4,7)位置放一颗白棋\r\n chessman.setPos((4,7))\r\n chessman.setColor('O')\r\n chessboard.setChessMan(chessman)\r\n chessboard.printBoard()\r\n\r\n # 测试读取棋子\r\n ret = chessboard.getChess((4,5))\r\n print(ret)\r\n\r\n # 测试是否为空\r\n ret = chessboard.isempty((4,14))\r\n if ret:\r\n print('empty')\r\n else:\r\n print('not empty')\r\n\r\ndef test3():\r\n '''测试电脑下棋'''\r\n chessboard = ChessBoard() # 创建棋盘类对象\r\n chessman = ChessMan() # 创建棋子类对象\r\n engine = Engine(chessboard) #创建引擎对象,并把棋盘传进去\r\n\r\n # 清空棋盘\r\n chessboard.initBoard()\r\n\r\n # 电脑下棋\r\n engine.computerGo(chessman) # 已将电脑的下棋位置传入chessman中\r\n chessboard.setChessMan(chessman) # 棋盘把棋子放进对应位置\r\n\r\n # 人下棋\r\n while True:\r\n userinput = input(\"请输入下棋坐标:\")\r\n ret = engine.userGo(chessman, userinput)\r\n if ret:\r\n # 返回真才把棋子传进chessman\r\n chessboard.setChessMan(chessman)\r\n # 打印棋盘\r\n # chessboard.printBoard()\r\n break\r\n\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\ndef test4():\r\n '''测试人下棋'''\r\n chessboard = ChessBoard() # 创建棋盘类对象\r\n chessman = ChessMan() # 创建棋子类对象\r\n engine = Engine(chessboard) # 创建引擎对象,并把棋盘传进去\r\n\r\n # 清空棋盘\r\n chessboard.initBoard()\r\n\r\n # 人下棋\r\n userinput = input(\"请输入下棋坐标:\")\r\n ret = engine.userGo(chessman,userinput)\r\n if ret:\r\n # 返回真才把棋子传进chessman\r\n chessboard.setChessMan(chessman)\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\ndef test5():\r\n '''测试上下方向'''\r\n chessboard = ChessBoard() # 创建棋盘类对象\r\n chessman = ChessMan() # 创建棋子类对象\r\n engine = Engine(chessboard)\r\n\r\n # 清空棋盘\r\n chessboard.initBoard()\r\n\r\n chessboard.setChess((3, 5), 'X')\r\n chessboard.setChess((4, 5), 'X')\r\n chessboard.setChess((5, 5), 'X')\r\n chessboard.setChess((6, 5), 'X')\r\n chessboard.setChess((7, 5), 'X')\r\n # chessboard.setChess((8, 5), 'X')\r\n #\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\n # 判断输赢\r\n ret = engine.isWon((3,5),'X')\r\n if ret:\r\n print(\"胜负已分\")\r\n else:\r\n print(\"胜负未分\")\r\n\r\ndef test6():\r\n '''测试左右方向'''\r\n chessboard = ChessBoard() # 创建棋盘类对象\r\n chessman = ChessMan() # 创建棋子类对象\r\n engine = Engine(chessboard)\r\n\r\n # 清空棋盘\r\n chessboard.initBoard()\r\n\r\n chessboard.setChess((1, 1), 'X')\r\n chessboard.setChess((1, 2), 'X')\r\n # chessboard.setChess((1, 3), 'X')\r\n chessboard.setChess((1, 4), 'X')\r\n chessboard.setChess((1, 5), 'X')\r\n # chessboard.setChess((8, 5), 'X')\r\n #\r\n # 打印棋盘\r\n chessboard.printBoard()\r\n\r\n # 判断输赢\r\n ret = engine.isWon((1, 5), 'X')\r\n if ret:\r\n print(\"胜负已分\")\r\n else:\r\n print(\"胜负未分\")\r\n\r\n# def main():\r\n# chessboard = ChessBoard()\r\n# engine = Engine(chessboard)\r\n# engine.play()\r\n\r\nfrom usergothread import *\r\nfrom computergothread import *\r\nimport socket\r\nfrom clientRecv import *\r\n\r\ndef mainThread():\r\n\r\n # 创建客户端套接字\r\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n # 创建服务端套接字\r\n # server_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n # computergothread = ComputerGoThread(chessboard,chessmanPC,engine,client_socket)\r\n\r\n # 连接服务端\r\n address = ('192.168.55.29', 8000) # 对手的ip地址和端口号\r\n client_socket.connect(address)\r\n\r\n while True:\r\n # 创建棋盘对象和引擎对象\r\n chessboard = ChessBoard()\r\n engine = Engine(chessboard)\r\n\r\n # 初始化和打印棋盘\r\n chessboard.initBoard()\r\n chessboard.printBoard()\r\n\r\n # 创建两个棋子对象\r\n chessblack = ChessMan()\r\n chesswhite = ChessMan()\r\n\r\n chessblack.setColor('X') # 先手为黑棋\r\n chesswhite.setColor('O') # 后手为白棋\r\n\r\n # 判断先后\r\n user_sort = input(\"请输入先后手:先为1\")\r\n # 把先后信息发给对方\r\n msg = user_sort.encode('gbk')\r\n client_socket.send(msg)\r\n\r\n if user_sort == '1':\r\n # 若选1,则自己下黑棋\r\n # 把黑棋对象传给下棋进程,白棋对象传给接收线程\r\n # 创建用户下棋线程和接收线程\r\n print(\"我方先手\")\r\n # 创建客户端下棋线程,传入chessblack唤醒UserGoThread\r\n usergothread = UserGoThread(chessblack, engine, client_socket)\r\n # 创建客户接收线程\r\n clientrecvthread = ClientRecvThread(chessboard, chesswhite, engine, client_socket)\r\n\r\n else:\r\n # 若选0,则自己下白棋\r\n # 把白棋对象传给下棋线程,黑棋对象传给接收线程\r\n print(\"对方先手\")\r\n usergothread = UserGoThread(chesswhite, engine, client_socket)\r\n clientrecvthread = ClientRecvThread(chessboard, chessblack, engine, client_socket) # 传入chessmanUser唤醒ClientRecvThread\r\n\r\n # 设置线程为守护线程,当主线程退出时子线程也随之退出\r\n usergothread.setDaemon(True)\r\n # computergothread.setDaemon(True)\r\n clientrecvthread.setDaemon(True)\r\n\r\n # 开始线程\r\n usergothread.start()\r\n # computergothread.start()\r\n clientrecvthread.start()\r\n\r\n # 先手(黑棋)notify\r\n # 若选1,唤醒usergothread中的wait\r\n # 若选0,唤醒clientrecvthread中的wait\r\n chessblack.doNotify()\r\n\r\n while True:\r\n # 1 用户wait\r\n chessblack.doWait()\r\n\r\n # 3 在棋盘上摆放用户下的棋子\r\n chessboard.setChessMan(chessblack)\r\n chessboard.printBoard()\r\n\r\n # 判断输赢\r\n if user_sort == '1':\r\n if engine.isWonman(chessblack):\r\n print(\"恭喜赢了\")\r\n break\r\n if user_sort == '0':\r\n if engine.isWonman(chessblack):\r\n print(\"输了\")\r\n break\r\n\r\n # 2 对方notify,唤醒客户端接收线程,接收对方的棋子\r\n chesswhite.doNotify()\r\n\r\n # 4 电脑wait\r\n chesswhite.doWait()\r\n\r\n # 5 在棋盘上摆放对方下的棋子\r\n chessboard.setChessMan(chesswhite)\r\n chessboard.printBoard()\r\n\r\n if user_sort == '1':\r\n if engine.isWonman(chesswhite):\r\n print(\"输了\")\r\n break\r\n if user_sort == '0':\r\n if engine.isWonman(chesswhite):\r\n print(\"恭喜赢了\")\r\n break\r\n\r\n # 6 用户notify\r\n chessblack.doNotify()\r\n\r\n # 是否继续游戏\r\n userinput = input(\"是否继续游戏:是为1,否为0\")\r\n # 把是否继续信息发给对方\r\n msg = userinput.encode('gbk')\r\n client_socket.send(msg)\r\n if userinput == '0':\r\n break\r\n\r\n\r\nif __name__=='__main__':\r\n # test2()\r\n # test3()\r\n # test4()\r\n # test5()\r\n # test6()\r\n # main()\r\n mainThread()\r\n" }, { "alpha_fraction": 0.47976309061050415, "alphanum_fraction": 0.4981901943683624, "avg_line_length": 27.52427101135254, "blob_id": "3af929551febb8855485359e1b5812a694d4f753", "content_id": "2985744a2455112e350b7fa8c25c6f31ab2e6184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3565, "license_type": "no_license", "max_line_length": 67, "num_lines": 103, "path": "/网络双人对战五子棋/gobang2_client/chessboard.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/30 9:21\r\n# @Author : LQY\r\n\"\"\" chessboard\"\"\"\r\n\r\nfrom chessman import *\r\n\r\nclass ChessBoard(object):\r\n # 类属性\r\n BOARD_SIZE = 15 # 棋盘的大小\r\n\r\n def __init__(self):\r\n # 棋盘的下标从0到15,申请内存\r\n self.__board = [[0 for i in range(ChessBoard.BOARD_SIZE+1)]\r\n for i in range(ChessBoard.BOARD_SIZE+1)]\r\n\r\n\r\n def initBoard(self):\r\n '''清空棋盘'''\r\n\r\n #直接忽略第0行\r\n for i in range(1,ChessBoard.BOARD_SIZE+1):\r\n # 直接忽略第0列\r\n for j in range(1, ChessBoard.BOARD_SIZE + 1):\r\n self.__board[i][j] = '+'\r\n\r\n def printBoard(self):\r\n '''打印棋盘'''\r\n\r\n # 打印列号\r\n print(' ',end='')\r\n for j in range(1, ChessBoard.BOARD_SIZE + 1):\r\n c = chr(j + ord('a')-1) #转换成字母ABCD...\r\n print(c,end=' ')\r\n print()\r\n\r\n # 打印整个棋盘\r\n for i in range(1,ChessBoard.BOARD_SIZE + 1):\r\n # 打印行号\r\n print('%2d' %i,end='')\r\n for j in range(1, ChessBoard.BOARD_SIZE + 1):\r\n print(self.__board[i][j],end=' ')\r\n print()\r\n\r\n def setChess(self,pos,color):\r\n '''\r\n 在棋盘上放置棋子\r\n :param pos: 棋子的位置,该值是一个长度为2的元组\r\n :param color: 棋子的颜色‘x'或’o'\r\n :return:\r\n '''\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception('第一个参数必须为元组或列表') # 抛出异常\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n\r\n self.__board[pos[0]][pos[1]] = color # 放置棋子\r\n\r\n\r\n def setChessMan(self,chessman):\r\n '''\r\n 在棋盘上放置棋子\r\n :param chessman: 棋子对象,需要包含棋子颜色和位置\r\n :return:\r\n '''\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n pos = chessman.getPos() #接收棋子对象的位置\r\n color = chessman.getColor() # 接收棋子对象的颜色\r\n self.setChess(pos,color)\r\n\r\n def getChess(self,pos):\r\n '''\r\n 根据坐标读取棋子\r\n :param pos: 棋子的位置\r\n :return: 棋子的颜色;x或o或+\r\n '''\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception('第一个参数必须为元组或列表') # 抛出异常\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n\r\n return self.__board[pos[0]][pos[1]]\r\n\r\n def isEmpty(self,pos):\r\n '''\r\n 判断某个坐标点是否为空\r\n :param pos: 坐标位置\r\n :return: True空,False不空\r\n '''\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception('第一个参数必须为元组或列表') # 抛出异常\r\n if pos[0] <= 0 or pos[0] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1] > ChessBoard.BOARD_SIZE:\r\n raise Exception('下标越界')\r\n\r\n return self.getChess(pos) == '+'" }, { "alpha_fraction": 0.47984495759010315, "alphanum_fraction": 0.49302324652671814, "avg_line_length": 25.404254913330078, "blob_id": "074efe65a1ab6f4c578c526936a15a0d5d4c3cb5", "content_id": "94b68e13ea0d13227ca2452493da681a98663d92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1490, "license_type": "no_license", "max_line_length": 63, "num_lines": 47, "path": "/网络双人对战五子棋/gobang2_client/usergothread.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/31 10:29\r\n# @Author : LQY\r\n\"\"\" usergothread\"\"\"\r\nimport threading\r\nfrom chessman import *\r\nfrom engine import *\r\nfrom chessboard import *\r\n\r\n\r\nclass UserGoThread(threading.Thread):\r\n '''用户下棋的线程'''\r\n\r\n def __init__(self,chessblack,engine,client_socket):\r\n '''初始化'''\r\n super().__init__()\r\n self.chessblack = chessblack\r\n self.engine = engine\r\n self.client_socket = client_socket\r\n\r\n\r\n def run(self):\r\n '''子线程执行的代码'''\r\n\r\n # 等待主线程唤醒\r\n self.chessblack.doWait()\r\n\r\n while True:\r\n # 1 用户下棋\r\n userinput = input(\"请用户输入下棋坐标:\")\r\n ret = self.engine.userGo(self.chessblack,userinput)\r\n if ret:\r\n # 给服务端发消息说我方已下完棋,轮到对方下棋\r\n # 向服务器发送信息,并传递我方下的棋子的坐标\r\n print(\"我是客户端,我方已下完棋\")\r\n # self.client_socket.send(msg.encode('gbk'))\r\n ret = self.chessblack.getPos()\r\n msg = str(ret[0])+str(',')+str(ret[1])\r\n self.client_socket.send(msg.encode('gbk'))\r\n\r\n # 2 用户notify\r\n self.chessblack.doNotify()\r\n\r\n # 3 用户wait\r\n self.chessblack.doWait()\r\n else:\r\n print(\"下棋重复\")\r\n\r\n" }, { "alpha_fraction": 0.477624773979187, "alphanum_fraction": 0.49956971406936646, "avg_line_length": 28.5, "blob_id": "1415468ace6757100b053ccdf3ab18f3a8d90503", "content_id": "799caceade98b09de27f65efc5eb552df243f509", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2730, "license_type": "no_license", "max_line_length": 89, "num_lines": 76, "path": "/网络双人对战五子棋/gobang2_client/computergothread.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# @Time : 2020/7/31 10:29\r\n# @Author : LQY\r\n\"\"\" computergothread\"\"\"\r\nimport threading\r\nfrom chessman import *\r\nfrom engine import *\r\nfrom chessboard import *\r\nimport re\r\n\r\nclass ComputerGoThread(threading.Thread):\r\n '''电脑下棋的线程'''\r\n\r\n def __init__(self,chessboard,chessmanUser,engine,client_socket): # 服务端收发要用客户端的socket\r\n '''初始化'''\r\n super().__init__()\r\n self.chessboard = chessboard\r\n self.chessmanUser = chessmanUser\r\n self.engine = engine\r\n\r\n self.client_socket = client_socket\r\n\r\n\r\n\r\n def run(self):\r\n '''子线程执行的代码'''\r\n # address = ('', 9860)\r\n # self.server_socket.bind(address) # 绑定服务端地址和端口号\r\n #\r\n # self.server_socket.listen(5) # 监听,最大连接数5\r\n #\r\n # # 一直等待客户端连接,连接成功后则创建一个线程\r\n # client_socket, client_info = self.server_socket.accept() # 申请连接\r\n # 连接服务端\r\n # address = ('192.168.55.29', 8000) # 对手的ip地址和端口号\r\n # self.client_socket.connect(address)\r\n while True:\r\n\r\n\r\n # 1 电脑wait\r\n self.chessmanUser.doWait()\r\n\r\n # # 2 电脑下棋\r\n # self.engine.computerGo(self.chessmanPC)\r\n #\r\n # # 接收客户端发来的坐标信息\r\n # recv_pos = client_socket.recv(1024)\r\n # print(\"我是服务端,对方发过来的坐标是:\",recv_pos.decode('gbk'))\r\n #\r\n # # self.chessboard.setChessMan(list(recv_pos.decode('gbk')))\r\n #\r\n # # 下完棋后给客户端发送坐标信息\r\n # ret = str(self.chessmanPC.getPos()).encode('gbk')\r\n # client_socket.send(ret)\r\n\r\n # 接收服务端发来的坐标信息\r\n recv_pos = self.client_socket.recv(1024).decode('gbk')\r\n pattern = '^([1-9]|1[0-5]),([a-o])$'\r\n ret = re.findall(pattern, recv_pos)\r\n # print(ret)\r\n if ret: # 判断是否匹配成功\r\n posX, posY = ret[0] # ret[0]是一个元组,把值依次传递\r\n posX = int(posX)\r\n posY = ord(posY) - ord('a') + 1\r\n # 判断是否为空\r\n if self.chessboard.isEmpty((posX, posY)):\r\n self.chessmanUser.setPos((posX, posY))\r\n # chessman.setColor('X')\r\n\r\n # 没有匹配到或者位置不空\r\n\r\n print(\"我是客户端,对方发过来的坐标是:\", ret)\r\n\r\n\r\n # 3 电脑notify\r\n self.chessmanUser.doNotify()\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.41313472390174866, "alphanum_fraction": 0.4339878261089325, "avg_line_length": 30.390350341796875, "blob_id": "ec16f6742b5de14380c0fe54f011e0d37389311e", "content_id": "2a7a53855a4518eaa54466716410ef6f12b97427", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8175, "license_type": "no_license", "max_line_length": 84, "num_lines": 228, "path": "/网络双人对战五子棋/Gobang_tcp/engine.py", "repo_name": "lqy9860/qy_code", "src_encoding": "UTF-8", "text": "import random\r\nimport re\r\nfrom chessboard import ChessBoard\r\nfrom chessman import ChessMan\r\n\r\n\r\nclass Engine(object):\r\n def __init__(self,chessboard):\r\n self.__chessboard=chessboard\r\n\r\n def computerGo(self,chessman):\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n # 电脑随机下棋\r\n # 先判断是否为空\r\n while 1:\r\n posX=random.randint(1,15)\r\n posY=random.randint(1,15)\r\n # 如果为空,获取棋子位置并退出循环\r\n if self.__chessboard.isEmpty((posX,posY)):\r\n chessman.Pos=(posX,posY)\r\n print('电脑下棋位置:',posX,posY)\r\n break\r\n\r\n\r\n\r\n def userGo(self,chessman,userInput):\r\n if not isinstance(chessman,ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n # 用户下棋\r\n # 正则表达式判断输入的格式 (1-15,a-o或1-15)\r\n pattern='^([1-9]|1[0-5]),([a-o]|[A-O]|[1-9]|1[0-5])$'\r\n ret=re.findall(pattern,userInput)\r\n if len(ret):\r\n posX,posY=ret[0]\r\n posX=int(posX)\r\n # 如果第二个参数是字母,进行转数字的处理\r\n if posY.isalpha() and ord(posY) >= 97:\r\n posY = ord(posY) - ord('a') + 1\r\n elif posY.isalpha() and ord(posY) >= 65:\r\n posY = ord(posY) - ord('A') + 1\r\n else:\r\n posY=int(posY)\r\n # 如果位置为空,设置棋子位置,并返回True\r\n if self.__chessboard.isEmpty((posX,posY)):\r\n chessman.Pos=(posX,posY)\r\n print('用户下棋位置:',posX, posY)\r\n return True\r\n\r\n return False\r\n\r\n\r\n def isWon(self,pos,color):\r\n if not isinstance(pos,tuple) and not isinstance(pos,list):\r\n raise Exception(\"第一个参数被选为元组或列表\")\r\n if pos[0] <= 0 or pos[0]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n if pos[1] <= 0 or pos[1]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n # print(\"棋子位置\",pos[0],pos[1])\r\n # 判断下某一颗棋子后是否赢\r\n # 上下\r\n count = 0\r\n # 开始标志\r\n startX=1\r\n if pos[0] -4>=1:\r\n startX=pos[0]-4\r\n\r\n # 结束标志\r\n endX=ChessBoard.BOAED_SIZE\r\n if pos[0] +4<=ChessBoard.BOAED_SIZE:\r\n endX=pos[0]+4\r\n # posX范围\r\n for posX in range(startX,endX+1):\r\n if self.__chessboard.getChess((posX,pos[1]))==color :\r\n count +=1\r\n if count == 5:\r\n return True\r\n else:\r\n count=0\r\n # 左右\r\n\r\n # 开始标志\r\n startY=1\r\n if pos[1] -4>=1:\r\n startY=pos[1]-4\r\n # 结束标志\r\n endY=ChessBoard.BOAED_SIZE\r\n if pos[1] +4<=ChessBoard.BOAED_SIZE:\r\n endY=pos[1]+4\r\n # posY范围\r\n for posY in range(startY,endY+1):\r\n if self.__chessboard.getChess((pos[0],posY))==color :\r\n count +=1\r\n if count == 5:\r\n return True\r\n else:\r\n count=0\r\n # 左上右下\r\n # 将棋盘划分为两部分,x>y和x<y\r\n # 开始标志\r\n startX=1\r\n if pos[0] >= pos[1] and pos[1]-4<=1 :\r\n startX=pos[0]-pos[1]+1\r\n elif pos[0] -4 >= 1 :\r\n startX = pos[0] - 4\r\n # 结束标志\r\n endX=ChessBoard.BOAED_SIZE\r\n if pos[0] <= pos[1] and pos[1]+4 >=ChessBoard.BOAED_SIZE:\r\n endX=15-(pos[1]-pos[0])\r\n elif pos[0] <=ChessBoard.BOAED_SIZE-4:\r\n endX = pos[0] + 4\r\n # posX范围\r\n # print(\"左上右下范围\",startX,endX)\r\n for posX in range(startX,endX+1):\r\n posY = pos[1] - (pos[0] - posX)\r\n # print(posX,posY)\r\n if self.__chessboard.getChess((posX,posY))==color :\r\n count +=1\r\n if count == 5:\r\n return True\r\n else:\r\n count = 0\r\n # 左下右上\r\n # 将棋盘划分为两部分,(x+y>15)和(x+y<15)\r\n # 开始标志\r\n startX=1\r\n if pos[1]>=10 and pos[0]+pos[1]>15:\r\n startX=pos[0]+pos[1]-15\r\n elif pos[0] - 4 >= 1 :\r\n startX = pos[0] - 4\r\n # 结束标志\r\n endX=ChessBoard.BOAED_SIZE\r\n if pos[1]<=5 and pos[0]+pos[1]<=15 :\r\n endX=pos[1] +pos[0]-1\r\n elif pos[0] +4<=ChessBoard.BOAED_SIZE:\r\n endX = pos[0] + 4\r\n # posX范围\r\n # print(\"左下右上范围\",startX,endX)\r\n for posX in range(startX,endX+1):\r\n posY = pos[1] + (pos[0] - posX)\r\n # print(posX,posY)\r\n if self.__chessboard.getChess((posX,posY))==color :\r\n count +=1\r\n if count == 5:\r\n return True\r\n else:\r\n count=0\r\n return False\r\n\r\n def isWonMan(self,chessman):\r\n if not isinstance(chessman.Pos,tuple) and not isinstance(chessman.Pos,list):\r\n raise Exception(\"第一个参数被选为元组或列表\")\r\n if chessman.Pos[0] <= 0 or chessman.Pos[0]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n if chessman.Pos[1] <= 0 or chessman.Pos[1]>ChessBoard.BOAED_SIZE:\r\n raise Exception('下标越界')\r\n # 判断某一方下子后是否赢\r\n if not isinstance(chessman, ChessMan):\r\n raise Exception('第一个参数必须为ChessMan对象')\r\n\r\n pos=chessman.Pos\r\n color=chessman.Color\r\n return self.isWon(pos,color)\r\n\r\n\r\n\r\n def play(self):\r\n # 游戏主流程\r\n state=True\r\n # 外循环\r\n while 1:\r\n computerchessman = ChessMan()\r\n userchessman = ChessMan()\r\n # 用户选择先手或后手\r\n order=input('先手1,后手2:')\r\n if order=='1':\r\n # 初始化棋子类\r\n userchessman.Color = 'o'\r\n computerchessman.Color = 'x'\r\n state=True\r\n else:\r\n userchessman.Color = 'x'\r\n computerchessman.Color = 'o'\r\n state=False\r\n # 清空棋盘\r\n self.__chessboard.initBoard()\r\n # 内循环\r\n while 1:\r\n # 是否到用户下\r\n if state:\r\n # 获取用户下棋位置\r\n userInput = input(\"请输入用户下棋位置:\")\r\n ret=self.userGo(userchessman, userInput)\r\n if ret:\r\n # 放置用户下棋位置\r\n self.__chessboard.setChessMan(userchessman)\r\n # 打印棋盘\r\n self.__chessboard.printBoard()\r\n\r\n # 是否赢了\r\n if self.isWonMan(userchessman):\r\n # 退出外循环\r\n print('uwin')\r\n break\r\n else:\r\n state=False\r\n else: continue\r\n # 电脑下\r\n else:\r\n # 获取电脑随机下棋位置\r\n self.computerGo(computerchessman)\r\n # 放置电脑下棋位置\r\n self.__chessboard.setChessMan(computerchessman)\r\n # 打印棋盘\r\n self.__chessboard.printBoard()\r\n # 是否赢了\r\n if self.isWonMan(computerchessman) :\r\n # 退出外循环\r\n print('cwin')\r\n break\r\n else:\r\n state=True\r\n\r\n cont=input('是否继续(1继续)')\r\n # 是否继续\r\n if not (cont=='1'):\r\n break\r\n" } ]
16
astonshane/Alien-Spoilers
https://github.com/astonshane/Alien-Spoilers
be93972b169480c28f9340a92c96e0e9abfe51ed
a84c2eff921bc260f192085129c6891d38594926
5c382b96b3b93abbe2e0f9588ad6d79bacea8a5e
refs/heads/master
2021-01-22T03:55:02.964165
2015-05-05T20:54:24
2015-05-05T20:54:24
28,692,637
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6119999885559082, "alphanum_fraction": 0.6159999966621399, "avg_line_length": 15.666666984558105, "blob_id": "1264694acb7bc62494d2a00360e0d4517b6a0e7a", "content_id": "5a0f303c7af8154eb41210f961779a55725ba703", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "permissive", "max_line_length": 38, "num_lines": 15, "path": "/test.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "import praw\n\ns = '/r/sarah'\ns = s.replace(\"/r/\",\"\")\n\n\nr = praw.Reddit('test by astonshane')\nx = \"\"\ntry:\n x = r.get_subreddit(s, fetch=True)\n print \"succeeded\"\nexcept:\n print x, \"failed\"\n#fullname = x.fullname.encode('utf-8')\n#print fullname\n" }, { "alpha_fraction": 0.7597253918647766, "alphanum_fraction": 0.7620137333869934, "avg_line_length": 30.214284896850586, "blob_id": "1db8cb0a74d3b092b8c09eb0f3d807b440c5c30e", "content_id": "18042f83fd01d2156b0d163b63a793db9d38ef9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 437, "license_type": "permissive", "max_line_length": 79, "num_lines": 14, "path": "/alienspoilers/README.md", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "Config File:\n============\ncreate a file called 'config.ini' in this directory with the following\ncontained inside:\n\n[reddit]\noauth_client_id: [YOUR_OAUTH_CLIENT_ID]\nouath_client_secret: [YOUR_OAUTH_CLIENT_SECRET]\noauth_redirect_uri: [YOUR_REDIRECT_URI]\n\n\nWhere [YOUR_OAUTH_CLIENT_ID] etc. are replaced with the information provided to\nyour specific app by Reddit. For more information visit:\nhttps://github.com/reddit/reddit/wiki/OAuth2\n" }, { "alpha_fraction": 0.7264957427978516, "alphanum_fraction": 0.7264957427978516, "avg_line_length": 28.25, "blob_id": "5b80078a17d9c563c4436df2eb13d44a976d6448", "content_id": "cfe2a5bf264ed75cb98756cd57036e1ab65c0df7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 117, "license_type": "permissive", "max_line_length": 85, "num_lines": 4, "path": "/README.md", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "Alien-Spoilers\n==============\n\nauto-subscribe / unsubscribe from specific subreddits on a schedule to avoid spoilers\n" }, { "alpha_fraction": 0.6403684616088867, "alphanum_fraction": 0.6430383324623108, "avg_line_length": 34.67142868041992, "blob_id": "ff0ef84a68e7ec7dee96003937319ab7bb4ec13c", "content_id": "b34708828a363133783f5f0fe9aef3bce531c759", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7491, "license_type": "permissive", "max_line_length": 109, "num_lines": 210, "path": "/alienspoilers/subs/oauthHelpers.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom subs.forms import UserForm, UserProfileForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom uuid import uuid4\nfrom django.contrib.auth.models import User\nfrom subs.models import UserProfile, Event\nfrom django.utils import timezone\nimport datetime\nimport urllib\nimport requests\nimport ConfigParser\nfrom subreddit import Subreddit\n\n#parse the config file to get the oauth client id/secret\nConfig = ConfigParser.ConfigParser()\nConfig.read(\"config.ini\")\nCLIENT_ID = Config.get(\"reddit\", \"oauth_client_id\")\nCLIENT_SECRET = Config.get(\"reddit\", \"ouath_client_secret\")\nREDIRECT_URI = Config.get(\"reddit\", \"oauth_redirect_uri\")\n\ndef user_agent():\n '''\n reddit API clients should each have their own, unique user-agent\n Ideally, with contact info included.\n '''\n return \"Alien Spoilers - [email protected] - v0.0.2\"\n\ndef base_headers():\n return {\"User-Agent\": user_agent()}\n\ndef make_authorization_url():\n # Generate a random string for the state parameter\n state = str(uuid4())\n print REDIRECT_URI\n params = {\"client_id\": CLIENT_ID,\n \"response_type\": \"code\",\n \"state\": state,\n \"redirect_uri\": REDIRECT_URI,\n \"duration\": \"permanent\",\n \"scope\": \"identity,mysubreddits,subscribe\"}\n url = \"https://ssl.reddit.com/api/v1/authorize?\" + urllib.urlencode(params)\n return url\n\ndef get_initial_token(request, code):\n print \"getting initial token\"\n client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)\n post_data = {\"grant_type\": \"authorization_code\",\n \"code\": code,\n \"redirect_uri\": REDIRECT_URI}\n headers = base_headers()\n response = requests.post(\"https://ssl.reddit.com/api/v1/access_token\",\n auth=client_auth,\n headers=headers,\n data=post_data)\n token_json = response.json()\n\n #update the UserProfile data model with the new data\n profile = request.user.profile\n profile.access_token = token_json[\"access_token\"]\n profile.refresh_token = token_json[\"refresh_token\"]\n profile.reddit_linked = True\n profile.token_expiry = timezone.now() + datetime.timedelta(hours=1)\n profile.save()\n\n return token_json[\"access_token\"]\n\ndef refresh_token(profile):\n print \"refreshing token\"\n client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)\n post_data = {\"grant_type\": \"refresh_token\",\n \"refresh_token\": profile.refresh_token,\n \"redirect_uri\": REDIRECT_URI}\n headers = base_headers()\n response = requests.post(\"https://ssl.reddit.com/api/v1/access_token\",\n auth=client_auth,\n headers=headers,\n data=post_data)\n token_json = response.json()\n\n #update the UserProfile data model with the new data\n #profile = request.user.profile\n profile.access_token = token_json[\"access_token\"]\n #profile.refresh_token = token_json[\"refresh_token\"]\n profile.token_expiry = timezone.now() + datetime.timedelta(hours=1)\n profile.save()\n\n #return token_json[\"access_token\"]\n\n\ndef get_username(access_token):\n headers = base_headers()\n headers.update({\"Authorization\": \"bearer \" + access_token})\n response = requests.get(\"https://oauth.reddit.com/api/v1/me\", headers=headers)\n me_json = response.json()\n #print me_json\n return me_json['name']\n\ndef get_my_subreddits(access_token):\n headers = base_headers()\n headers.update({\"Authorization\": \"bearer \" + access_token})\n response = requests.get(\"https://oauth.reddit.com/subreddits/mine/subscriber?limit=100\", headers=headers)\n dump = response.json()\n\n #print my_subreddits\n\n data = dump['data']\n\n all_subreddits = data['children']\n\n #dictionary\n my_subreddits = []\n\n for subreddit in all_subreddits:\n data = subreddit['data']\n fullname = data['name']\n url = data['url']\n # gets rid of the u' thing\n name = url.encode('utf-8')\n\n #print name, fullname\n\n sub = Subreddit(name, fullname)\n my_subreddits.append(sub)\n\n return my_subreddits\n\ndef unsubscribe(access_token, fullname):\n headers = base_headers()\n headers.update({\"Authorization\": \"bearer \" + access_token})\n headers.update({\"Content-Type\": \"application/json\"})\n rqst = \"https://oauth.reddit.com/api/subscribe?action=unsub&sr=\" + fullname\n #print rqst\n response = requests.post(rqst, headers=headers)\n dump = response.json()\n #print dump\n\ndef subscribe(access_token, fullname):\n headers = base_headers()\n headers.update({\"Authorization\": \"bearer \" + access_token})\n headers.update({\"Content-Type\": \"application/json\"})\n rqst = \"https://oauth.reddit.com/api/subscribe?action=sub&sr=\" + fullname\n #print rqst\n response = requests.post(rqst, headers=headers)\n dump = response.json()\n #print dump\n\ndef newRepeatedEvent(event):\n newEvent = Event()\n newEvent.creator = event.creator\n\n newEvent.title = event.title\n newEvent.subreddit = event.subreddit\n newEvent.subreddit_fullname = event.subreddit_fullname\n\n newEvent.pub_date = event.pub_date\n if event.repeat_type == \"Weekly\":\n newEvent.start_date = event.start_date + datetime.timedelta(weeks=1)\n newEvent.end_date = event.end_date + datetime.timedelta(weeks=1)\n elif event.repeat_type == \"Daily\":\n newEvent.start_date = event.start_date + datetime.timedelta(days=1)\n newEvent.end_date = event.end_date + datetime.timedelta(days=1)\n\n newEvent.event_id = uuid4()\n newEvent.finished = False\n newEvent.repeat = True\n newEvent.repeat_type = event.repeat_type\n newEvent.save()\n\ndef checkEvents(user):\n profile = user.profile\n #refresh the access_token if necessary\n if(timezone.now() >= profile.token_expiry):\n refresh_token(profile)\n\n access_token = profile.access_token\n my_subreddits = get_my_subreddits(access_token)\n\n #get all of the events\n events = Event.objects.filter(creator = user)\n #loop through them\n for event in events:\n current_time = timezone.now()\n #if the current time after the start date of this event and\n # it hasn't been marked as complete...\n if current_time > event.start_date and not event.finished:\n found = False\n fullname = event.subreddit_fullname\n\n #search for the subreddit for this event in my subreddits\n for subreddit in my_subreddits:\n #print subreddit.name\n if subreddit.fullname == fullname:\n found = True\n break\n\n if current_time < event.end_date and found:\n print \"unsubscribing from \", event.subreddit\n unsubscribe(access_token, fullname)\n elif current_time > event.end_date and not found:\n print \"subscribing to \", event.subreddit\n subscribe(access_token, fullname)\n event.finished = True\n event.save()\n\n #if this was a repeated event, create the next event in the sequence\n if event.repeat:\n print \"creating new event...\"\n newRepeatedEvent(event)\n" }, { "alpha_fraction": 0.49298518896102905, "alphanum_fraction": 0.4984411597251892, "avg_line_length": 24.919191360473633, "blob_id": "d283c777f8c22bb595230f6a0a2711d91b49911f", "content_id": "95a85f0f61db1af6ce0db909478a90a89223609d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2566, "license_type": "permissive", "max_line_length": 92, "num_lines": 99, "path": "/alienspoilers/templates/subs/index.html", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% load staticfiles %}\n\n{% block title %}Welcome to Alien Spoilers{% endblock %}\n{% block customStyle %}\n<style>\n table, th, td {\n border: 0px;\n border-collapse: collapse;\n padding: 5px;\n text-align: left;\n }\n th{\n border-bottom: 2px solid black;\n }\n</style>\n{% endblock %}\n\n{% block pagename %}\nYour Events\n{% endblock %}\n\n{% block content %}\n<div class=\"container mtb\">\n Create a new event <a href=\"/subs/create_event\">here</a>!\n </br>\n View all of your Reddit Subscriptions <a href=\"/subs/my_subreddits\">here</a>!\n\n <table style=\"width:100%\">\n <td colspan = \"6\"><h2>Your Current Events:</h2></td>\n <tr>\n <th>Title</th>\n <th>Subreddit</th>\n <th>Start Date</th>\n <th>End Date</th>\n <th>Repeat</th>\n <th></th>\n </tr>\n {% for event in current_events %}\n <tr>\n <td> {{ event.title }} </td>\n <td> {{ event.subreddit }} </td>\n <td> {{ event.start_date }} </td>\n <td> {{ event.end_date }} </td>\n <td>\n {%if event.repeat %}\n <img src=\"/static/admin/img/icon-yes.gif\" alt=\"True\" />\n {{event.repeat_type}}\n {%else%}\n <img src=\"/static/admin/img/icon-no.gif\" alt=\"True\" />\n None\n {%endif%}\n </td>\n <td> <form id=\"delete_event_form\" method=\"post\" action=\"/subs/?id={{event.event_id}}\">\n {% csrf_token %}\n <input type=\"submit\" value=\"delete\" />\n </form>\n </td>\n </tr>\n {% empty %}\n <td colspan = \"6\"> Sorry, No events found... </td>\n {% endfor %}\n\n <td colspan = \"6\"><h2>Your Past Events:</h2></td>\n <tr>\n <th>Title</th>\n <th>Subreddit</th>\n <th>Start Date</th>\n <th>End Date</th>\n <th>Repeat</th>\n <th></th>\n </tr>\n {% for event in past_events %}\n <tr>\n <td> {{ event.title }} </td>\n <td> {{ event.subreddit }} </td>\n <td> {{ event.start_date }} </td>\n <td> {{ event.end_date }} </td>\n <td>\n {%if event.repeat %}\n <img src=\"/static/admin/img/icon-yes.gif\" alt=\"True\" />\n {{event.repeat_type}}\n {%else%}\n <img src=\"/static/admin/img/icon-no.gif\" alt=\"True\" />\n None\n {%endif%}\n </td>\n <td> <form id=\"delete_event_form\" method=\"post\" action=\"/subs/?id={{event.event_id}}\">\n {% csrf_token %}\n <input type=\"submit\" value=\"delete\" />\n </form>\n </td>\n </tr>\n {% empty %}\n <td colspan = \"6\"> Sorry, No events found... </td>\n {% endfor %}\n </table>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5551102161407471, "alphanum_fraction": 0.5571142435073853, "avg_line_length": 18.19230842590332, "blob_id": "8b37f142274a2c9b7dc49d7e8ec3e146a2dbfb60", "content_id": "bfda5b756bd5680f20ddf76f422525b7fde25db9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/old/toggle_sub.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "import praw\nimport sys\n\n\ntry:\n r = praw.Reddit(user_agent = \"astonshane - test praw\")\n r.login()\n subs = r.get_my_subreddits()\n\n found = False\n\n for sub in subs:\n s = str(sub)\n if s.lower() == \"python\":\n found = True\n\n if found:\n r.get_subreddit('python').unsubscribe()\n print \"unsubscribing...\"\n else:\n r.get_subreddit('python').subscribe()\n print \"subscribing...\"\n\n\nexcept:\n print \"Unexpected error:\", sys.exc_info()[0]\n" }, { "alpha_fraction": 0.6761476993560791, "alphanum_fraction": 0.6776447296142578, "avg_line_length": 29.830768585205078, "blob_id": "bac247c0be65d4f946d163fb376002ca1e6377d5", "content_id": "47fb979ca5d2fe07410dd249b772fea465c2ef2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2004, "license_type": "permissive", "max_line_length": 111, "num_lines": 65, "path": "/alienspoilers/subs/renderings.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom uuid import uuid4\nfrom django.contrib.auth.models import User\nfrom subs.models import UserProfile, Event\nfrom django.utils import timezone\nimport datetime\nimport urllib\nimport requests\nfrom subreddit import Subreddit\nimport sys\nimport os\n\nscriptpath = \"subs/\"\n\n# Add the directory containing your module to the Python path (wants absolute paths)\nsys.path.append(os.path.abspath(scriptpath))\nfrom oauthHelpers import *\n\n\ndef my_subreddits_render(request):\n profile = request.user.profile\n\n if(timezone.now() >= profile.token_expiry):\n refresh_token(profile)\n user_name = get_username(profile.access_token)\n my_subreddits = get_my_subreddits(profile.access_token)\n\n return render(request, 'subs/my_subreddits.html', {'user_name': user_name, 'my_subreddits': my_subreddits})\n\ndef index_render(request):\n\n user = request.user\n profile = request.user.profile\n\n if request.method == 'POST':\n event_id = request.GET.get('id', '')\n #print \"event_id: \", event_id\n\n '''events = Event.objects.filter(creator = user)\n print events\n for event in events:\n print \" \", event.event_id, event.title\n events = Event.objects.filter(event_id = event_id)\n print events'''\n event = Event.objects.filter(creator=user, event_id=event_id)\n #print event[0]\n event[0].delete()\n\n checkEvents(user)\n\n #get all of the events which the user is a part of...\n events = Event.objects.filter(creator = user)\n current_events = []\n past_events = []\n for event in events:\n if event.end_date > timezone.now():\n current_events.append(event)\n else:\n past_events.append(event)\n\n '''print \"current events: \", current_events\n print \"past events: \", past_events'''\n\n return render(request, 'subs/index.html', {'current_events': current_events, 'past_events': past_events})\n" }, { "alpha_fraction": 0.7090908885002136, "alphanum_fraction": 0.710303008556366, "avg_line_length": 28.464284896850586, "blob_id": "deed4ba0106c38346d88c14fe90cffee11a84391", "content_id": "316ecdc9a2d0b1d72b05b54e9d8ce4a9f5956e2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "permissive", "max_line_length": 118, "num_lines": 28, "path": "/alienspoilers/subs/forms.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth.models import User\nfrom subs.models import UserProfile, Event\nimport datetime\nfrom django.utils import timezone\nfrom django.contrib.admin import widgets\n\nclass UserForm(forms.ModelForm):\n password = forms.CharField(widget=forms.PasswordInput())\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password')\n\nclass UserProfileForm(forms.ModelForm):\n class Meta:\n model = UserProfile\n fields = ()\n\n\nclass CreateEventForm(forms.ModelForm):\n\n #start_date = forms.DateTimeField(widget=forms.DateTimeInput(), initial=timezone.now())\n #end_date = forms.DateTimeField(widget=forms.DateTimeInput(), initial=timezone.now() + datetime.timedelta(days=1))\n\n class Meta:\n model = Event\n fields = ['title', 'subreddit']\n" }, { "alpha_fraction": 0.5504841208457947, "alphanum_fraction": 0.5629322528839111, "avg_line_length": 27.920000076293945, "blob_id": "4671d31f4564be26571b3bcf5d732e24caf94d16", "content_id": "3557fb9725dba7f37d17a32dc7ba4a4d1b3bb1c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1446, "license_type": "permissive", "max_line_length": 131, "num_lines": 50, "path": "/alienspoilers/templates/subs/login.html", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% load staticfiles %}\n\n{% block title %}Login to Alien Spoilers{% endblock %}\n{% block pagename %} Login {% endblock %}\n\n{% block content %}\n<div class=\"container mtb\">\n {% if invalid %}\n <div style=\"color:#FF0000\"> Invalid login details supplied. Try Again! </div>\n {% endif %}\n\n <form id=\"login_form\" method=\"post\" action=\"/subs/login/\">\n {% csrf_token %}\n\n <p><label for=\"id_username\">Username:</label> <input id=\"id_username\" maxlength=\"30\" name=\"username\" type=\"text\" /></p>\n <p><label for=\"id_password\">Password:</label> <input id=\"id_password\" maxlength=\"30\" name=\"password\" type=\"password\" /></p>\n\n <button type=\"submit\" name =\"submit\" class=\"btn btn-theme\">Submit</button>\n </form>\n</div>\n{% endblock %}\n\n<!--\n<!DOCTYPE html>\n<html>\n <head>\n <title>Alien Spoilers - Login</title>\n </head>\n\n <body>\n <h1>Login to Alien Spoilers</h1>\n\n {% if invalid %}\n <div style=\"color:#FF0000\"> Invalid login details supplied. Try Again! </div>\n {% endif %}\n\n <form id=\"login_form\" method=\"post\" action=\"/subs/login/\">\n {% csrf_token %}\n Username: <input type=\"text\" name=\"username\" value=\"\" size=\"50\" />\n <br />\n Password: <input type=\"password\" name=\"password\" value=\"\" size=\"50\" />\n <br />\n\n <input type=\"submit\" value=\"submit\" />\n </form>\n\n </body>\n</html>\n-->\n" }, { "alpha_fraction": 0.5586854219436646, "alphanum_fraction": 0.5586854219436646, "avg_line_length": 25.625, "blob_id": "5bdfe8f1471d594e0e578afe28046bcf8d0faca6", "content_id": "266b00c14406718c93e095e4fc3fd17126033127", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "permissive", "max_line_length": 49, "num_lines": 8, "path": "/alienspoilers/subs/subreddit.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "class Subreddit:\n def __init__(self, name, fullname):\n self.name = name\n self.fullname = fullname\n self.url = \"http://www.reddit.com\" + name\n\n def __str__(self):\n print self.name\n" }, { "alpha_fraction": 0.5739848613739014, "alphanum_fraction": 0.5815554261207581, "avg_line_length": 31.288888931274414, "blob_id": "628873c1d7a86f3f85f96ed4c0e1d5d716556ed1", "content_id": "ff9ddce230ab0024999ae2780a91b528f33320fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1453, "license_type": "permissive", "max_line_length": 86, "num_lines": 45, "path": "/old/subscribe.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "import praw\nimport sys\n\ndef is_subscribed(subreddit):\n r = praw.Reddit(user_agent = \"Alien Spoilers: v0.0.1\")\n r.login()\n\n subs = r.get_my_subreddits()\n for sub in subs:\n if str(sub) == subreddit:\n return True\n return False\n\n\ndef subscribe(subreddit):\n r = praw.Reddit(user_agent = \"Alien Spoilers: v0.0.1\")\n try:\n r.login()\n try:\n r.get_subreddit(subreddit).subscribe()\n print \"Subscribed to /r/\", subreddit\n except:\n if is_subscribed(subreddit):\n print \"ERROR: You are already subscribed to\", subreddit\n else:\n print \"Unexpected error:\", sys.exc_info()[0]\n print \"Could not subscribe to /r/\", subreddit\n except:\n print \"Unexpected error: Failed during login login: check username / password\"\n\ndef unsubscribe(subreddit):\n r = praw.Reddit(user_agent = \"Alien Spoilers: v0.0.1\")\n try:\n r.login()\n try:\n r.get_subreddit(subreddit).unsubscribe()\n print \"Unsubscribed from /r/\", subreddit\n except:\n if not is_subscribed(subreddit):\n print \"ERROR: You are not subscribed to \", subreddit\n else:\n print \"Unexpected error:\", sys.exc_info()[0]\n print \"Could not unsubscribe from /r/\", subreddit\n except:\n print \"Unexpected error: Failed during login login: check username / password\"\n" }, { "alpha_fraction": 0.7345724701881409, "alphanum_fraction": 0.7353159785270691, "avg_line_length": 33.487178802490234, "blob_id": "18be3ddd03af9e65b08cdc23721beea9c307958f", "content_id": "5ad45730eab9a8a2a026fbcd26b05e1ad752e19d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "permissive", "max_line_length": 119, "num_lines": 39, "path": "/alienspoilers/home/views.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom subs.forms import UserForm, UserProfileForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom uuid import uuid4\nfrom django.contrib.auth.models import User\nfrom subs.models import UserProfile\nfrom django.utils import timezone\nimport datetime\nimport urllib\nimport ConfigParser\nimport sys\nimport os\n\nscriptpath = \"subs/\"\n\n# Add the directory containing your module to the Python path (wants absolute paths)\nsys.path.append(os.path.abspath(scriptpath))\n\n# Do the import\nfrom oauthHelpers import *\nfrom renderings import *\n\n# Create your views here.\n\ndef index(request):\n if request.user.is_authenticated():\n #if user hasn't linked their reddit account yet, send them to a page to do that...\n profile = request.user.profile\n if profile.reddit_linked:\n return index_render(request)\n else:\n return render(request, 'subs/index.html', {'link_url': make_authorization_url()})\n else:\n user_form = UserForm()\n profile_form = UserProfileForm()\n return render(request, 'home/index.html', {'home': True, 'user_form': user_form, 'profile_form': profile_form})\n #return HttpResponse(\"Hello World. Homepage\")\n" }, { "alpha_fraction": 0.6611570119857788, "alphanum_fraction": 0.6611570119857788, "avg_line_length": 42.21428680419922, "blob_id": "b359903ae6326d2acb177e1f8a88173f24af2030", "content_id": "69f45c6c40a644b8e865cb1127711515ad2b0bd2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 605, "license_type": "permissive", "max_line_length": 82, "num_lines": 14, "path": "/alienspoilers/subs/urls.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\n\nfrom subs import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^register/$', views.register, name='register'),\n url(r'^login/$', views.user_login, name='login'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^authorize_callback/$', views.user_authorize_callback, name='callback'),\n url(r'^my_subreddits/$', views.my_subreddits, name='my_subreddits'),\n url(r'^create_event/$', views.create_event, name='create_event'),\n url(r'^link_account/$', views.link_account, name='link_account'),\n)\n" }, { "alpha_fraction": 0.7562189102172852, "alphanum_fraction": 0.7562189102172852, "avg_line_length": 39.20000076293945, "blob_id": "c847716a414a8f753c03548186b9d3e5aaf691d9", "content_id": "9df3cbd84a05002a8f44acf27bdb0b777c9ba867", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "permissive", "max_line_length": 163, "num_lines": 10, "path": "/alienspoilers/subs/admin.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom subs.models import Event\nfrom subs.models import UserProfile\n\nclass EventAdmin(admin.ModelAdmin):\n list_display = ('title', 'creator', 'subreddit', 'subreddit_fullname', 'start_date', 'end_date', 'pub_date', 'repeat', 'repeat_type', 'was_published_recently')\n\n# Register your models here.\nadmin.site.register(Event, EventAdmin)\nadmin.site.register(UserProfile)\n" }, { "alpha_fraction": 0.641058623790741, "alphanum_fraction": 0.6418086290359497, "avg_line_length": 37.407405853271484, "blob_id": "8a5df0deefc79f37b50d24bf4bc125804979c336", "content_id": "8a38932f2d008830694e1b6c800a318635868c9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9333, "license_type": "permissive", "max_line_length": 127, "num_lines": 243, "path": "/alienspoilers/subs/views.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom subs.forms import UserForm, UserProfileForm, CreateEventForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom uuid import uuid4\nfrom django.contrib.auth.models import User\nfrom subs.models import UserProfile, Event\nfrom django.utils import timezone\nimport datetime\nimport urllib\nimport ConfigParser\nfrom subreddit import Subreddit\nfrom oauthHelpers import *\nfrom renderings import *\nimport praw\n\n#parse the config file to get the oauth client id/secret\nConfig = ConfigParser.ConfigParser()\nConfig.read(\"config.ini\")\nCLIENT_ID = Config.get(\"reddit\", \"oauth_client_id\")\nCLIENT_SECRET = Config.get(\"reddit\", \"ouath_client_secret\")\nREDIRECT_URI = Config.get(\"reddit\", \"oauth_redirect_uri\")\n\n@login_required\ndef index(request):\n profile = request.user.profile\n if profile.reddit_linked:\n return index_render(request)\n else:\n #if user hasn't linked their reddit account yet, send them to a page to do that...\n return render(request, 'subs/link_account.html', {'link_url': make_authorization_url()})\n\n@login_required\ndef my_subreddits(request):\n profile = request.user.profile\n if profile.reddit_linked:\n return my_subreddits_render(request)\n else:\n #if user hasn't linked their reddit account yet, send them to a page to do that...\n return render(request, 'subs/link_account.html', {'link_url': make_authorization_url()})\n\n@login_required\ndef link_account(request):\n profile = request.user.profile\n if profile.reddit_linked:\n return index_render(request)\n else:\n return index_render(request)\n\n\ndef register(request):\n # A boolean value for telling the template whether the registration was successful.\n # Set to False initially. Code changes value to True when registration succeeds.\n registered = False\n\n # If it's a HTTP POST, we're interested in processing form data.\n if request.method == 'POST':\n # Attempt to grab information from the raw form information.\n # Note that we make use of both UserForm and UserProfileForm.\n user_form = UserForm(data=request.POST)\n profile_form = UserProfileForm(data=request.POST)\n\n # If the two forms are valid...\n if user_form.is_valid() and profile_form.is_valid():\n # Save the user's form data to the database.\n user = user_form.save()\n\n # Now we hash the password with the set_password method.\n # Once hashed, we can update the user object.\n user.set_password(user.password)\n user.save()\n\n # Now sort out the UserProfile instance.\n # Since we need to set the user attribute ourselves, we set commit=False.\n # This delays saving the model until we're ready to avoid integrity problems.\n profile = profile_form.save(commit=False)\n profile.user = user\n\n\n # Now we save the UserProfile model instance.\n profile.save()\n\n # Update our variable to tell the template registration was successful.\n registered = True\n\n # Invalid form or forms - mistakes or something else?\n # Print problems to the terminal.\n # They'll also be shown to the user.\n else:\n print user_form.errors, profile_form.errors\n\n # Not a HTTP POST, so we render our form using two ModelForm instances.\n # These forms will be blank, ready for user input.\n else:\n user_form = UserForm()\n profile_form = UserProfileForm()\n\n # Render the template depending on the context.\n return render(request,\n 'subs/register.html',\n {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )\n\ndef user_login(request):\n # If the request is a HTTP POST, try to pull out the relevant information.\n if request.method == 'POST':\n # Gather the username and password provided by the user.\n # This information is obtained from the login form.\n username = request.POST['username']\n password = request.POST['password']\n\n # Use Django's machinery to attempt to see if the username/password\n # combination is valid - a User object is returned if it is.\n user = authenticate(username=username, password=password)\n\n # If we have a User object, the details are correct.\n # If None (Python's way of representing the absence of a value), no user\n # with matching credentials was found.\n if user:\n # Is the account active? It could have been disabled.\n if user.is_active:\n # If the account is valid and active, we can log the user in.\n # We'll send the user back to the homepage.\n login(request, user)\n #run checks upon login to see if the user has any events current events:\n if user.profile.reddit_linked:\n checkEvents(user)\n return HttpResponseRedirect('/subs/')\n else:\n # An inactive account was used - no logging in!\n return HttpResponse(\"Your AlienSpoilers account is disabled.\")\n else:\n # Bad login details were provided. So we can't log the user in.\n print \"Invalid login details: {0}, {1}\".format(username, password)\n return render(request,'subs/login.html', {'invalid':True})\n #return HttpResponse(\"Invalid login details supplied.\")\n\n # The request is not a HTTP POST, so display the login form.\n # This scenario would most likely be a HTTP GET.\n else:\n # No context variables to pass to the template system, hence the\n # blank dictionary object...\n return render(request, 'subs/login.html', {'invalid':False})\n\n# Use the login_required() decorator to ensure only those logged in can access the view.\n@login_required\ndef user_logout(request):\n # Since we know the user is logged in, we can now just log them out.\n logout(request)\n\n # Take the user back to the homepage.\n return HttpResponseRedirect('/')\n\n@login_required\ndef user_authorize_callback(request):\n\n error = request.GET.get('error', '')\n if error:\n return \"Error: \" + error\n\n state = request.GET.get('state', '')\n code = request.GET.get('code')\n\n get_initial_token(request, code)\n\n return index_render(request)\n\n@login_required\ndef create_event(request):\n # A boolean value for telling the template whether the registration was successful.\n # Set to False initially. Code changes value to True when registration succeeds.\n created = False\n\n # If it's a HTTP POST, we're interested in processing form data.\n if request.method == 'POST':\n # Attempt to grab information from the raw form information.\n event_form = CreateEventForm(data=request.POST)\n # If the for is valid...\n # Save the user's form data to the database.\n event = Event()\n event.subreddit = request.POST['subreddit']\n event.title = request.POST['title']\n event.start_date = request.POST['start_date']\n event.end_date = request.POST['end_date']\n\n event.creator = request.user\n event.event_id = uuid4()\n event.pub_date = timezone.now()\n\n repeat = request.POST['choice']\n if repeat != \"None\":\n event.repeat = True\n event.repeat_type = repeat\n\n #print request.POST\n #for p in request.POST:\n # print p, request.POST[p]\n #startDate = request.POST['datetimepicker6']\n #print startDate\n\n\n r = praw.Reddit(user_agent())\n sr = event.subreddit.replace(\"/r/\",\"\")\n #print sr\n try:\n #print \"subreddit: ####\", sr\n x = r.get_subreddit(sr, fetch=True)\n event.subreddit_fullname = x.fullname.encode('utf-8')\n #print event.subreddit_fullname\n\n except:\n #the subreddit lookup failed...\n # display an error message\n print \"invalid subreddit entered\"\n event_form = CreateEventForm()\n return render(request, 'subs/create_event.html',\n {'event_form': event_form, 'created': created, 'invalid': True, 'msg': \"Invalid subreddit entered. Try again\"})\n\n\n try:\n #save the form\n event.save()\n # Update our variable to tell the template the event creation was successful.\n created = True\n return index_render(request)\n\n except:\n print \"ERROR occured while saving event\"\n print sys.exc_info()[0]\n event_form = CreateEventForm()\n return render(request, 'subs/create_event.html',\n {'event_form': event_form, 'created': created, 'invalid': True, 'msg': \"Error while saving event. Try Again\"})\n\n\n # Not a HTTP POST, so we render our form using two ModelForm instances.\n # These forms will be blank, ready for user input.\n else:\n event_form = CreateEventForm()\n\n # Render the template depending on the context.\n return render(request,\n 'subs/create_event.html',\n {'event_form': event_form, 'created': created} )\n" }, { "alpha_fraction": 0.7107203602790833, "alphanum_fraction": 0.7231990694999695, "avg_line_length": 34.8775520324707, "blob_id": "015162419b9c1307212a9b3ab437dae300123870", "content_id": "0b69b1e7e4c79c171243776519a8d4a8bf716a26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "permissive", "max_line_length": 75, "num_lines": 49, "path": "/alienspoilers/subs/models.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "import datetime\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\nimport uuid\n\nclass UserProfile(models.Model):\n # This line is required. Links UserProfile to a User model instance.\n user = models.OneToOneField(User, related_name=\"profile\")\n\n # The additional attributes we wish to include.\n refresh_token = models.CharField(max_length=200, null=True)\n access_token = models.CharField(max_length=200, null=True)\n token_expiry = models.DateTimeField('token expiry', null=True)\n reddit_linked = models.BooleanField(default=False)\n\n # Override the __unicode__() method to return out something meaningful!\n def __unicode__(self):\n return self.user.username\n\n\n# Create your models here.\nclass Event(models.Model):\n creator = models.ForeignKey(User, blank=True, null=True)\n title = models.CharField(max_length=200)\n\n subreddit = models.CharField(max_length=200)\n subreddit_fullname = models.CharField(max_length=200, null=True)\n\n pub_date = models.DateTimeField('date published')\n start_date = models.DateTimeField('start date')\n end_date = models.DateTimeField('end date')\n\n event_id = models.CharField(max_length=200)\n finished = models.BooleanField(default=False)\n repeat = models.BooleanField(default=False)\n repeat_type = models.CharField(max_length=200, null=True)\n\n\n def __str__(self):\n return self.title\n\n def was_published_recently(self):\n return self.pub_date >= timezone.now() - datetime.timedelta(days=1)\n\n was_published_recently.admin_order_field = 'pub_date'\n was_published_recently.boolean = True\n was_published_recently.short_description = 'Published recently?'\n \n" }, { "alpha_fraction": 0.5320910811424255, "alphanum_fraction": 0.567287802696228, "avg_line_length": 20.954545974731445, "blob_id": "b0d8970f995e2c140a85d38c305f161f47392f9c", "content_id": "902b6c532a2d54bc3051e697b8c93efd6136b7aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "permissive", "max_line_length": 44, "num_lines": 22, "path": "/alienspoilers/subs/migrations/0006_auto_20150204_1435.py", "repo_name": "astonshane/Alien-Spoilers", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('subs', '0005_auto_20150204_1432'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='userprofile',\n name='reddit_linked',\n ),\n migrations.RemoveField(\n model_name='userprofile',\n name='reddit_refresh_token',\n ),\n ]\n" } ]
17
sachin1171/Multi-linear-regression
https://github.com/sachin1171/Multi-linear-regression
af176b594a559173fde2ebe13a3ca2b27f8fbe1c
8f42d1f405a07ce33d2cefad190cafe98c66dfe9
bce269f71edc68ca6e4ba1b0ad94b3e826937378
refs/heads/main
2023-06-05T13:10:11.954621
2021-06-15T07:04:40
2021-06-15T07:04:40
377,068,266
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.667809009552002, "alphanum_fraction": 0.6793628931045532, "avg_line_length": 33.09621810913086, "blob_id": "e177fd4e31739d91f6964fc9c90a36f40e66e237", "content_id": "27f04841c79c6abcc3f021120d9e688b1551b3a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30639, "license_type": "no_license", "max_line_length": 218, "num_lines": 873, "path": "/MLR.py", "repo_name": "sachin1171/Multi-linear-regression", "src_encoding": "UTF-8", "text": "########################### problem 1 #####################\r\nimport pandas as pd\r\n#loading the dataset\r\nstartup = pd.read_csv(\"C:/Users/usach/Desktop/Multi Linear Regression/50_Startups.csv\")\r\n\r\n#2.\tWork on each feature of the dataset to create a data dictionary as displayed in the below image\r\n\r\n#######feature of the dataset to create a data dictionary\r\ndescription = [\"Money spend on research and development\",\r\n \"Administration\",\r\n \"Money spend on Marketing\",\r\n \"Name of state\",\r\n \"Company profit\"]\r\n\r\nd_types =[\"Ratio\",\"Ratio\",\"Ratio\",\"Nominal\",\"Ratio\"]\r\n\r\ndata_details =pd.DataFrame({\"column name\":startup.columns,\r\n \"data types \":d_types,\r\n \"description\":description,\r\n \"data type(in Python)\": startup.dtypes})\r\n\r\n#3.\tData Pre-startupcessing\r\n#3.1 Data Cleaning, Feature Engineering, etc\r\n#details of startup \r\nstartup.info()\r\nstartup.describe() \r\n#rename the columns\r\nstartup.rename(columns = {'R&D Spend':'rd_spend', 'Marketing Spend' : 'm_spend'} , inplace = True) \r\n#data types \r\nstartup.dtypes\r\n#checking for na value\r\nstartup.isna().sum()\r\nstartup.isnull().sum()\r\n#checking unique value for each columns\r\nstartup.nunique()\r\n\"\"\"\tExploratory Data Analysis (EDA):\r\n\tSummary\r\n\tUnivariate analysis\r\n\tBivariate analysis \"\"\"\r\n \r\nEDA ={\"column \": startup.columns,\r\n \"mean\": startup.mean(),\r\n \"median\":startup.median(),\r\n \"mode\":startup.mode(),\r\n \"standard deviation\": startup.std(),\r\n \"variance\":startup.var(),\r\n \"skewness\":startup.skew(),\r\n \"kurtosis\":startup.kurt()}\r\n\r\nEDA\r\n# covariance for data set \r\ncovariance = startup.cov()\r\ncovariance\r\n\r\n# Correlation matrix \r\nco = startup.corr()\r\nco\r\n\r\n# according to correlation coefficient no correlation of Administration & State with model_dffit\r\n#According scatter plot strong correlation between model_dffit and rd_spend and \r\n#also some relation between model_dffit and m_spend.\r\n####### graphistartup repersentation \r\n##historgam and scatter plot\r\nimport seaborn as sns\r\nsns.pairplot(startup.iloc[:, :])\r\n\r\n#boxplot for every columns\r\nstartup.columns\r\nstartup.nunique()\r\n\r\nstartup.boxplot(column=['rd_spend', 'Administration', 'm_spend', 'Profit']) #no outlier\r\n\r\n# here we can see lVO For profit\r\n# Detection of outliers (find limits for RM based on IQR)\r\nIQR = startup['Profit'].quantile(0.75) - startup['Profit'].quantile(0.25)\r\nlower_limit = startup['Profit'].quantile(0.25) - (IQR * 1.5)\r\n\r\n####################### 2.Replace ############################\r\n# Now let's replace the outliers by the maximum and minimum limit\r\n#Graphical Representation\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt # mostly used for visualization purposes \r\n\r\nstartup['Profit']= pd.DataFrame( np.where(startup['Profit'] < lower_limit, lower_limit, startup['Profit']))\r\n\r\nimport seaborn as sns \r\nsns.boxplot(startup.Profit);plt.title('Boxplot');plt.show()\r\n\r\n# rd_spend\r\nplt.bar(height = startup.rd_spend, x = np.arange(1, 51, 1))\r\nplt.hist(startup.rd_spend) #histogram\r\nplt.boxplot(startup.rd_spend) #boxplot\r\n\r\n# Administration\r\nplt.bar(height = startup.Administration, x = np.arange(1, 51, 1))\r\nplt.hist(startup.Administration) #histogram\r\nplt.boxplot(startup.Administration) #boxplot\r\n\r\n# m_spend\r\nplt.bar(height = startup.m_spend, x = np.arange(1, 51, 1))\r\nplt.hist(startup.m_spend) #histogram\r\nplt.boxplot(startup.m_spend) #boxplot\r\n\r\n#profit\r\nplt.bar(height = startup.Profit, x = np.arange(1, 51, 1))\r\nplt.hist(startup.Profit) #histogram\r\nplt.boxplot(startup.Profit) #boxplot\r\n\r\n# Jointplot\r\n\r\nsns.jointplot(x=startup['Profit'], y=startup['rd_spend'])\r\n\r\n# Q-Q Plot\r\nfrom scipy import stats\r\nimport pylab\r\n\r\nstats.probplot(startup.Profit, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n# startupfit is normally distributed\r\n\r\nstats.probplot(startup.Administration, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n# administration is normally distributed\r\n\r\nstats.probplot(startup.rd_spend, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n\r\nstats.probplot(startup.m_spend, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n#normal\r\n# Normalization function using z std. all are continuous data.\r\ndef norm_func(i):\r\n x = (i-i.mean())/(i.std())\r\n return (x)\r\n\r\n# Normalized data frame (considering the numerical part of data)\r\ndf_norm = norm_func(startup.iloc[:,[0,1,2]])\r\ndf_norm.describe()\r\n\r\n\"\"\"\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n# creating instance of one-hot-encoder\r\nenc = OneHotEncoder(handle_unknown='ignore')\r\nsta=startup.iloc[:,[3]]\r\nenc_df = pd.DataFrame(enc.fit_transform(sta).toarray())\"\"\"\r\n\r\n# Create dummy variables on categorcal columns\r\n\r\nenc_df = pd.get_dummies(startup.iloc[:,[3]])\r\nenc_df.columns\r\nenc_df.rename(columns={\"State_New York\":'State_New_York'},inplace= True)\r\n\r\nmodel_df = pd.concat([enc_df, df_norm, startup.iloc[:,4]], axis =1)\r\n\r\n#rename the columns\r\n\r\n\"\"\"5.\tModel Building\r\n5.1\tBuild the model on the scaled data (try multiple options)\r\n5.2\tPerform Multi linear regression model and check for VIF, AvPlots, Influence Index Plots.\r\n5.3\tTrain and Test the data and compare RMSE values tabulate R-Squared values , RMSE for different models in documentation and model_dfvide your explanation on it.\r\n5.4\tBriefly explain the model output in the documentation. \r\n\"\"\"\r\n\r\n# preparing model considering all the variables \r\nimport statsmodels.formula.api as smf # for regression model\r\n\r\nml1 = smf.ols('Profit ~ State_California+ State_Florida+ State_New_York+ rd_spend + Administration + m_spend ', data = model_df).fit() # regression model\r\n\r\n# Summary\r\nml1.summary2()\r\nml1.summary()\r\n# p-values for State, Administration are more th no correlation of model_dffit with State and Administrationan 0.05\r\n# Checking whether data has any influential values \r\n# Influence Index Plots\r\nimport statsmodels.api as sm \r\n\r\nsm.graphics.influence_plot(ml1)\r\n# Studentized Residuals = Residual/standard deviation of residuals\r\n# index 49 is showing high influence so we can exclude that entire row\r\n\r\nmodel_df_new = model_df.drop(model_df.index[[49]])\r\n\r\n# Preparing model \r\nml_new = smf.ols('Profit ~State_California+ State_Florida+ State_New_York+ rd_spend + Administration + m_spend ', data = model_df_new).fit() \r\n\r\n# Summary\r\nml_new.summary()\r\nml_new.summary2()\r\n\r\n# Check for Colinearity to decide to remove a variable using VIF\r\n# Assumption: VIF > 10 = colinearity\r\n# calculating VIF's values of independent variables\r\nrsq_rd_spend = smf.ols('rd_spend ~ Administration + m_spend + State_California+ State_Florida+ State_New_York', data = model_df).fit().rsquared \r\nvif_rd_spend = 1/(1 - rsq_rd_spend) \r\n\r\nrsq_admini = smf.ols(' Administration ~ rd_spend + m_spend + State_California+ State_Florida+ State_New_York ', data = model_df).fit().rsquared \r\nvif_admini = 1/(1 - rsq_admini)\r\nml_ad=smf.ols(' Administration ~ rd_spend + m_spend + State_California+ State_Florida+ State_New_York ', data = model_df).fit()\r\nml_ad.summary() \r\n\r\nrsq_m_spend = smf.ols(' m_spend ~ rd_spend + Administration + State_California+ State_Florida+ State_New_York', data = model_df).fit().rsquared \r\nvif_m_spend = 1/(1 - rsq_m_spend) \r\n\r\nrsq_state = smf.ols(' State_California ~ rd_spend + Administration + m_spend ', data = model_df).fit().rsquared \r\nvif_state = 1/(1 - rsq_state) \r\n\r\nml_S= smf.ols(' State_California~ rd_spend + Administration + m_spend ', data = model_df).fit()\r\nml_S.summary()\r\n\r\n# Storing vif values in a data frame\r\nd1 = {'Variables':['rd_spend' ,'Administration' ,'m_spend ',' State '], 'VIF':[vif_rd_spend, vif_admini, vif_m_spend, vif_state]}\r\nVif_frame = pd.DataFrame(d1) \r\nVif_frame\r\n\r\n#vif is low \r\n#model 2 without Administration column because p value of state >>> 0.5\r\n\r\nml2 = smf.ols('Profit ~ rd_spend + State_California+ State_Florida+ State_New_York + m_spend ', data = model_df).fit() # regression model\r\n# Summary\r\nml2.summary()\r\n\r\n# administration p value is high \r\nsm.graphics.influence_plot(ml2)\r\n\r\n# Studentized Residuals = Residual/standard deviation of residuals\r\n#model 3 without Administration and state column because p value of state >>> 0.5\r\nml3 = smf.ols('Profit ~ rd_spend + m_spend ', data = model_df_new).fit() # regression model\r\n\r\n# Summary\r\nml3.summary()\r\n\r\nsm.graphics.influence_plot(ml3)\r\n\r\n# Final model\r\nfinal_ml = smf.ols('Profit ~ rd_spend + m_spend + State_California+ State_Florida+ State_New_York ', data = model_df).fit() \r\nfinal_ml.summary() \r\n\r\n# Prediction\r\npred = final_ml.predict(model_df)\r\n\r\n# Q-Q plot\r\nres = final_ml.resid\r\nsm.qqplot(res)\r\nplt.show()\r\n\r\nstats.probplot(res, dist = \"norm\", plot = pylab)\r\nplt.show()\r\n\r\n# Residuals vs Fitted plot\r\nsns.residplot(x = pred, y = model_df.Profit, lowess = True)\r\nplt.xlabel('Fitted')\r\nplt.ylabel('Residual')\r\nplt.title('Fitted vs Residual')\r\nplt.show()\r\n\r\nsm.graphics.influence_plot(final_ml)\r\n### Splitting the data into train and test data \r\nfrom sklearn.model_selection import train_test_split\r\nmodel_df_train, model_df_test = train_test_split(model_df, test_size = 0.2,random_state = 457) # 20% test data\r\n\r\n# preparing the model on train data \r\nmodel_train = smf.ols('Profit ~ rd_spend + m_spend + State_California+ State_Florida+ State_New_York ', data = model_df_train).fit()\r\nmodel_train.summary()\r\nmodel_train.summary2()\r\n# prediction on test data set \r\ntest_pred = model_train.predict(model_df_test)\r\n\r\n# test residual values \r\ntest_resid = test_pred - model_df_test.Profit\r\n# RMSE value for test data \r\ntest_rmse = np.sqrt(np.mean(test_resid * test_resid))\r\ntest_rmse\r\n# train_data prediction\r\ntrain_pred = model_train.predict(model_df_train)\r\n\r\n# train residual values \r\ntrain_resid = train_pred - model_df_train.Profit\r\n# RMSE value for train data \r\ntrain_rmse = np.sqrt(np.mean(train_resid * train_resid))\r\ntrain_rmse\r\n\r\n####################### problem 2 #################################\r\nimport pandas as pd\r\n\r\n#loading the dataset\r\ncomputer = pd.read_csv(\"C:/Users/usach/Desktop/Multi Linear Regression/Computer_Data.csv\")\r\n#2.\tWork on each feature of the dataset to create a data dictionary as displayed in the below image\r\n#######feature of the dataset to create a data dictionary\r\ndescription = [\"Index row number (irrelevant ,does not provide useful Informatiom)\",\r\n \"Price of computer(relevant provide useful Informatiom)\",\r\n \"computer speed (relevant provide useful Informatiom)\",\r\n \"Hard Disk space of computer (relevant provide useful Informatiom)\",\r\n \"Random axis momery of computer (relevant provide useful Informatiom)\",\r\n \"Screen size of Computer (relevant provide useful Informatiom)\",\r\n \"Compact dist (relevant provide useful Informatiom)\",\r\n \"Multipurpose use or not (relevant provide useful Informatiom)\",\r\n \"Premium Class of computer (relevant provide useful Informatiom)\",\r\n \"advertisement expenses (relevant provide useful Informatiom)\",\r\n \"Trend position in market (relevant provide useful Informatiom)\"]\r\n\r\nd_types =[\"Count\",\"Ratio\",\"Ratio\",\"Ratio\",\"Ratio\",\"Ratio\",\"Binary\",\"Binary\",\"Binary\",\"Ratio\",\"Ratio\"]\r\n\r\ndata_details =pd.DataFrame({\"column name\":computer.columns,\r\n \"data types \":d_types,\r\n \"description\":description,\r\n \"data type(in Python)\": computer.dtypes})\r\n\r\n#3.\tData Pre-computercessing\r\n#3.1 Data Cleaning, Feature Engineering, etc\r\n#details of computer \r\ncomputer.info()\r\ncomputer.describe() \r\n\r\n#droping index colunms \r\ncomputer.drop(['Unnamed: 0'], axis = 1, inplace = True)\r\n#dummy variable creation \r\nfrom sklearn.preprocessing import LabelEncoder\r\nLE = LabelEncoder()\r\ncomputer['cd'] = LE.fit_transform(computer['cd'])\r\ncomputer['multi'] = LE.fit_transform(computer['multi'])\r\ncomputer['premium'] = LE.fit_transform(computer['premium'])\r\n\r\n#data types \r\ncomputer.dtypes\r\n\r\n#checking for na value\r\ncomputer.isna().sum()\r\ncomputer.isnull().sum()\r\n\r\n#checking unique value for each columns\r\ncomputer.nunique()\r\n\"\"\"\tExploratory Data Analysis (EDA):\r\n\tSummary\r\n\tUnivariate analysis\r\n\tBivariate analysis \"\"\"\r\n \r\nEDA ={\"column \": computer.columns,\r\n \"mean\": computer.mean(),\r\n \"median\":computer.median(),\r\n \"mode\":computer.mode(),\r\n \"standard deviation\": computer.std(),\r\n \"variance\":computer.var(),\r\n \"skewness\":computer.skew(),\r\n \"kurtosis\":computer.kurt()}\r\n\r\nEDA\r\n# covariance for data set \r\ncovariance = computer.cov()\r\ncovariance\r\n\r\n# Correlation matrix \r\nco = computer.corr()\r\nco\r\n\r\n# according to correlation coefficient no correlation of Administration & State with model_dffit\r\n#According scatter plot strong correlation between model_dffit and rd_spend and \r\n#also some relation between model_dffit and m_spend.\r\n####### graphicomputer repersentation \r\n##historgam and scatter plot\r\nimport seaborn as sns\r\nsns.pairplot(computer.iloc[:, :])\r\n\r\n#boxplot for every columns\r\ncomputer.columns\r\ncomputer.nunique()\r\n\r\ncomputer.boxplot(column=['price','ads', 'trend']) #no outlier\r\n\r\n#for imputing HVO for Price column\r\n\"\"\"\r\n# here we can see lVO For Price\r\n# Detection of outliers (find limits for RM based on IQR)\r\nIQR = computer['Price'].quantile(0.75) - computer['Price'].quantile(0.25)\r\nupper_limit = computer['Price'].quantile(0.75) + (IQR * 1.5)\r\n####################### 2.Replace ############################\r\n# Now let's replace the outliers by the maximum and minimum limit\r\n#Graphical Representation\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt # mostly used for visualization purposes \r\ncomputer['Price']= pd.DataFrame( np.where(computer['Price'] > upper_limit, upper_limit, computer['Price']))\r\nimport seaborn as sns \r\nsns.boxplot(computer.Price);plt.title('Boxplot');plt.show()\"\"\"\r\n\r\n# Q-Q Plot\r\nfrom scipy import stats\r\nimport pylab\r\nimport matplotlib.pyplot as plt\r\n\r\nstats.probplot(computer.price, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n\r\nstats.probplot(computer.ads, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n\r\nstats.probplot(computer.trend, dist = \"norm\", plot = pylab)\r\nplt.show() \r\n\r\n#normal\r\n\r\n# Normalization function using z std. all are continuous data.\r\ndef norm_func(i):\r\n x = (i-i.mean())/(i.std())\r\n return (x)\r\n\r\n# Normalized data frame (considering the numerical part of data)\r\ndf_norm = norm_func(computer.iloc[:,[1,2,3,4,8,9]])\r\ndf_norm.describe()\r\n\"\"\"\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n# creating instance of one-hot-encoder\r\nenc = OneHotEncoder(handle_unknown='ignore')\r\nsta=computer.iloc[:,[3]]\r\nenc_df = pd.DataFrame(enc.fit_transform(sta).toarray())\"\"\"\r\n\r\n# Create dummy variables on categorcal columns\r\n\r\nenc_df = computer.iloc[:,[5,6,7]]\r\n\r\nmodel_df = pd.concat([enc_df, df_norm,computer.iloc[:,[0]] ], axis =1)\r\n\r\n#rename the columns\r\n\r\n\"\"\"5.\tModel Building\r\n5.1\tBuild the model on the scaled data (try multiple options)\r\n5.2\tPerform Multi linear regression model and check for VIF, AvPlots, Influence Index Plots.\r\n5.3\tTrain and Test the data and compare RMSE values tabulate R-Squared values , RMSE for different models in documentation and model_dfvide your explanation on it.\r\n5.4\tBriefly explain the model output in the documentation. \r\n\"\"\"\r\n# preparing model considering all the variables \r\nimport statsmodels.formula.api as smf # for regression model \r\nml1 = smf.ols('price ~ speed + hd + ram + screen + cd + multi + premium + ads + trend', data = model_df).fit() # regression model\r\n\r\n# Summary\r\nml1.summary()\r\n\r\n# Checking whether data has any influential values \r\n# Influence Index Plots\r\nimport statsmodels.api as sm\r\n\r\nsm.graphics.influence_plot(ml1)\r\n# Check for Colinearity to decide to remove a variable using VIF\r\n# Assumption: VIF > 10 = colinearity\r\n# calculating VIF's values of independent variables\r\n\r\nrsq_hd = smf.ols('hd ~ speed + ram + screen + cd + multi + premium + ads + trend', data = model_df).fit().rsquared \r\nvif_hd = 1/(1 - rsq_hd) \r\nvif_hd # vif is low \r\n\r\nrsq_ram = smf.ols('ram ~ speed + hd + screen + cd + multi + premium + ads + trend', data = model_df).fit().rsquared \r\nvif_ram = 1/(1 - rsq_ram) \r\nvif_ram # vif is low \r\n\r\n # by r squared value\r\nmlhd = smf.ols('hd ~ speed + ram + screen + cd + multi + premium + ads + trend', data = model_df).fit()\r\nmlhd.summary()\r\n\r\n#model 2 \r\nml2 = smf.ols('price ~ speed + ram + screen + cd + multi + premium + ads + trend', data = model_df).fit() # regression model\r\n\r\n# Summary\r\nml2.summary()\r\n\r\n#model 3 \r\nml3 = smf.ols('price ~ speed + hd + screen + cd + multi + premium + ads + trend', data = model_df).fit() # regression model\r\n# Summary\r\nml3.summary()\r\n\r\n# Final model\r\nfinal_ml = smf.ols('price ~ speed + hd + ram + screen + cd + multi + premium + ads + trend', data = model_df).fit()\r\nfinal_ml.summary() \r\nfinal_ml.summary2()\r\n# Prediction\r\npred = final_ml.predict(model_df)\r\npred\r\nfrom scipy import stats\r\nimport pylab\r\nimport statsmodels.api as sm\r\n# Q-Q plot\r\nres = final_ml.resid\r\nsm.qqplot(res)\r\nplt.show()\r\n\r\n# Q-Q plot\r\nstats.probplot(res, dist = \"norm\", plot = pylab)\r\nplt.show()\r\n\r\n# Jointplot\r\nimport seaborn as sns\r\n# Residuals vs Fitted plot\r\nsns.residplot(x = pred, y = model_df.price, lowess = True)\r\nplt.xlabel('Fitted')\r\nplt.ylabel('Residual')\r\nplt.title('Fitted vs Residual')\r\nplt.show()\r\n\r\nsm.graphics.influence_plot(final_ml)\r\n### Splitting the data into train and test data \r\nfrom sklearn.model_selection import train_test_split\r\ntrain, test = train_test_split(model_df, test_size = 0.2,random_state = 7) # 20% test data\r\n\r\n# preparing the model on train data \r\nmodel_train = smf.ols('price ~ speed + hd + ram + screen + cd + multi + premium + ads + trend', data = train).fit()\r\n\r\n# prediction on test data set \r\ntest_pred = model_train.predict(test)\r\n\r\n# test residual values \r\ntest_resid = test_pred - test.price\r\nimport numpy as np\r\n# RMSE value for test data \r\ntest_rmse = np.sqrt(np.mean(test_resid * test_resid))\r\ntest_rmse\r\n\r\n# train_data prediction\r\ntrain_pred = model_train.predict(train)\r\n\r\n# train residual values \r\ntrain_resid = train_pred - train.price\r\n# RMSE value for train data \r\ntrain_rmse = np.sqrt(np.mean(train_resid * train_resid))\r\ntrain_rmse\r\n############################# problem 3 #############################\r\nimport pandas as pd\r\n#loading the dataset\r\ntoyo = pd.read_csv(\"C:/Users/usach/Desktop/Multi Linear Regression/ToyotaCorolla.csv\", encoding =\"latin1\")\r\n\r\n#2.\tWork on each feature of the dataset to create a data dictionary as displayed in the below image\r\n#######feature of the dataset to create a data dictionary\r\n\r\ndata_details =pd.DataFrame({\"column name\":toyo.columns,\r\n \"data type(in Python)\": toyo.dtypes})\r\n\r\n#3.\tData Pre-toyocessing\r\n#3.1 Data Cleaning, Feature Engineering, etc\r\n#details of toyo \r\ntoyo.info()\r\ntoyo.describe() \r\n\r\n#droping index colunms \r\ntoyo.drop([\"Id\"], axis = 1, inplace = True)\r\n#dummy variable creation \r\nfrom sklearn.preprocessing import LabelEncoder\r\nLE = LabelEncoder()\r\ntoyo['Age_08_04'] = LE.fit_transform(toyo['Age_08_04'])\r\ntoyo['HP'] = LE.fit_transform(toyo['HP'])\r\ntoyo['cc'] = LE.fit_transform(toyo['cc'])\r\ntoyo['Doors'] = LE.fit_transform(toyo['Doors'])\r\ntoyo['Gears'] = LE.fit_transform(toyo['Gears'])\r\n\r\ndf= toyo[[\"Price\",\"Age_08_04\",\"KM\",\"HP\",\"cc\",\"Doors\",\"Gears\",\"Quarterly_Tax\",\"Weight\"]]\r\n\r\n#data types \r\ndf.dtypes\r\n#checking for na value\r\ndf.isna().sum()\r\ndf.isnull().sum()\r\n\r\n#checking unique value for each columns\r\ndf.nunique()\r\n\"\"\"\tExploratory Data Analysis (EDA):\r\n\tSummary\r\n\tUnivariate analysis\r\n\tBivariate analysis \"\"\"\r\n\r\nEDA ={\"column \": df.columns,\r\n \"mean\": df.mean(),\r\n \"median\":df.median(),\r\n \"mode\":df.mode(),\r\n \"standard deviation\": df.std(),\r\n \"variance\":df.var(),\r\n \"skewness\":df.skew(),\r\n \"kurtosis\":df.kurt()}\r\n\r\nEDA\r\n# covariance for data set \r\ncovariance = df.cov()\r\ncovariance\r\n# Correlation matrix \r\nco = df.corr()\r\nco\r\n# according to correlation coefficient no correlation of Administration & State with model_dffit\r\n#According scatter plot strong correlation between model_dffit and rd_spend and \r\n#also some relation between model_dffit and m_spend.\r\n####### graphidf repersentation \r\n##historgam and scatter plot\r\nimport seaborn as sns\r\nsns.pairplot(df.iloc[:, :])\r\n#boxplot for every columns\r\ndf.columns\r\ndf.nunique()\r\n\r\ndf.boxplot(column=['Price', 'Age_08_04', 'KM', 'HP', 'cc', 'Doors', 'Gears','Quarterly_Tax', 'Weight']) #no outlier\r\n\r\n#normal\r\n# Normalization function using z std. all are continuous data.\r\ndef norm_func(i):\r\n x = (i-i.mean())/(i.std())\r\n return (x)\r\n\r\n# Normalized data frame (considering the numerical part of data)\r\ndf = norm_func(df.iloc[:,1:9])\r\ndf.describe()\r\n\"\"\"\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n# creating instance of one-hot-encoder\r\nenc = OneHotEncoder(handle_unknown='ignore')\r\nsta=df.iloc[:,[3]]\r\nenc_df = pd.DataFrame(enc.fit_transform(sta).toarray())\"\"\"\r\n\r\n# Create dummy variables on categorcal columns\r\n\r\nmodel_df = pd.concat([df,toyo.iloc[:,[1]] ], axis =1)\r\n\r\n#rename the columns\r\n\"\"\"5.\tModel Building\r\n5.1\tBuild the model on the scaled data (try multiple options)\r\n5.2\tPerform Multi linear regression model and check for VIF, AvPlots, Influence Index Plots.\r\n5.3\tTrain and Test the data and compare RMSE values tabulate R-Squared values , RMSE for different models in documentation and model_dfvide your explanation on it.\r\n5.4\tBriefly explain the model output in the documentation. \r\n\"\"\"\r\n\r\n# preparing model considering all the variables \r\nimport statsmodels.formula.api as smf # for regression model\r\n\r\nml1 = smf.ols('Price ~ Age_08_04 + KM + HP + cc + Doors + Gears + Quarterly_Tax + Weight', data = model_df).fit() # regression model\r\n\r\n# Summary\r\nml1.summary()\r\n\r\n# Checking whether data has any influential values \r\n# Influence Index Plots\r\nimport statsmodels.api as sm\r\n\r\nsm.graphics.influence_plot(ml1)\r\n\r\nmodel_df_new = model_df.drop(model_df.index[[960,221]])\r\n#droping row num 960,221 due to outlire\r\n\r\n# Preparing model \r\nml_new = smf.ols('Price ~ Age_08_04 + KM + HP + cc + Doors + Gears + Quarterly_Tax + Weight', data = model_df_new).fit() \r\n\r\n# Summary\r\nml_new.summary()\r\n\r\n# Prediction\r\npred = ml_new.predict(model_df)\r\n# removing outlier \r\n# Final model\r\nfinal_ml = smf.ols('Price ~ Age_08_04 + KM + HP + cc + Doors + Gears + Quarterly_Tax + Weight', data = model_df_new).fit()\r\nfinal_ml.summary() \r\n\r\n# Prediction\r\npred = final_ml.predict(model_df)\r\n\r\nfrom scipy import stats\r\nimport pylab\r\nimport statsmodels.api as sm\r\nimport matplotlib.pyplot as plt\r\n# Q-Q plot residuals\r\nres = final_ml.resid\r\nsm.qqplot(res)\r\nplt.show()\r\n\r\n# Q-Q plot\r\nstats.probplot(res, dist = \"norm\", plot = pylab)\r\nplt.show()\r\n\r\n# Jointplot\r\nimport seaborn as sns\r\n# Residuals vs Fitted plot\r\nsns.residplot(x = pred, y = model_df.Price, lowess = True)\r\nplt.xlabel('Fitted')\r\nplt.ylabel('Residual')\r\nplt.title('Fitted vs Residual')\r\nplt.show()\r\n\r\nsm.graphics.influence_plot(final_ml)\r\n\r\n### Splitting the data into train and test data \r\nfrom sklearn.model_selection import train_test_split\r\npro_train, pro_test = train_test_split(model_df_new, test_size = 0.2,random_state = 77) # 20% test data\r\n\r\n# preparing the model on train data \r\nmodel_train = smf.ols('Price ~ Age_08_04 + KM + HP + cc + Doors + Gears + Quarterly_Tax + Weight', data = pro_train).fit()\r\nmodel_train.summary()\r\n# prediction on test data set \r\ntest_pred = model_train.predict(pro_test)\r\n\r\nimport numpy as np\r\n# test residual values \r\ntest_resid = test_pred - pro_test.Price\r\n# RMSE value for test data \r\ntest_rmse = np.sqrt(np.mean(test_resid * test_resid))\r\ntest_rmse\r\n# train_data prediction\r\ntrain_pred = model_train.predict(pro_train)\r\ntrain_pred\r\n# train residual values \r\ntrain_resid = train_pred - pro_train.Price\r\n# RMSE value for train data \r\ntrain_rmse = np.sqrt(np.mean(train_resid * train_resid))\r\ntrain_rmse\r\n\r\n########################## problem 4 ################################\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# loading the data\r\nAvocado_Price = pd.read_csv(\"C:/Users/usach/Desktop/Multi Linear Regression/Avacado_Price.csv\")\r\n\r\n# Exploratory data analysis:\r\n# 1. Measures of central tendency\r\n# 2. Measures of dispersion\r\n# 3. Third moment business decision\r\n# 4. Fourth moment business decision\r\n# 5. Probability distributions of variables \r\n# 6. Graphical representations (HistogTOT_AVA2, Box plot, Dot plot, Stem & Leaf plot, Bar plot, etc.)\r\n\r\nAvocado_Price.drop('type', inplace=True, axis=1)\r\nAvocado_Price.drop('year', inplace=True, axis=1)\r\nAvocado_Price.drop('region', inplace=True, axis=1)\r\n\r\nAvocado_Price.rename(columns = {'XLarge Bags': 'XLarge_Bags'}, inplace = True)\r\n\r\nAvocado_Price.describe()\r\n\r\n#Graphical Representation\r\nimport matplotlib.pyplot as plt # mostly used for visualization purposes \r\n\r\n# Total_Volume\r\nplt.bar(height = Avocado_Price.Total_Volume, x = np.arange(1, 18249, 1))\r\nplt.hist(Avocado_Price.Total_Volume) #histog\r\nplt.boxplot(Avocado_Price.Total_Volume) #boxplot\r\n\r\n# AVERAGEPRICE\r\nplt.bar(height = Avocado_Price.AveragePrice, x = np.arange(1, 18249, 1))\r\nplt.hist(Avocado_Price.AveragePrice) #histogTOT_AVA2\r\nplt.boxplot(Avocado_Price.AveragePrice) #boxplot\r\n\r\n# Jointplot\r\nimport seaborn as sns\r\nsns.jointplot(x=Avocado_Price['Total_Volume'], y=Avocado_Price['AveragePrice'])\r\n\r\n# Countplot\r\nplt.figure(1, figsize=(16, 10))\r\nsns.countplot(Avocado_Price['Total_Volume'])\r\n\r\n# Q-Q Plot\r\nfrom scipy import stats\r\nimport pylab\r\nstats.probplot(Avocado_Price.AveragePrice, dist = \"norm\", plot = pylab)\r\nplt.show()\r\n\r\n# Scatter plot between the variables along with histogTOT_AVA2s\r\nimport seaborn as sns\r\nsns.pairplot(Avocado_Price.iloc[:, :])\r\n \r\n# Correlation matrix \r\nAvocado_Price.corr()\r\n\r\n# we see there exists High collinearity between input variables especially between\r\n# [TOT_AVA2 & SP], [VOL & WT] so there exists collinearity problem\r\n\r\n# preparing model considering all the variables \r\nimport statsmodels.formula.api as smf # for regression model\r\n \r\nml1 = smf.ols('AveragePrice ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit() # regression model\r\n\r\n# Summary\r\nml1.summary()\r\n# p-values for WT, VOL are more than 0.05\r\n\r\n# Checking whether data has any influential values \r\n# Influence Index Plots\r\nimport statsmodels.api as sm\r\n\r\nsm.graphics.influence_plot(ml1)\r\n# Studentized Residuals = Residual/standard deviation of residuals\r\n# index 1043 is showing high influence so we can exclude that entire row\r\n \r\nAvocado_Price_new = Avocado_Price.drop(Avocado_Price.index[[11271]])\r\n\r\n# Preparing model \r\nml_new = smf.ols('AveragePrice ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price_new).fit() \r\n\r\n# Summary\r\nml_new.summary()\r\n\r\n# Check for Colinearity to decide to remove a variable using VIF\r\n# Assumption: VIF > 10 = colinearity\r\n# calculating VIF's values of independent variables\r\nrsq_tt = smf.ols('Total_Volume ~ tot_ava1 + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_tt= 1/(1 - rsq_tt) \r\n\r\nrsq_tot_ava1 = smf.ols('tot_ava1 ~ Total_Volume + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_tot_ava1 = 1/(1 - rsq_tot_ava1)\r\n\r\nrsq_tot_ava2 = smf.ols('tot_ava2 ~ Total_Volume + tot_ava1 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_tot_ava2 = 1/(1 - rsq_tot_ava2) \r\n\r\nrsq_tot_ava3 = smf.ols('tot_ava3 ~ Total_Volume + tot_ava1 + tot_ava2 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_tot_ava3 = 1/(1 - rsq_tot_ava3) \r\n\r\nrsq_tb = smf.ols('Total_Bags ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Small_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_tb = 1/(1 - rsq_tb) \r\n\r\nrsq_sb = smf.ols('Small_Bags ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Total_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_sb = 1/(1 - rsq_sb) \r\n\r\nrsq_lb = smf.ols('Large_Bags ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Small_Bags + Total_Bags + + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_lb = 1/(1 - rsq_lb) \r\n\r\nrsq_xl = smf.ols('XLarge_Bags ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Small_Bags + Total_Bags + Large_Bags + XLarge_Bags', data = Avocado_Price).fit().rsquared \r\nvif_xl = 1/(1 - rsq_xl) \r\n\r\n# Storing vif values in a data fTOT_AVA2e\r\nd1 = {'Variables':['Total_Volume', 'tot_ava1 + tot_ava2 ', 'tot_ava3', 'Total_Bags', 'Small_Bags', 'Large_Bags', 'XLarge_Bags'], 'VIF':[vif_tt, vif_tot_ava1, vif_tot_ava2, vif_tot_ava3, vif_tb, vif_sb, vif_lb, vif_xl]}\r\nVif_frame = pd.DataFrame(d1) \r\nVif_frame\r\n# As Large_Bags is having highest VIF value, we are going to drop this from the prediction model\r\n\r\n# Final model\r\nfinal_ml = smf.ols('AveragePrice ~ Total_Volume + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + XLarge_Bags', data = Avocado_Price).fit()\r\nfinal_ml.summary() \r\n\r\n# Prediction\r\npred = final_ml.predict(Avocado_Price)\r\npred\r\n\r\n# Q-Q plot\r\nres = final_ml.resid\r\nsm.qqplot(res)\r\nplt.show()\r\n\r\n# Q-Q plot\r\nstats.probplot(res, dist = \"norm\", plot = pylab)\r\nplt.show()\r\n\r\n# Residuals vs Fitted plot\r\nsns.residplot(x = pred, y = Avocado_Price.AveragePrice, lowess = True)\r\nplt.xlabel('Fitted')\r\nplt.ylabel('Residual')\r\nplt.title('Fitted vs Residual')\r\nplt.show()\r\n\r\nsm.graphics.influence_plot(final_ml)\r\n\r\n\r\n### Splitting the data into train and test data \r\nfrom sklearn.model_selection import train_test_split\r\nAvocado_Price_train, Avocado_Price_test = train_test_split(Avocado_Price, test_size = 0.2) # 20% test data\r\n\r\n# preparing the model on train data \r\nmodel_train = smf.ols(\"AveragePrice ~ Total_Volume + tot_ava1 + tot_ava2 + tot_ava3 + Total_Bags + Small_Bags + Large_Bags + XLarge_Bags\", data = Avocado_Price_train).fit()\r\n\r\n# prediction on test data set \r\ntest_pred = model_train.predict(Avocado_Price_test)\r\n\r\n# test residual values \r\ntest_resid = test_pred - Avocado_Price_test.AveragePrice\r\n\r\n# RMSE value for test data \r\ntest_rmse = np.sqrt(np.mean(test_resid * test_resid))\r\ntest_rmse\r\n\r\n# train_data prediction\r\ntrain_pred = model_train.predict(Avocado_Price_train)\r\n\r\n# train residual values \r\ntrain_resid = train_pred - Avocado_Price_train.AveragePrice\r\n# RMSE value for train data \r\ntrain_rmse = np.sqrt(np.mean(train_resid * train_resid))\r\ntrain_rmse\r\n" }, { "alpha_fraction": 0.6760187745094299, "alphanum_fraction": 0.7103745937347412, "avg_line_length": 38.23196792602539, "blob_id": "1511b633d7b5d177e4e9764e2fbad19995401943", "content_id": "7ebf83d3e44cfcb0230cd01e816a44b7a04270c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 20637, "license_type": "no_license", "max_line_length": 155, "num_lines": 513, "path": "/MLR.R", "repo_name": "sachin1171/Multi-linear-regression", "src_encoding": "UTF-8", "text": "############################# problem 1 ##########################\r\n# Do transformations for getting better predictions of profit and \r\n# make a table containing R^2 value for each prepared model.\r\n\r\n# Loading the data\r\nopt_profit<-read.csv(file.choose())\r\nView(opt_profit)\r\nsummary(opt_profit)\r\nstr(opt_profit)\r\n# Defining State as a factor\r\nopt_profit$State<-factor(opt_profit$State,levels=c('New York','California','Florida'), labels=c(1,2,3))\r\nstr(opt_profit)\r\ninstall.packages(\"moments\")\r\nlibrary(moments)\r\ninstall.packages(\"lattice\")\r\nlibrary(lattice)\r\nattach(opt_profit)\r\n# Understanding data of R.D. Spend\r\nskewness(R.D.Spend)\r\nkurtosis(R.D.Spend)\r\ndotplot(R.D.Spend)\r\nhist(R.D.Spend)\r\nqqnorm(R.D.Spend)\r\nqqline(R.D.Spend)\r\nboxplot(R.D.Spend)\r\n# R.D. Spend does not exactly follow the normal distribution.\r\n# Mean is greater than median and skewness is +ve. It indicates positively skewed distributed\r\n# However, there is no outliers as evident from the boxplot.\r\n\r\n# Understanding data of Administration\r\nskewness(Administration)\r\nkurtosis(Administration)\r\ndotplot(Administration)\r\nhist(Administration)\r\nqqnorm(Administration)\r\nqqline(Administration)\r\nboxplot(Administration)\r\n# This is a negative skewed distributed with -ve skewness. Mean is lower than median value.\r\n# However,there is no outliers\r\n\r\n# Understanding Marketing Spend\r\nskewness(Marketing.Spend)\r\nkurtosis(Marketing.Spend)\r\ndotplot(Marketing.Spend)\r\nhist(Marketing.Spend)\r\nqqnorm(Marketing.Spend)\r\nqqline(Marketing.Spend)\r\nboxplot(Marketing.Spend)\r\n# This is negative skewed distributed with negative skewness.\r\n# Median is more than mean which also indicates that it is -ve skewed distributed.\r\n# There is no outlier exists\r\n# Understanding the output -Profit\r\nskewness(Profit)\r\nkurtosis(Profit)\r\ndotplot(Profit)\r\nhist(Profit)\r\nqqnorm(Marketing.Spend)\r\nqqline(Marketing.Spend)\r\nboxplot(Profit)\r\n# Profit is positive skewed distributed with mean greater than median.\r\n# There is no outlier in it\r\n\r\n# Relationship of output Profit with other variables & relation among all input variables\r\npairs(opt_profit)\r\ncor(opt_profit[,-4])\r\n# It indicates that there is a strong correlation i.e. 0.97 between R.D.Spend and Profit\r\n# There is a moderate correlation i.e. 0.75 between Marketing Spend and Profit\r\n# There is a moderate correlation i.e. 0.72 between R.D.Spend and Marketing Spend\r\n# State and Administration do not have any effect on profit or any other variables\r\n\r\n# Building Model of Profit with input variables\r\nlibrary(caTools)\r\nmodel1<-lm(Profit~.,data=opt_profit)\r\nsummary(model1)\r\nplot(model1)\r\n# R^2 is 0.95 which is Excellent\r\n# R.D.Spend is found to be significant and others are found to be insignificant\r\n# Check colinearity among input variables\r\ninstall.packages(\"car\")\r\nlibrary(car)\r\ninstall.packages(carData)\r\nlibrary(carData)\r\ncar::vif(model1)\r\n# VIF values for all variables are found to be less than 10- No colinearity\r\nlibrary(MASS)\r\nstepAIC(model1)\r\n# AIC values were found to be reducing in absence of State and Administration.\r\n# Therefore, these two variables are not significant\r\nresidualPlots(model1)\r\navPlots(model1)\r\nqqPlot(model1)\r\n# There is no trend found in residual plots\r\n# R.D.Spend & Marketing Spend found to have contributions to prediction of Profit\r\n# First Iteration (Removal of State)\r\nmodel2<-lm(Profit~R.D.Spend+Administration+Marketing.Spend,data=opt_profit)\r\nsummary(model2)\r\n# Second Iteration (Removal of Administration)\r\nmodel3<-lm(Profit~R.D.Spend+Marketing.Spend,data=opt_profit)\r\nsummary(model3)\r\n# Third Iteration (Removal of Marketing Spend)\r\nmodel4<-lm(Profit~R.D.Spend,data=opt_profit)\r\nsummary(model4)\r\n# Since there is a decrease in R^2 value by not considering the Marketing Spend.\r\n# Moreover this is also significant at 90% significance level\r\n# Therefore, let's consider both the variables\r\nmodel5<-lm(Profit~R.D.Spend+Marketing.Spend, data=opt_profit)\r\nsummary(model5)\r\nplot(model5)\r\npred<-predict(model5,interval=\"predict\")\r\npred1<-data.frame(pred)\r\ncor(pred1$fit,opt_profit$Profit)\r\nplot(pred1$fit,opt_profit$Profit)\r\n# Correlation between predicted and actual found to be strong i.e. 0.97\r\n# For further improvement in the model, we can check data points influencing the model\r\ninfluenceIndexPlot(model5)\r\n# We have observed the data point 50 is above limits in Diagnosis plots.\r\n# We can make the model by eliminating the influencing data point 50\r\nmodel6<-lm(Profit~R.D.Spend+Marketing.Spend, data=opt_profit[-50,])\r\nsummary(model6)\r\n# R^2 value has improved to 0.96\r\n# Calculation of RMSE\r\nsqrt(sum(model5$residuals^2)/nrow(opt_profit))\r\n\r\nmodel_R_Squared_values <- list(model=NULL,R_squared=NULL,RMSE=NULL)\r\nmodel_R_Squared_values[[\"model\"]] <- c(\"model1\",\"model2\",\"model3\",\"model4\",\"model5\",\"model6\")\r\nmodel_R_Squared_values[[\"R_squared\"]] <- c(0.95,0.95,0.95,0.94,0.95,0.96)\r\nmodel_R_Squared_values[[\"RMSE\"]]<-c(9439,9232,9161,9416,9161,7192)\r\nFinal <- cbind(model_R_Squared_values[[\"model\"]],model_R_Squared_values[[\"R_squared\"]],model_R_Squared_values[[\"RMSE\"]])\r\nView(model_R_Squared_values)\r\nView(Final)\r\n# Final model is as given below :\r\nfinal_model<-lm(Profit~R.D.Spend+Marketing.Spend, data=opt_profit[-50,])\r\nsummary(final_model)\r\npred<-predict(final_model,interval=\"predict\")\r\npred1<-data.frame(pred)\r\npred1\r\ncor(pred1$fit,opt_profit[-50,]$Profit)\r\nplot(pred1$fit,opt_profit[-50,]$Profit)\r\n# Final model gives R^2 value 0.96 and correlation with fitting value as 0.98\r\n\r\n######################## problem 2 ###########################\r\ninstall.packages(\"readr\")\r\nlibrary(readr)\r\nComputer_Data <- read.csv(file.choose())\r\nView(Computer_Data)\r\ncom <- Computer_Data[,-1]\r\nView(com)\r\nattach(com)\r\n\r\ncom$cd <- as.integer(factor(com$cd, levels = c(\"yes\", \"no\"), labels = c(1, 0)))\r\ncom$multi <- as.integer(factor(com$multi, levels = c(\"yes\", \"no\"), labels = c(1, 0)))\r\ncom$premium <- as.integer(factor(com$premium, levels = c(\"yes\", \"no\"), labels = c(1, 0)))\r\nView(com)\r\nattach(com)\r\n\r\nstr(com)\r\nsummary(com) #1st business decision\r\ninstall.packages(\"psych\")\r\nlibrary(psych)\r\ndescribe(com) #2nd business decision\r\nplot(com)\r\npairs(com)\r\ninstall.packages(\"GGally\")\r\nlibrary(GGally)\r\ninstall.packages(\"ggplot2\")\r\nlibrary(ggplot2)\r\nggplot(data=com)+geom_histogram(aes(x=price,),bin=40)\r\n\r\n#Mutiple Linear Regression\r\nmodel_com1 <- lm(com$price~.,data = com)\r\nsummary(model_com1) #R^2=0.7756\r\nrmse1 <- sqrt(mean(model_com1$residuals^2))\r\nrmse1 #RMSE=275.1298\r\npred1 <- predict(model_com1, newdata = com)\r\ncor(pred1, com$price) #Accuracy=0.8806631\r\nvif(model_com1)\r\navPlots(model_com1)\r\ninfluenceIndexPlot(model_com1, grid = T, id = list(n=10, cex=1.5, col=\"blue\"))\r\ninfluence.measures(model_com1)\r\ninfluencePlot(model_com1)\r\nqqPlot(model_com1)\r\n\r\n#Removing influencing Observations\r\nmodel_com2 <- lm(price~., data = com[-c(1441, 1701),])\r\nsummary(model_com2) #R^2=0.7777\r\nrmse2 <- sqrt(mean(model_com2$residuals^2))\r\nrmse2 #RMSE=272.8675\r\npred2 <- predict(model_com2, newdata = com)\r\nvif(model_com2)\r\ncor(pred2, com$price) #Accuracy=0.8806566\r\navPlots(model_com2)\r\nqqPlot(model_com2)\r\n\r\n#Applying Logarithmic Transformation\r\nx <- log(com[, -1])\r\nlog_com <- data.frame(com[,1], x)\r\ncolnames(log_com)\r\nattach(log_com)\r\nView(log_com)\r\nmodel_com3 <- lm(com...1.~speed+hd+ram+screen+cd+multi+premium+ads+trend, data=log_com)\r\nsummary(model_com3) #R^2=0.7426\r\nrmse3 <- sqrt(mean(model_com3$residuals^2))\r\nrmse3 #RMSE=294.653\r\npred3 <- predict(model_com3, newdata = log_com)\r\ncor(pred3, log_com$com...1.) #Accuracy=0.8617343\r\nvif(model_com3)\r\navPlots(model_com3)\r\nqqPlot(model_com3)\r\ninfluenceIndexPlot(model_com3, grid = T, id = list(n=10, cex=1.5, col=\"blue\"))\r\ninfluence <- as.integer(rownames(influencePlot(model_com3, grid = T, id = list(n=10, cex=1.5, col=\"blue\"))))\r\ninfluence\r\n\r\n#Log Transformation with Removing Influencial Observations\r\nmodel_com4 <- lm(com...1.~speed+hd+ram+screen+cd+multi+premium+ads+trend, data = log_com[-c(1441, 1701)])\r\nsummary(model_com4) #R^2=0.7426\r\nrmse4 <- sqrt(mean(model_com4$residuals^2))\r\nrmse4 #RMSE=294.653\r\npred4 <- predict(model_com4, newdata = log_com)\r\ncor(pred4, log_com$com...1.) #Accuracy=0.8617343\r\navPlots(model_com4)\r\nqqPlot(model_com4)\r\n\r\n#model_com2 has the best model with high R^2 value and less RMSR\r\nplot(model_com2)\r\n\r\n############################ problem 3############################\r\n# Loading the data\r\nToyota_Corolla<-read.csv(file.choose())\r\nView(Toyota_Corolla)\r\nToyota_Corolla1<-Toyota_Corolla[,-c(1,2)]\r\nView(Toyota_Corolla1)\r\nstr(Toyota_Corolla1)\r\nsummary(Toyota_Corolla1)\r\n# It shows that cylinder is constant, which does not give any variance.\r\n# The variable cylinder can be eliminated from the data set for analysis\r\nToyota_Corolla2<-Toyota_Corolla1[,-6]\r\nView(Toyota_Corolla2)\r\n# Check for correlation between output and input variables among all input variables\r\npairs(Toyota_Corolla2)\r\ncor(Toyota_Corolla2)\r\n# There is a negative strong correlation found between price and age(-0.876)\r\n# There is a negative moderate correlation found between price and km(-0.57)\r\n# There is a positive correlation found between price and weight(0.58)\r\n# There is a positive correlation between age and km (0.50)\r\nattach(Toyota_Corolla2)\r\nmodel1<-lm(Price ~. , data=Toyota_Corolla2)\r\nsummary(model1)\r\n# R^2 value is observed 0.86 and Door variable was found insignificant\r\nplot(model1)\r\n\r\ninstall.packages(\"car\")\r\nlibrary(car)\r\ncar::vif(model1)\r\n# VIF values are found to be less than 10. There is no Collinearity observed.\r\nlibrary(MASS)\r\nstepAIC(model1)\r\n# AIC value decreases by removing the insignificant variable i.e. Door\r\nresidualPlots(model1)\r\navPlots(model1)\r\nqqPlot(model1)\r\nsqrt(sum(model1$residuals^2)/nrow(Toyota_Corolla2))\r\n\r\n# QQ Plot looks to be normal.Residual plot of Age is showing a trend\r\nmodel2<-lm(Price ~ Age_08_04+I(Age_08_04^2)+KM+HP+Gears+Weight, data=Toyota_Corolla2)\r\nsummary(model2)\r\n# R^2 value improved to 0.88\r\n# All the variables are found to be significant\r\nplot(model2)\r\nresidualPlots(model2)\r\navPlots(model2)\r\nqqPlot(model2)\r\nsqrt(sum(model2$residuals^2)/nrow(Toyota_Corolla2))\r\n\r\n# Trend was found in HP variable in the residual plot\r\n# model was further improved by adding HP^2\r\nmodel3<-lm(Price ~ Age_08_04+I(Age_08_04^2)+KM+HP+I(HP^2)+Gears+Weight, data=Toyota_Corolla2)\r\nsummary(model3)\r\nplot(model3)\r\nresidualPlots(model3)\r\navPlots(model3)\r\nqqPlot(model3)\r\n# No trend is observed in residual plot\r\n# But Data points 222 & 602 are found out of the normal plot.\r\n# These data points can be verified in Diagnosis plots\r\ninfluenceIndexPlot(model3)\r\nsqrt(sum(model3$residuals^2)/nrow(Toyota_Corolla2))\r\n\r\n# 222 & 602 data points also observed in cooks' distance plot\r\n# These two influencing points can be removed from the model\r\nmodel4<-lm(Price ~ Age_08_04+I(Age_08_04^2)+KM+HP+I(HP^2)+Gears+Weight,\r\n data=Toyota_Corolla2[-c(222,602),])\r\nsummary(model4)\r\n# R^2 value improved to 0.89\r\nplot(model4)\r\nresidualPlots(model4)\r\navPlots(model4)\r\nqqPlot(model4)\r\ninfluenceIndexPlot(model4)\r\nsqrt(sum(model4$residuals^2)/nrow(Toyota_Corolla2[-c(222,602),]))\r\n\r\n# Trend was observed in KM residual plot and\r\n# some influencing data points were identified\r\nmodel5<-lm(Price ~ Age_08_04+I(Age_08_04^2)+KM+HP+I(HP^2)+Gears+Weight+I(Weight^2),\r\n data=Toyota_Corolla2[-c(148,192,193,222,602,961,524),])\r\nsummary(model5)\r\nplot(model5)\r\nresidualPlots(model5)\r\navPlots(model5)\r\nqqPlot(model5)\r\ninfluenceIndexPlot(model5)\r\nsqrt(sum(model5$residuals^2)/nrow(Toyota_Corolla2[-c(148,192,193,222,602,961,524),]))\r\n# No residual trend observed.\r\n# It is found to be normal in Q-Q Plot\r\n# R^2 is found to be improved to 0.9 and all the input variables are found to be significant.\r\nmodel_R_Squared_RMSE_values <- list(model=NULL,R_squared=NULL,RMSE=NULL)\r\nmodel_R_Squared_RMSE_values[[\"model\"]] <- c(\"model1\",\"model2\",\"model3\",\"model4\",\"model5\")\r\nmodel_R_Squared_RMSE_values[[\"R_squared\"]] <- c(0.86,0.88,0.87,0.89,0.90)\r\nmodel_R_Squared_RMSE_values[[\"RMSE\"]]<-c(1342,1240,1258,1195,1112)\r\nfinal_model <- cbind(model_R_Squared_RMSE_values[[\"model\"]],model_R_Squared_RMSE_values[[\"R_squared\"]],model_R_Squared_RMSE_values[[\"RMSE\"]])\r\nView(model_R_Squared_RMSE_values)\r\nView(final_model)\r\n# Final model is as given below :\r\nfinal_model<-lm(Price ~ Age_08_04+I(Age_08_04^2)+KM+HP+I(HP^2)+Gears+Weight+I(Weight^2),\r\n data=Toyota_Corolla2[-c(148,192,193,222,602,961,524),])\r\npred<-predict(final_model,interval=\"predict\")\r\npred1<-data.frame(pred)\r\npred1\r\nToyota_Corolla3<-Toyota_Corolla2[-c(148,192,193,222,602,961,524),]\r\ncor(pred1$fit,Toyota_Corolla3$Price)\r\n# Since there is a consistent value in R^2 and all the variables are significant, We can take it as final model\r\n# R-Square value is 0.90 and Correlation between fitting value with price is 0.95\r\n######################## problem 4#####################\r\n#load the dataset\r\nav_ds <- read.csv(file.choose())\r\nav_ds$X <- NULL #This auto created column, we don't required this\r\nhead(av_ds)\r\n\r\nlibrary(anytime)\r\n#Convert Date to date\r\nav_ds$Date <- anydate(av_ds$Date)\r\nstr(av_ds)\r\n#Dependant Variable : AveragePrice, since this is continous variable so start with MLR\r\n#Step 1: Model Validation: HOLD OUT, divide the data into train and test data, and create model on train_data\r\nlibrary(caret)\r\n#Loading required package: lattice\r\n## Loading required package: ggplot2\r\nindex <- createDataPartition(av_ds$AveragePrice, p=0.8, list = F)\r\ntrain_data <- av_ds[index,]\r\ntest_data <- av_ds[-index,]\r\n\r\nav_model_train <- lm(AveragePrice~Total_Volume+tot_ava1+tot_ava2+tot_ava3+Total_Bags+Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#removing the insignificant variable one by one and re-run the model again\r\nav_model_train <- lm(AveragePrice~tot_ava1+tot_ava2+tot_ava3+Total_Bags+Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#removing the insignificant variable one by one and re-run the model again\r\nav_model_train <- lm(AveragePrice~tot_ava2+tot_ava3+Total_Bags+Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#removing the insignificant variable one by one and re-run the model again\r\nav_model_train <- lm(AveragePrice~tot_ava3+Total_Bags+Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#removing the insignificant variable one by one and re-run the model again\r\nav_model_train <- lm(AveragePrice~Total_Bags+Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#removing the insignificant variable one by one and re-run the model again\r\nav_model_train <- lm(AveragePrice~Small_Bags+Large_Bags+XLarge.Bags+type+year+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#some region factor levels are not significant but then also we keep this factor, because it also contains the significant levels\r\nsummary(av_model_train)\r\n\r\n#Now all the variables are significant\r\n#Step 2 : Check for MultiColinearity\r\nlibrary(car)\r\n## Loading required package: carData\r\nvif(av_model_train)\r\n\r\n#From the Output above, Date and year are insignificant variables, first remove the variable with highest vif value that is year and re-run the model\r\nav_model_train <- lm(AveragePrice~Large_Bags+XLarge.Bags+type+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#Re-Run Step 2 : Check for MultiColinearity\r\nvif(av_model_train)\r\n\r\n#Create the fitted and resi variables in train_data\r\ntrain_data$fitt <- round(fitted(av_model_train),2)\r\ntrain_data$resi <- round(residuals(av_model_train),2)\r\nhead(train_data)\r\n\r\n#Step 3 : Checking the normality of error i.e. resi column from train_data\r\n#There are 2 ways of doing this, as below :\r\n#(a)lillieTest from norTest() package\r\ninstall.packages(\"nortest\")\r\nlibrary(nortest)\r\nlillie.test(train_data$resi) #We have to accept H0: it is normal\r\n\r\n#But from o/p this is not normal\r\n#(b)qqplot\r\nqqnorm(train_data$resi)\r\nqqline(train_data$resi, col = \"green\")\r\n\r\n\r\n#From graph also this is not normal\r\n#For MLR model error must be normal, lets do some trnsformaation ton achieve this\r\n#Step 4 : Check for Influencing data in case on non- normal error\r\n#4.(a)\r\ninflu <- influence.measures(av_model_train)\r\n#influ\r\n#check for cook.d column and if any value > 1 then remove that value and re-run the model\r\n#4.(b)\r\ninfluencePlot(av_model_train, id.method = \"identical\", main = \"Influence Plot\", sub = \"Circle size\")\r\n## Warning in plot.window(...): \"id.method\" is not a graphical parameter\r\n## Warning in plot.xy(xy, type, ...): \"id.method\" is not a graphical parameter\r\n## Warning in axis(side = side, at = at, labels = labels, ...): \"id.method\" is\r\n## not a graphical parameter\r\n\r\n## Warning in axis(side = side, at = at, labels = labels, ...): \"id.method\" is\r\n## not a graphical parameter\r\n## Warning in box(...): \"id.method\" is not a graphical parameter\r\n## Warning in title(...): \"id.method\" is not a graphical parameter\r\n## Warning in plot.xy(xy.coords(x, y), type = type, ...): \"id.method\" is not a\r\n## graphical parameter\r\n\r\n#from plot 5486 index data is influencing\r\n#Remove 5486 index data from the data set and re-run the model\r\ntrain_data$fitt <- NULL\r\ntrain_data$resi <- NULL\r\ntrain_data <- train_data[-(5485),]\r\n\r\n\r\nav_model_train <- lm(AveragePrice~Large_Bags+XLarge.Bags+type+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\ntrain_data$fitt <- round(fitted(av_model_train),2)\r\ntrain_data$resi <- round(residuals(av_model_train),2)\r\nhead(train_data)\r\n\r\n#Repeat 4.(b)\r\ninfluencePlot(av_model_train, id.method = \"identical\", main = \"Influence Plot\", sub = \"Circle size\")\r\n\r\n#Step 5 : Check for Heteroscadicity, H0 : error are randomly spread, we have to accept H0, i.e p-value must be > than 0.05\r\n#(a)plot\r\nplot(av_model_train)\r\n\r\n#5.(b) ncvTest\r\nncvTest(av_model_train, ~Large_Bags+XLarge.Bags+type+region)\r\n## Non-constant Variance Score Test \r\n## Variance formula: ~ Date + Large.Bags + XLarge.Bags + type + region \r\n## Chisquare = 3401.212 Df = 57 p = 0\r\n# p = 0 it means there is problem of heteroscadicity \r\n#Since error are not normal and there is issue of Heteroscadicity, we can transform the dependent variable and this may be resolve these issues.\r\n#take log of Y varibale and re-run the model\r\n\r\ntrain_data$fitt <- NULL\r\ntrain_data$resi <- NULL\r\ntrain_data$AveragePrice <- log(train_data$AveragePrice)\r\n\r\nav_model_train <- lm(AveragePrice~Large_Bags+XLarge.Bags+type+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#Check again, repeat Step 3 again:\r\nlillie.test(train_data$resi)\r\n\r\nqqnorm(train_data$resi)\r\nqqline(train_data$resi, col = \"green\")\r\n\r\n\r\n#Still error are not normal\r\nncvTest(av_model_train, ~Large_Bags+XLarge.Bags+type+region)\r\n## Non-constant Variance Score Test \r\n## Variance formula: ~ Date + Large.Bags + XLarge.Bags + type + region \r\n## Chisquare = 2346.56 Df = 57 p = 0\r\n#Still there is issue of Heteroscadicity\r\n#Now re-run the model and re-run the model implementation steps done above.\r\nav_model_train <- lm(AveragePrice~Large_Bags+XLarge.Bags+type+region, data = train_data)\r\nsummary(av_model_train)\r\n\r\n#Checking the Nomality of error again\r\ntrain_data$fitt <- fitted(av_model_train)\r\ntrain_data$resi <- residuals(av_model_train)\r\n\r\nlillie.test(train_data$resi) #way 1\r\n\r\n#Again H0, ois rejected, and errors are not normal again after the transformation\r\nqqnorm(train_data$resi) #way 2\r\nqqline(train_data$resi, col = \"green\")#way 2\r\n\r\n\r\n#Lest Check the stability of Model using RMSE of Train and Test Data\r\nlibrary(ModelMetrics)\r\ntest_data$AveragePrice <- log(test_data$AveragePrice)\r\ntest_data$fitt <- predict(av_model_train, test_data)\r\ntest_data$resi <- test_data$AveragePrice - test_data$fitt\r\n\r\nhead(test_data)\r\nhead(train_data)\r\n\r\nRMSE_train <- RMSE(train_data$AveragePrice, train_data$fitt)\r\nRMSE_test <- RMSE(test_data$AveragePrice, test_data$fitt)\r\n\r\ncheck_stability <- paste0( round((RMSE_test - RMSE_train)*100,2),\" %\")\r\n\r\nRMSE_train\r\nRMSE_test\r\n\r\ncheck_stability \r\n# Since the Difference between Test and Train RMSE is less than 10%, so that the model is stable, but not linear acceptable model.\r\n# To make the model Good, we require add more VARIABLES or PREDICTORS, so that the Adjusted R square value must be above 65% or .65" } ]
2
JrMasterno1/Python-project-sym-a-pix-fill-a-pix
https://github.com/JrMasterno1/Python-project-sym-a-pix-fill-a-pix
84da8713350091af0a51850cbb7bff94ea321eaa
8962c3ebfd480b6ea5c590d8045884d0f76da071
e16eeccce2c9342b6a9a12a12182fd8109e5d48d
refs/heads/master
2021-12-12T16:57:42.373608
2017-02-04T16:11:56
2017-02-04T16:11:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4467353820800781, "alphanum_fraction": 0.5025773048400879, "avg_line_length": 32.25714111328125, "blob_id": "f6a4ae00bc21067119a1b788bd464206707ec109", "content_id": "cc151d415566fd019a24bfd44c295e5b94240ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/sym-a-pix_tests/misc_tests.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy.testing import assert_array_equal\nimport unittest\nimport common.misc as cm\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass TestGetUnique(unittest.TestCase):\n \"\"\"Tests for getting unique points from point list\"\"\"\n\n def setUp(self):\n self.lists = [[[1, 2], [2, 3], [1, 2], [2, 3]],\n [[1], [1], [1], [1], [1]],\n []]\n self.answers = [np.array([[1, 2], [2, 3]]).transpose(), np.array([[1]]), np.array([])]\n\n def test(self):\n for l, a in zip(self.lists, self.answers):\n assert_array_equal(cm.get_unique(l), a)\n\n\nclass TestSymmetricPoint(unittest.TestCase):\n \"\"\"Tests for finding symmetric point\"\"\"\n\n def setUp(self):\n self.walls = [[3, 5], [2, 7], [0, 3], [3, 3], [0, 3], [0, 7], [0, 9]]\n self.dots = [[2, 4], [2, 3], [5, 6], [2, 2], [2, 3], [0, 8], [0, 8]]\n self.answers = [(1, 3), (2, -1), (10, 9), (1, 1), (4, 3), (0, 9), (0, 7)]\n\n def test(self):\n \"\"\"Different dots.\"\"\"\n for d, w, a in zip(self.walls, self.dots, self.answers):\n self.assertEqual(cm.symmetric_point(w[0], w[1], d[0], d[1]), a)\n" }, { "alpha_fraction": 0.638059675693512, "alphanum_fraction": 0.641791045665741, "avg_line_length": 21.33333396911621, "blob_id": "6ddc5dbb37c44886c74436e116833f531c3fcc84", "content_id": "303391cd9e332c063eabf444f1054fab10f27b6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/puzzles.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Project created for \"Programming in Python\" Class.\nSym-a-pix and fill-a-pix puzzle solver and generator.\n\"\"\"\n\nfrom gui.main_window import main_window\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\nif __name__ == '__main__':\n main_window()\n" }, { "alpha_fraction": 0.5406976938247681, "alphanum_fraction": 0.5736433863639832, "avg_line_length": 26.157894134521484, "blob_id": "fae0369a958b0c98892fb98300c7c03e3f0d70ec", "content_id": "613a1261db518414585e4b890268221fdc41fc16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 88, "num_lines": 38, "path": "/classifiers/numberrecognition.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Classifier builder.\n Gets images from folders with names corresponding to category (100 is empty square).\n Images are not included in this repository.\n Uses SVM.\n\"\"\"\n\nimport glob\nimport pickle\nimport numpy as np\n\nimport cv2\nfrom sklearn.svm import SVC\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nif __name__ == '__main__':\n # directory containing training data\n data_dir = '../../numbers/'\n\n dirs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '100']\n\n images = []\n labels = []\n for d in dirs:\n for y in sorted(glob.glob(data_dir + d + '/*')):\n img = cv2.imread(y, cv2.IMREAD_GRAYSCALE)\n img = img[:-2, :]\n img = cv2.resize(img, (15, 15))\n images.append(img)\n labels.append(int(d))\n images = np.array(images).reshape((len(labels), -1))\n labels = np.array(labels)\n classifier = SVC(gamma=0.00001)\n classifier.fit(images, labels)\n pickle.dump(classifier, open('digit_clf.p', 'wb'), protocol=2)\n" }, { "alpha_fraction": 0.5844421982765198, "alphanum_fraction": 0.5941658020019531, "avg_line_length": 33.28070068359375, "blob_id": "3b002eeb55639a469327e2baf96f538051c9dfaf", "content_id": "1a290506f3f90490c6e98c99fb0c26c2694a5b05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1954, "license_type": "no_license", "max_line_length": 113, "num_lines": 57, "path": "/fillapix/imageops/reader.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Fill-a-pix: Processing operation on images - reading puzzle from image.\n\"\"\"\n\nimport cv2\n\nfrom common.imageops import get_line_positions\nfrom fillapix.puzzle.container import Container\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass FillAPixReader:\n \"\"\"Reader for fill-a-pix puzzle.\"\"\"\n def __init__(self, filename):\n \"\"\" Reads puzzle from picture.\n :param filename: name of file with image of puzzle.\n :return: None\n \"\"\"\n self.img_rgb = cv2.imread(str(filename), cv2.IMREAD_COLOR)\n if self.img_rgb is None:\n raise IOError('File not found')\n self.img_gray = cv2.cvtColor(self.img_rgb, cv2.COLOR_BGR2GRAY)\n self.img_edges = None\n self.rho_vertical = []\n self.rho_horizontal = []\n\n def create_puzzle(self):\n \"\"\"\n Creates new puzzle. Detects lines on image, cuts image along them and passes smaller images to container.\n :return: puzzle\n \"\"\"\n self.rho_horizontal, self.rho_vertical = get_line_positions(self.img_gray, 150)\n puzzle = Container((len(self.rho_horizontal) - 1, len(self.rho_vertical) - 1))\n\n for i in range(len(self.rho_horizontal) - 1):\n for j in range(len(self.rho_vertical) - 1):\n puzzle.insert(self.cut_image(i, j), i, j)\n return puzzle\n\n def cut_image(self, x, y):\n \"\"\" Cuts part of an image depending on position of lines.\n :param x: position\n :param y: position\n :return: part of an image\n \"\"\"\n img = self.img_gray[2 + self.rho_horizontal[x]: self.rho_horizontal[x + 1],\n 2 + self.rho_vertical[y]: self.rho_vertical[y + 1] - 1]\n return img\n\n def get_lines(self):\n \"\"\"\n Returns number of lines (size of a picture).\n :return: number of lines of both types.\n \"\"\"\n return len(self.rho_horizontal), len(self.rho_vertical)\n" }, { "alpha_fraction": 0.5442083477973938, "alphanum_fraction": 0.562714159488678, "avg_line_length": 32.15909194946289, "blob_id": "928ae35233300f488f8484f54b13b4c443e4f172", "content_id": "01c62980f7844fcd8b8c587d6f47e309a730c7d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1459, "license_type": "no_license", "max_line_length": 88, "num_lines": 44, "path": "/classifiers/circle_recognition.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Classifier builder.\n Gets images from folders with names corresponding to category (100 is empty square).\n Images are not included in this repository.\n Uses SVM.\n\"\"\"\n\nimport glob\nimport os\nimport pickle\n\nimport cv2\nimport numpy as np\nfrom sklearn.svm import SVC\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\nif __name__ == '__main__':\n # directory containing training data\n data_dir = '../../classes/'\n\n dirs = ['horiz', 'sq', 'vert', 'x']\n dirs_label = ['_empty', '_circle']\n labels = [0, 1]\n\n for d in dirs:\n images = []\n labels = []\n empty_size = len([name for name in os.listdir(data_dir + d + dirs_label[0])])\n circle_size = len([name for name in os.listdir(data_dir + d + dirs_label[1])])\n sample = np.random.choice(int(empty_size), int(2 * empty_size))\n for l, dl in enumerate(dirs_label):\n for i, y in enumerate(sorted(glob.glob(data_dir + d + dl + '/*'))):\n if l == 1 or l == 0 and i in sample:\n img = cv2.imread(y, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (20, 20))\n images.append(img)\n labels.append(l)\n images = np.array(images).reshape((len(labels), -1))\n labels = np.array(labels)\n classifier = SVC(gamma=0.00001)\n classifier.fit(images, labels)\n pickle.dump(classifier, open(d + 'clf.p', 'wb'), protocol=2)\n" }, { "alpha_fraction": 0.3175267279148102, "alphanum_fraction": 0.4556020498275757, "avg_line_length": 36.73684310913086, "blob_id": "3e9dc0c449c903cccc64d8415c0529a01d1cdf2f", "content_id": "0677b4f6b05aa79ab9dfb52d8305fc7d7f6909c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2151, "license_type": "no_license", "max_line_length": 81, "num_lines": 57, "path": "/sym-a-pix_tests/solver_tests.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "import unittest\nimport numpy as np\n\nfrom symapix.solver.solver import SymAPixSolver\nfrom common.misc import symmetric_point\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass TestContainsDot(unittest.TestCase):\n \"\"\"Tests for checking if there is dot or part of dot in square.\"\"\"\n def setUp(self):\n self.solver = SymAPixSolver(None)\n self.arr = np.array([[0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1],\n [1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 1]])\n\n def test_corner(self):\n self.solver.set_puzzle(self.arr)\n txt = ''\n for i in range(0, self.arr.shape[0], 2):\n for j in range(0, self.arr.shape[1], 2):\n txt += str(int(self.solver.contains_dot(i, j)))\n txt += '\\n'\n answer = '0111\\n1111\\n0111\\n1111\\n'\n self.assertEqual(txt, answer)\n\n\nclass TestIsInside(unittest.TestCase):\n \"\"\"Test for checking if point is inside.\"\"\"\n def setUp(self):\n self.solver = SymAPixSolver(None)\n self.arr = np.array([[0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1],\n [1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 1]])\n\n def test_inside(self):\n self.solver.set_puzzle(self.arr)\n txt = ''\n for i in range(-3, 10):\n for j in range(-3, 10):\n txt += '1' if self.solver.is_inside(i, j) else '0'\n txt += '\\n'\n answer = '0000000000000\\n0000000000000\\n0000000000000\\n0001111111000' \\\n '\\n0001111111000\\n0001111111000\\n0001111111000\\n0001111111000' \\\n '\\n0001111111000\\n0001111111000\\n0000000000000\\n0000000000000' \\\n '\\n0000000000000\\n'\n self.assertEqual(txt, answer)\n" }, { "alpha_fraction": 0.6051103472709656, "alphanum_fraction": 0.6062718033790588, "avg_line_length": 27.700000762939453, "blob_id": "b3c83f9439b7bd54d9f0f6da97b78268bfc7e801", "content_id": "3cf995ed4c053251c505c37370a341aba8e1b285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "no_license", "max_line_length": 83, "num_lines": 30, "path": "/classifiers/classifier.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Manages classifier files.\n\"\"\"\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\ndef get(classifier):\n \"\"\"\n Gives SVM classifier file, depending on name.\n :param classifier: name of classifier: [digit, horizontal, vertical, square, x]\n :return: classifier file\n \"\"\"\n if classifier == 'digit':\n return open('classifiers/digit_clf.p', 'rb')\n elif classifier == 'horizontal':\n return open('classifiers/horizclf.p', 'rb')\n elif classifier == 'vertical':\n return open('classifiers/vertclf.p', 'rb')\n elif classifier == 'square':\n return open('classifiers/sqclf.p', 'rb')\n elif classifier == 'x':\n return open('classifiers/xclf.p', 'rb')\n else:\n print('No such classifier: {}'.format(classifier))\n\n\nif __name__ == '__main__':\n print('Use get(classifier) function.')\n" }, { "alpha_fraction": 0.3128712773323059, "alphanum_fraction": 0.40947049856185913, "avg_line_length": 44.90909194946289, "blob_id": "136ed3541c0b92a7fae20145d38be198d58e48a4", "content_id": "7fa1955f5af58f8206671690e00e5a20a9ca4158", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11615, "license_type": "no_license", "max_line_length": 117, "num_lines": 253, "path": "/fill-a-pix_tests/solver_tests.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "import unittest\nimport numpy as np\n\nfrom fillapix.solver.solver import FillAPixSolver\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass TestSolverSizeOfHood(unittest.TestCase):\n \"\"\"Tests for size_of_hood function.\"\"\"\n\n def setUp(self):\n self.solver = FillAPixSolver(None)\n\n def test_corner(self):\n \"\"\"Tests for corner, all corner have neighbourhoods of size 4\"\"\"\n self.assertEqual(self.solver.size_of_hood(0, 0), 4)\n self.assertEqual(self.solver.size_of_hood(0, 9), 4)\n self.assertEqual(self.solver.size_of_hood(9, 0), 4)\n self.assertEqual(self.solver.size_of_hood(9, 9), 4)\n\n def test_border(self):\n \"\"\"Tests for borders, all borders have neighbourhoods of size 6\"\"\"\n self.assertEqual(self.solver.size_of_hood(0, 5), 6)\n self.assertEqual(self.solver.size_of_hood(9, 5), 6)\n self.assertEqual(self.solver.size_of_hood(5, 0), 6)\n self.assertEqual(self.solver.size_of_hood(5, 9), 6)\n\n def test_inside(self):\n \"\"\"Tests for other points, all other points have neighbourhoods of size 9\"\"\"\n self.assertEqual(self.solver.size_of_hood(2, 3), 9)\n self.assertEqual(self.solver.size_of_hood(4, 3), 9)\n self.assertEqual(self.solver.size_of_hood(8, 2), 9)\n self.assertEqual(self.solver.size_of_hood(5, 5), 9)\n\n\nclass Test2ClueLogic(unittest.TestCase):\n \"\"\"Tests for 2 clue logic (finding filling of squares using clues based on 2 points.\"\"\"\n def setUp(self):\n self.solver = FillAPixSolver(None)\n\n def test_not_filled(self):\n \"\"\"Test for finding 2 clue logic, without additional filled fields in solution\"\"\"\n examples = []\n answers = []\n examples.append(np.array([[100, 100, 100, 100],\n [100, 4, 7, 100],\n [100, 100, 100, 100]]))\n answers.append(' . - - *\\n . - - *\\n . - - *\\n')\n examples.append(np.array([[100, 100, 100],\n [100, 8, 100],\n [100, 5, 100],\n [100, 100, 100]]))\n answers.append(' * * *\\n - - -\\n - - -\\n . . .\\n')\n examples.append(np.array([[100, 2, 4, 100],\n [100, 100, 100, 100]]))\n answers.append(' . - - *\\n . - - *\\n')\n examples.append(np.array([[100, 100, 100, 100],\n [100, 3, 100, 100],\n [100, 100, 8, 100],\n [100, 100, 100, 100]]))\n answers.append(' . . . -\\n . - - *\\n . - - *\\n - * * *\\n')\n examples.append(np.array([[100, 100, 100, 100, 100],\n [100, 1, 100, 7, 100],\n [100, 100, 100, 100, 100]]))\n answers.append(' . . - * *\\n . . - * *\\n . . - * *\\n')\n examples.append(np.array([[100, 100, 100, 100, 100],\n [100, 1, 100, 100, 100],\n [100, 100, 100, 8, 100],\n [100, 100, 100, 100, 100]]))\n answers.append(' . . . - -\\n . . - * *\\n . . - * *\\n - - * * *\\n')\n\n for e, a in zip(examples, answers):\n self.solver.set_puzzle(e)\n for i in range(e.shape[0]):\n for j in range(e.shape[1]):\n self.solver.find_2_clue_logic(i, j)\n self.assertEqual(self.solver.print_solution(), a)\n\n def test_some_filled(self):\n \"\"\"Test for finding 2 clue logic, with additional filled fields in solution\"\"\"\n examples = []\n answers = []\n solutions = []\n examples.append(np.array([[100, 2, 1, 100],\n [100, 100, 100, 100]]))\n solutions.append(np.array([[-1, 0, 0, 0],\n [0, 0, 0, 0]]))\n answers.append(' . - - .\\n * - - .\\n')\n\n examples.append(np.array([[100, 2, 1, 100],\n [100, 100, 100, 100]]))\n solutions.append(np.array([[-1, 0, 0, 0],\n [0, 0, -1, -1]]))\n answers.append(' . - - .\\n * - . .\\n')\n\n examples.append(np.array([[100, 100, 100, 100],\n [100, 2, 4, 100],\n [100, 100, 100, 100]]))\n solutions.append(np.array([[0, 0, 0, -1],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]))\n answers.append(' . - - .\\n . - - *\\n . - - *\\n')\n\n examples.append(np.array([[100, 100, 100, 100],\n [100, 2, 4, 100],\n [100, 100, 100, 100]]))\n solutions.append(np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [1, 0, 0, 0]]))\n answers.append(' . - - *\\n . - - *\\n * - - *\\n')\n\n examples.append(np.array([[100, 5, 100, 100],\n [100, 100, 3, 100],\n [100, 100, 100, 100]]))\n solutions.append(np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]))\n answers.append(' * - - .\\n * - - .\\n - . . .\\n')\n\n examples.append(np.array([[100, 100, 100, 100, 100],\n [100, 2, 100, 7, 100],\n [100, 100, 100, 100, 100]]))\n solutions.append(np.array([[0, 0, 0, 0, -1],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]))\n answers.append(' . . - * .\\n . . - * *\\n . . - * *\\n')\n\n examples.append(np.array([[100, 100, 100, 100, 100],\n [100, 1, 100, 100, 100],\n [100, 100, 100, 7, 100],\n [100, 100, 100, 100, 100]]))\n solutions.append(np.array([[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, -1],\n [0, 0, 0, 0, 0]]))\n answers.append(' . . . - -\\n . . - * *\\n . . - * .\\n - - * * *\\n')\n\n for e, a, s in zip(examples, answers, solutions):\n self.solver.set_puzzle(e)\n self.solver.solution = s\n for i in range(e.shape[0]):\n for j in range(e.shape[1]):\n self.solver.find_2_clue_logic(i, j)\n self.assertEqual(self.solver.print_solution(), a)\n\n def test_special_case_corner(self):\n \"\"\"Test for case with two 2s in corner.\"\"\"\n example = np.array([[2, 2, 100, 100, 100, 2, 2],\n [2, 100, 100, 100, 100, 100, 2],\n [100, 100, 100, 100, 100, 100, 100],\n [100, 100, 100, 100, 100, 100, 100],\n [2, 100, 100, 100, 100, 100, 2],\n [2, 2, 100, 100, 100, 2, 2]])\n answer = ' - - . - . - -\\n - - . - . - -\\n . . - - - . .\\n . . - - - . .\\n - - . - . - -\\n - - . - . - -\\n'\n self.solver.set_puzzle(example)\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.solver.special_case(i, j)\n self.assertEqual(self.solver.print_solution(), answer)\n\n def test_special_case_border(self):\n \"\"\"Test for case with two 3s on border\"\"\"\n example = np.array([[100, 100, 3, 100, 100],\n [100, 100, 3, 100, 100],\n [100, 100, 100, 100, 100],\n [3, 3, 100, 100, 100],\n [100, 100, 100, 100, 100],\n [100, 100, 100, 3, 3],\n [100, 100, 100, 100, 100],\n [100, 100, 100, 100, 100],\n [100, 100, 3, 100, 100],\n [100, 100, 3, 100, 100]])\n answer = ' - - - - -\\n - - - - -\\n - . . . -\\n - - . - -\\n - - . - -\\n - - . - -\\n - - . - -\\n - . . . -\\n' \\\n + ' - - - - -\\n - - - - -\\n'\n self.solver.set_puzzle(example)\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.solver.special_case(i, j)\n self.assertEqual(self.solver.print_solution(), answer)\n\n\nclass Test3ClueLogic(unittest.TestCase):\n \"\"\"Tests for logic based on 3 points.\"\"\"\n def setUp(self):\n self.solver = FillAPixSolver(None)\n\n def test_checking_neighbours(self):\n \"\"\"Test for checking if point has 2 neighbours.\"\"\"\n example = np.array([[100, 2, 3, 100, 100],\n [2, 100, 3, 100, 100],\n [100, 4, 5, 6, 100]])\n self.solver.set_puzzle(example)\n answers = [True, False, True, True, False, True, False, False, False, False, True, False, False, True, False]\n a = 0\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.assertEqual(self.solver.get_neighbours(i, j, close=False)[0], answers[a])\n a += 1\n\n def test_3_clue_logic(self):\n \"\"\"Tests for basic 3 clue logic.\"\"\"\n example = np.array([[100, 100, 100, 100, 100],\n [1, 100, 100, 100, 100],\n [100, 100, 100, 100, 100],\n [100, 2, 100, 100, 100],\n [100, 100, 100, 1, 100]])\n solution = np.array([[-1, -1, 0, 0, 0],\n [-1, -1, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, -1, -1],\n [0, 0, 0, -1, -1]])\n answer = ' . . - - -\\n . . - - -\\n - - . - -\\n . . - . .\\n . . - . .\\n'\n self.solver.set_puzzle(example)\n self.solver.solution = solution\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.solver.find_3_clue_logic(i, j)\n self.assertEqual(self.solver.print_solution(), answer)\n\n example = np.array([[100, 100, 100, 100, 100],\n [2, 100, 100, 100, 100],\n [100, 100, 100, 100, 100],\n [100, 2, 100, 100, 100],\n [100, 100, 100, 1, 100]])\n solution = np.array([[1, -1, 0, 0, 0],\n [-1, -1, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, -1, -1],\n [0, 0, 0, -1, -1]])\n answer = ' * . - - -\\n . . - - -\\n - - . - -\\n . . - . .\\n . . - . .\\n'\n self.solver.set_puzzle(example)\n self.solver.solution = solution\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.solver.find_3_clue_logic(i, j)\n self.assertEqual(self.solver.print_solution(), answer)\n\n def test_ASA(self):\n \"\"\"Tests for special clue: type ASA\"\"\"\n example = np.array([[100, 100, 100, 100, 100, 100],\n [100, 4, 6, 100, 2, 100],\n [100, 100, 100, 100, 100, 100]])\n answer = ' . - - - . .\\n . - - - . .\\n . - - - . .\\n'\n self.solver.set_puzzle(example)\n for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n self.solver.find_asa(i, j)\n self.assertEqual(self.solver.print_solution(), answer)\n\nif __name__ == '__main__':\n print('Tests for fill-a-pix solver.')\n" }, { "alpha_fraction": 0.4371032118797302, "alphanum_fraction": 0.4681028127670288, "avg_line_length": 42.42015075683594, "blob_id": "9c0cdecb9613d53b9927203bb18e246dd35167e4", "content_id": "4ffdf5aa248098055cd2430d4a61e216a5c9f8eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22839, "license_type": "no_license", "max_line_length": 111, "num_lines": 526, "path": "/fillapix/solver/solver.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "# !/usr/bin/env python3\n\"\"\" Fill-a-pix: Solving puzzle\n\"\"\"\n\nimport numpy as np\nimport math\nimport copy\nfrom operator import xor\n\nfrom common.misc import get_unique\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass FillAPixSolver:\n \"\"\" Solver class. \"\"\"\n\n def __init__(self, puzzle):\n \"\"\"Solver initialization.\n :param: puzzle: puzzle container\n \"\"\"\n if puzzle is None:\n self.puzzle = np.zeros((10, 10), int)\n else:\n self.puzzle = puzzle.get_board()\n self.size = self.puzzle.shape\n self.solution = np.zeros(self.size, int)\n self.probability = np.zeros(self.size, float)\n self.user_solution = np.zeros(self.size, int)\n\n def set_puzzle(self, array):\n \"\"\"\n For tests: Setting puzzle board.\n :param array: array to be set as puzzle.\n :return:\n \"\"\"\n self.puzzle = array\n self.size = self.puzzle.shape\n self.solution = np.zeros(self.size, int)\n\n def set_solution(self, array):\n \"\"\"\n Sets solution, only for generated puzzles\n :param array: array with solution to generated puzzle\n :return: None\n \"\"\"\n self.solution = array\n\n def solve(self):\n \"\"\"Solver:\n 1. Fills obvious: 0 and 9, 4 in corners, 6 on borders.\n 2. Checks for pairs of 3s on borders, and 2s in corners.\n 3. Goes from 8 to 1 and checks if there are obvious points.\n 4. Checks for clue logic.\n 5. One every Every five iterations starts random solver.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.puzzle[i, j] == 0:\n self.assign_to_hood(i, j, -1)\n elif self.puzzle[i, j] == 9:\n self.assign_to_hood(i, j, 1)\n elif self.size_of_hood(i, j) == 4 and self.puzzle[i, j] == 4:\n self.assign_to_hood(i, j, 1)\n elif self.size_of_hood(i, j) == 6 and self.puzzle[i, j] == 6:\n self.assign_to_hood(i, j, 1)\n if i in [0, self.size[0] - 1] or j in [0, self.size[1] - 1]:\n self.special_case(i, j)\n self.fill()\n count = 1\n while not self.is_solved():\n self.fill()\n self.find_clues()\n self.fill()\n if count % 5 == 0:\n self.random_solver()\n self.correct_solution()\n if count > 39:\n break\n count += 1\n self.fill_gray()\n\n def fill(self):\n \"\"\"Fills fields with respect to actual knowledge.\"\"\"\n while True:\n changed = 0\n for k in range(8, 0, -1):\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.puzzle[i, j] == k:\n if self.filled_sure(i, j) == k:\n changed += self.assign_to_hood(i, j, -1)\n elif self.empty_sure(i, j) == self.size_of_hood(i, j) - k:\n changed += self.assign_to_hood(i, j, 1)\n\n if changed == 0:\n break\n\n def find_clues(self):\n \"\"\"\n Find 3 types of clues:\n 1. 2 clue logic\n 2. 3 clue logic\n 3. 3 clue logic type ASA\n \"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.puzzle[i, j] < 10:\n self.find_2_clue_logic(i, j)\n self.find_3_clue_logic(i, j)\n self.find_asa(i, j)\n\n def find_2_clue_logic(self, x, y):\n \"\"\"Finds advanced 2 clue logic for point x, y if possible:\n 1. Points directly next to each other\n 2. Point not next to each other (one point between them).\"\"\"\n el1 = self.puzzle[x, y]\n if el1 == 100:\n return\n # directly to each other\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n el1 = self.puzzle[x, y]\n el1_hood = [(a, b) for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n if (i != x or j != y) and self.puzzle[i, j] < 10:\n el2 = self.puzzle[i, j]\n el2_hood = [(a, b) for a in range(max(0, i - 1), min(i + 2, self.size[0]))\n for b in range(max(0, j - 1), min(j + 2, self.size[1]))]\n intersection = [a for a in set(el1_hood + el2_hood) if\n a in el1_hood and a in el2_hood]\n el1_alone = [a for a in el1_hood if a not in intersection if self.solution[a] != -1]\n el2_alone = [a for a in el2_hood if a not in intersection if self.solution[a] != -1]\n el1 -= len([a for a in el1_alone if self.solution[a] == 1])\n el2 -= len([a for a in el2_alone if self.solution[a] == 1])\n if el1 > el2 and len(el1_alone) == math.fabs(el1 - el2):\n self.assign_to_array(el1_alone, 1)\n self.assign_to_array(el2_alone, -1)\n elif el1 < el2 and len(el2_alone) == math.fabs(el1 - el2):\n self.assign_to_array(el1_alone, -1)\n self.assign_to_array(el2_alone, 1)\n\n # not directly next to each other\n for i in range(max(0, x - 2), min(x + 3, self.size[0])):\n for j in range(max(0, y - 2), min(y + 3, self.size[1])):\n el1 = self.puzzle[x, y]\n el1_hood = [(a, b) for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n if (i not in range(max(0, x - 1), min(x + 2, self.size[0])) or\n j not in range(max(0, y - 1), min(y + 2, self.size[1]))) \\\n and self.puzzle[i, j] < 10:\n el2 = self.puzzle[i, j]\n el2_hood = [(a, b) for a in range(max(0, i - 1), min(i + 2, self.size[0]))\n for b in range(max(0, j - 1), min(j + 2, self.size[1]))]\n intersection = [a for a in set(el1_hood + el2_hood) if\n a in el1_hood and a in el2_hood]\n el1_alone = [a for a in el1_hood if a not in intersection if self.solution[a] != -1]\n el2_alone = [a for a in el2_hood if a not in intersection if self.solution[a] != -1]\n el1 -= len([a for a in el1_alone if self.solution[a] == 1])\n el2 -= len([a for a in el2_alone if self.solution[a] == 1])\n if el1 > el2 and len(el1_alone) == math.fabs(el1 - el2):\n self.assign_to_array(el1_alone, 1)\n self.assign_to_array(el2_alone, -1)\n elif el1 < el2 and len(el2_alone) == math.fabs(el1 - el2):\n self.assign_to_array(el1_alone, -1)\n self.assign_to_array(el2_alone, 1)\n\n def find_3_clue_logic(self, x, y):\n \"\"\"\n Finds 3 clue logic for point x, y.\n :param x: position\n :param y: position\n :return: None\n \"\"\"\n el1 = self.puzzle[x, y]\n if el1 == 100:\n return\n # first case\n neighbours = self.get_neighbours(x, y, True)\n if len(neighbours) >= 2:\n neighbours_pairs = get_unique(np.array([(a, b) for a in neighbours for b in neighbours if a != b]))\n for pair in neighbours_pairs:\n el2_x, el2_y = pair[0]\n el3_x, el3_y = pair[1]\n el1_hood = [(a, b) for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n el2 = self.puzzle[el2_x, el2_y]\n el2_hood = [(a, b) for a in range(max(0, el2_x - 1), min(el2_x + 2, self.size[0]))\n for b in range(max(0, el2_y - 1), min(el2_y + 2, self.size[1]))]\n el3 = self.puzzle[el3_x, el3_y]\n el3_hood = [(a, b) for a in range(max(0, el3_x - 1), min(el3_x + 2, self.size[0]))\n for b in range(max(0, el3_y - 1), min(el3_y + 2, self.size[1]))]\n a_only = get_unique(np.array([a for a in el1_hood if a not in el2_hood and a not in el3_hood]))\n b_but_not_a = get_unique(np.array([a for a in el2_hood + el3_hood if a not in el1_hood]))\n a_and_all_b = get_unique(np.array([a for a in el1_hood if a in el2_hood and a in el3_hood]))\n if el1 == len(a_only) + el2 + el3:\n self.assign_to_array(a_only, 1)\n self.assign_to_array(b_but_not_a, -1)\n self.assign_to_array(a_and_all_b, -1)\n\n # second case\n neighbours = self.get_neighbours(x, y, False)\n if len(neighbours) >= 2:\n neighbours_pairs = get_unique(np.array([(a, b) for a in neighbours for b in neighbours if a != b]))\n for pair in neighbours_pairs:\n el2_x, el2_y = pair[0]\n el3_x, el3_y = pair[1]\n el1_hood = [(a, b) for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n el2 = self.puzzle[el2_x, el2_y]\n el2_hood = [(a, b) for a in range(max(0, el2_x - 1), min(el2_x + 2, self.size[0]))\n for b in range(max(0, el2_y - 1), min(el2_y + 2, self.size[1]))]\n el3 = self.puzzle[el3_x, el3_y]\n el3_hood = [(a, b) for a in range(max(0, el3_x - 1), min(el3_x + 2, self.size[0]))\n for b in range(max(0, el3_y - 1), min(el3_y + 2, self.size[1]))]\n el2 -= len([a for a in el2_hood if a not in el1_hood and self.solution[a] == 1])\n el3 -= len([a for a in el3_hood if a not in el1_hood and self.solution[a] == 1])\n a_only = get_unique(np.array([a for a in el1_hood if a not in el2_hood and a not in el3_hood]))\n b_but_not_a = get_unique(np.array([a for a in el2_hood + el3_hood\n if a not in el1_hood and self.solution[a] == 0]))\n a_and_one_b = get_unique(np.array([a for a in el1_hood if xor(a in el2_hood, a in el3_hood)]))\n # A_and_all_B = get_unique(np.array([a for a in el1_hood if a in el2_hood + el3_hood]))\n if el1 == el2 + el3 and len(b_but_not_a) == 0 and el1 < len(a_and_one_b):\n self.assign_to_array(a_only, -1)\n\n def find_asa(self, x, y):\n \"\"\"\n Find 3 clue logic of type ASA, for example: _ 2 6 _ 4 _.\n :param x: position\n :param y: position\n :return: None\n \"\"\"\n el1 = self.puzzle[x, y]\n if el1 == 100:\n return\n el1_hood = [(a, b) for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n hood = []\n if 1 < x < self.size[0] - 2 and self.puzzle[x - 1, y] + self.puzzle[x + 2, y] == el1:\n hood = [(a, b) for a in range(max(x - 2, 0), min(x + 4, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n elif 2 < x < self.size[0] - 1 and self.puzzle[x + 1, y] + self.puzzle[x - 2, y] == el1:\n hood = [(a, b) for a in range(max(x - 3, 0), min(x + 3, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n elif 1 < y < self.size[1] - 2 and self.puzzle[x, y - 1] + self.puzzle[x, y + 2] == el1:\n hood = [(a, b) for a in range(max(x - 1, 0), min(x + 2, self.size[0]))\n for b in range(max(y - 2, 0), min(y + 4, self.size[1]))]\n elif 2 < y < self.size[1] - 1 and self.puzzle[x, y + 1] + self.puzzle[x, y - 2] == el1:\n hood = [(a, b) for a in range(max(x - 1, 0), min(x + 2, self.size[0]))\n for b in range(max(y - 4, 0), min(y + 2, self.size[1]))]\n to_insert = [a for a in hood if a not in el1_hood]\n self.assign_to_array(to_insert, -1)\n\n def random_solver(self):\n \"\"\"Creates list with all unfilled squares on board with number with condition:\n number in square - filled squares in neighbourhood == 1.\n Takes one random square and tries filling unfilled squares in its neighbourhood and then\n the rest of puzzle. If solution is not correct discards it.\"\"\"\n queue = []\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.puzzle[i, j] - self.filled_sure(i, j) == 1:\n queue.append([i, j])\n if len(queue) == 0:\n return\n\n q = queue[np.random.randint(0, len(queue))]\n queue2 = []\n for n in self.get_hood(*q):\n if self.solution[n[0], n[1]] == 0:\n queue2.append(n)\n for n in queue2:\n old_solution = copy.deepcopy(self.solution)\n self.solution[n[0], n[1]] = 1\n self.fill()\n self.find_clues()\n self.fill()\n if self.correct_fill() == [-1, -1]:\n break\n else:\n self.solution = copy.deepcopy(old_solution)\n\n def fill_gray(self):\n \"\"\"All not black squares are filled with gray.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.solution[i, j] == 0:\n self.solution[i, j] = -1\n\n\n def get_neighbours(self, x, y, close):\n \"\"\"\n Creates list of neighbours of point x, y with numbers in them.\n :param x: position\n :param y: position\n :param close: boolean, True if function is expected to check closes neighbours, False if 2 points away\n :return: neighbours\n \"\"\"\n neighbours = []\n if close:\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n if (i != x or j != y) and self.puzzle[i, j] < 10:\n neighbours.append([i, j])\n else:\n for i in range(max(0, x - 2), min(x + 3, self.size[0])):\n for j in range(max(0, y - 2), min(y + 3, self.size[1])):\n if (i not in range(max(0, x - 1), min(x + 2, self.size[0])) or\n j not in range(max(0, y - 1), min(y + 2, self.size[1]))) \\\n and self.puzzle[i, j] < 10:\n neighbours.append([i, j])\n return neighbours\n\n def get_hood(self, x, y):\n \"\"\"\n Creates list of all neighbours.\n :param x: position\n :param y: position\n :return: list of neighbours\n \"\"\"\n return [[a, b] for a in range(max(0, x - 1), min(x + 2, self.size[0]))\n for b in range(max(0, y - 1), min(y + 2, self.size[1]))]\n\n def special_case(self, x, y):\n \"\"\"\n Checks for special case: two 3: one on border, one next to it not on border,\n two 2: one in corner, one on border\n :param x: position\n :param y: position\n :return: None\n \"\"\"\n if self.puzzle[x, y] == 2:\n if x == 0 and y == 0:\n if self.puzzle[x + 1, y] == 2:\n self.solution[x + 2, 0: 2] = -1\n if self.puzzle[x, y + 1] == 2:\n self.solution[0: 2, y + 2] = -1\n if x == 0 and y == self.size[1] - 1:\n if self.puzzle[x + 1, y] == 2:\n self.solution[x + 2, self.size[1] - 2: self.size[1]] = -1\n if self.puzzle[x, y - 1] == 2:\n self.solution[0: 2, y - 2] = -1\n if x == self.size[0] - 1 and y == 0:\n if self.puzzle[x - 1, y] == 2:\n self.solution[x - 2, 0: 2] = -1\n if self.puzzle[x, y + 1] == 2:\n self.solution[self.size[0] - 2: self.size[0], y + 2] = -1\n if x == self.size[0] - 1 and y == self.size[1] - 1:\n if self.puzzle[x - 1, y] == 2:\n self.solution[x - 2, self.size[1] - 2: self.size[1]] = -1\n if self.puzzle[x, y - 1] == 2:\n self.solution[self.size[0] - 2: self.size[0], y - 2] = -1\n\n elif self.puzzle[x, y] == 3 and (\n x in [0, self.size[0] - 1] or y in [0, self.size[1] - 1]):\n if x == 0 and 0 < y < self.size[1] - 1 and self.puzzle[x + 1, y] == 3:\n self.solution[x + 2, y - 1: y + 2] = -1\n if x == self.size[0] - 1 and 0 < y < self.size[1] - 1 and self.puzzle[x - 1, y] == 3:\n self.solution[x - 2, y - 1: y + 2] = -1\n if 0 < x < self.size[0] - 1 and y == 0 and self.puzzle[x, y + 1] == 3:\n self.solution[x - 1: x + 2, y + 2] = -1\n if 0 < x < self.size[0] - 1 and y == self.size[1] - 1 and self.puzzle[x, y - 1] == 3:\n self.solution[x - 1: x + 2, y - 2] = -1\n\n def filled_sure(self, x, y):\n \"\"\"\n Counts how many neighbours of point are for sure filled.\n :param x: position\n :param y: position\n :return: number of filled neighbours\n \"\"\"\n count = 0\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n if self.solution[i, j] == 1:\n count += 1\n return count\n\n def empty_sure(self, x, y):\n \"\"\"\n Counts how many neighbours of point are for sure unfilled.\n :param x: position\n :param y: position\n :return: number of unfilled neighbours\n \"\"\"\n count = 0\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n if self.solution[i, j] == -1:\n count += 1\n return count\n\n def size_of_hood(self, i, j):\n \"\"\"\n Size of point's neighbourhood.\n :param i: position\n :param j: position\n :return: number of neighbours\n \"\"\"\n if 0 < i < self.size[0] - 1 and 0 < j < self.size[1] - 1:\n return 9\n elif (i == 0 or i == self.size[0] - 1) and (j == 0 or j == self.size[1] - 1):\n return 4\n else:\n return 6\n\n def assign_to_hood(self, x, y, val):\n \"\"\"\n Assign val to entire neighbourhood of point (including point i, j).\n :param x: position\n :param y: position\n :param val: value to be assigned\n :return: how many points were assigned\n \"\"\"\n count = 0\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n if self.solution[i, j] not in [-1, 1]:\n self.solution[i, j] = val\n count += 1\n return count\n\n def reset_hood(self, x, y):\n \"\"\"Resets values in neighbourhood to 0.\"\"\"\n for i in range(max(0, x - 1), min(x + 2, self.size[0])):\n for j in range(max(0, y - 1), min(y + 2, self.size[1])):\n self.solution[i, j] = 0\n\n def assign_to_array(self, array, val):\n \"\"\"\n Assign val to array of points.\n :param array: array to be filled\n :param val: value to be assigned\n :return: how many points were assigned\n \"\"\"\n count = 0\n for x, y in array:\n if self.solution[x, y] == 0:\n self.solution[x, y] = val\n count += 1\n return count\n\n def is_solved(self):\n \"\"\"Checks if puzzle is solved.\"\"\"\n count = 0\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.solution[i, j] == 0:\n count += 1\n if count == 0:\n return True\n else:\n return False\n\n def correct_fill(self):\n \"\"\"Checks if current filling is correct. If not returns first found mistake.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n el = self.puzzle[i, j]\n if el < 10:\n if self.filled_sure(i, j) > el:\n return i, j\n elif self.empty_sure(i, j) > self.size_of_hood(i, j) - el:\n return i, j\n return [-1, -1]\n\n def correct_solution(self):\n \"\"\"Resets neighbourhood of square with mistake.\"\"\"\n if self.correct_fill() != [-1, -1]:\n self.reset_hood(*self.correct_fill())\n\n def print_solution(self):\n \"\"\"For tests: prints solution.\"\"\"\n print()\n txt = ''\n for row in self.solution:\n for el in row:\n if el == -1:\n txt += ' .'\n elif el == 1:\n txt += ' *'\n else:\n txt += ' -'\n txt += '\\n'\n print(txt)\n return txt\n\n def get_user_solution(self):\n \"\"\"Getter for user's solution.\"\"\"\n return self.user_solution\n\n def get_user_value(self, i, j):\n \"\"\"Getter for user chosen value in point.\"\"\"\n return self.user_solution[i, j]\n\n def set_user_value(self, x, y, val):\n \"\"\"Sets user chosen value.\"\"\"\n self.user_solution[x, y] = val\n\n def set_solved(self):\n \"\"\"Sets user's solution to solution.\"\"\"\n self.user_solution = copy.deepcopy(self.solution)\n\n def clear_user_solution(self):\n \"\"\"Resets user's solution.\"\"\"\n self.user_solution = np.zeros(self.size, int)\n\n def check_user_solution(self):\n \"\"\"Checks if user's solution is currently correct. Omits unfilled points.\"\"\"\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if self.solution[i, j] != self.user_solution[i, j] and self.user_solution[i, j] != 0:\n return i, j\n return -1, -1\n\n def is_solved_by_user(self):\n \"\"\"Checks if puzzle is solved by user.\"\"\"\n count = 0\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.user_solution[i, j] != self.solution[i, j]:\n count += 1\n if count == 0:\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.5830508470535278, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 30.052631378173828, "blob_id": "beeb2c2f76197f3ea9b03b9cad992e00d48a1d28", "content_id": "5f2b35b34296a9f2a8f18daeedcbf131ae6911d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1770, "license_type": "no_license", "max_line_length": 68, "num_lines": 57, "path": "/gui/generate_sym_dialog.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Dialog window to choose parameters of sym-a-pix being generated.\n\"\"\"\n\nfrom PyQt4 import QtGui\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass GenerateSymDialog(QtGui.QMainWindow):\n \"\"\"Dialog window where user can set size of new puzzle\"\"\"\n\n def __init__(self, parent):\n \"\"\"Initialization of class.\"\"\"\n super(GenerateSymDialog, self).__init__()\n self.ok_btn = QtGui.QPushButton('OK')\n self.size_value = QtGui.QSpinBox()\n self.colors_value = QtGui.QSpinBox()\n self.parent = parent\n self.init_ui()\n\n def init_ui(self):\n \"\"\"Dialog window\"\"\"\n self.setWindowTitle('Sym-a-pix: generate game')\n self.resize(200, 120)\n cw = QtGui.QWidget()\n self.setCentralWidget(cw)\n l = QtGui.QGridLayout()\n size_label = QtGui.QLabel('Size: ')\n\n self.size_value.setMinimum(5)\n self.size_value.setMaximum(20)\n self.size_value.setValue(10)\n l.addWidget(size_label, *(0, 0))\n l.addWidget(self.size_value, *(0, 1))\n\n color_label = QtGui.QLabel('Colors: ')\n self.colors_value.setMinimum(2)\n self.colors_value.setMaximum(10)\n self.colors_value.setValue(2)\n\n l.addWidget(color_label, *(1, 0))\n l.addWidget(self.colors_value, *(1, 1))\n\n self.ok_btn.clicked.connect(self.send_values)\n l.addWidget(self.ok_btn, *(2, 1))\n cw.setLayout(l)\n\n def send_values(self):\n \"\"\"Function to send user's values to generating function.\"\"\"\n size = self.size_value.value()\n color = self.colors_value.value()\n self.parent.generate_new_sym(size, size, color)\n self.size_value.setValue(10)\n self.colors_value.setValue(2)\n self.close()\n" }, { "alpha_fraction": 0.405832976102829, "alphanum_fraction": 0.42463281750679016, "avg_line_length": 41.326820373535156, "blob_id": "73b7e8babb1aadcb607aa8e3b3a0933bc4a98537", "content_id": "cb5c3bcae150c04056e7122413f472d1dc36da62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23830, "license_type": "no_license", "max_line_length": 115, "num_lines": 563, "path": "/symapix/solver/solver.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Sym-a-pix: Solving puzzle\n\"\"\"\nimport copy\n\nimport numpy as np\n\nfrom common.misc import get_unique, define_frame, define_block, symmetric_point, wall_between, count, point_dist, \\\n adjacent_squares, closest_closed\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass SymAPixSolver:\n \"\"\" Solver class. \"\"\"\n\n def __init__(self, puzzle):\n if puzzle is None:\n self.puzzle = np.zeros((10, 10), int) - 1\n else:\n self.puzzle = puzzle.get_board()\n self.colors = puzzle.get_colors()\n self.size = self.puzzle.shape\n\n # solution: -2 - dot, 1 - wall, 0 - empty\n self.solution = np.zeros(self.size, int)\n self.user_solution = np.zeros(self.size, int)\n self.fill_color = np.zeros(self.size, int) - 1 # -1 - non, [0,1,2,3,...] - color from list\n self.set_dots()\n\n def set_puzzle(self, array):\n \"\"\"Setting puzzle board; just for fill-a-pix_tests.\"\"\"\n self.puzzle = array\n self.size = self.puzzle.shape\n self.solution = np.zeros(self.size, int)\n self.set_dots()\n\n def set_dots(self):\n \"\"\"Sets values in solution were dots are\"\"\"\n for i, row in enumerate(self.puzzle):\n for j, el in enumerate(row):\n if el > 0:\n self.solution[i, j] = -2\n self.user_solution[i, j] = -2\n\n def solve(self):\n \"\"\"Main solver function\"\"\"\n self.init_fill()\n self.fill_smallest()\n self.check_closed()\n filled_count = 1\n while filled_count > 0:\n filled_count = self.find_blocked_regions()\n self.check_closed()\n self.fill_smallest()\n self.check_closed()\n self.correct_solution()\n\n def init_fill(self):\n \"\"\"Fills obvious lines between two dots: if two squares contain dot or part of dot there is line.\"\"\"\n for x in range(0, self.size[0], 2):\n for y in range(0, self.size[1], 2):\n if self.contains_dot(x, y):\n adjacent = adjacent_squares(x, y)\n for pair in adjacent:\n if self.is_inside(*pair):\n i, j = pair\n if self.contains_dot(i, j) and not self.is_same_dot(x, y, i, j):\n a, b = wall_between(x, y, i, j)\n self.solution[a, b] = 1\n\n def contains_dot(self, x, y):\n \"\"\"\n Checks if square contains dot or part of a dot\n or checks if line contains dot or part of a dot.\n :param x: position\n :param y: position\n :return: bool: True if contains, False if not.\n \"\"\"\n if not self.is_inside(x, y):\n return False\n if x % 2 == 0 and y % 2 == 0:\n for i in range(max(x - 1, 0), min(x + 2, self.size[0])):\n for j in range(max(y - 1, 0), min(y + 2, self.size[1])):\n if self.puzzle[i, j] > 0:\n return True\n elif x % 2 == 0:\n for j in range(y - 1, y + 2):\n if self.puzzle[x, j] > 0:\n return True\n elif y % 2 == 0:\n for i in range(x - 1, x + 2):\n if self.puzzle[i, y] > 0:\n return True\n return False\n\n def dot_in_corner(self, x, y, i, j):\n \"\"\"\n Checks if corner between two squares (x,y and i,j) are dots.\n :param x: 1st square position\n :param y: 1st square position\n :param i: 2nd square position\n :param j: 2nd square position\n :return: dot in the corner\n \"\"\"\n if x % 2 > 0 or y % 2 > 0:\n return [-1, -1]\n corners = []\n if x == i:\n corners = [[x - 1, int((y + j) / 2)], [x + 1, int((y + j) / 2)]]\n elif y == j:\n corners = [[int((x + i) / 2), y - 1], [int((x + i) / 2), y + 1]]\n for c in corners:\n if self.is_inside(*c) and self.puzzle[c[0], c[1]] > 0:\n return c\n return [-1, -1]\n\n def is_same_dot(self, x, y, i, j):\n \"\"\"\n Checks if two squares have the same dot.\n :param x: 1st square position\n :param y: 1st square position\n :param i: 2nd square position\n :param j: 2nd square position\n :return: bool: True if they have, False if not\n \"\"\"\n a = self.dots_list(x, y)\n b = self.dots_list(i, j)\n if len([k for k in a + b if k in a and k in b]) > 0:\n return True\n else:\n return False\n\n def dots_list(self, x, y):\n \"\"\"\n Gives list of dots for point.\n :param x: position\n :param y: position\n :return: list of dots touching square.\n \"\"\"\n dots = []\n for i in range(max(x - 1, 0), min(x + 2, self.size[0])):\n for j in range(max(y - 1, 0), min(y + 2, self.size[1])):\n if self.puzzle[i, j] > 0:\n dots.append([i, j])\n return dots\n\n def fill_smallest(self):\n \"\"\"Fills the smallest blocks (1, 2 or 4 squares depending on where dot is).\"\"\"\n filled_count = 0\n for x in range(0, self.size[0]):\n for y in range(0, self.size[1]):\n if self.puzzle[x, y] > 0:\n frame = define_frame(x, y)\n for wall in frame:\n if self.is_wall(*wall):\n a, b = symmetric_point(x, y, wall[0], wall[1])\n if 0 <= a < self.size[0] and 0 <= b < self.size[1]:\n self.solution[a, b] = 1\n filled_count += 1\n return filled_count\n\n def fill(self, k):\n \"\"\"Fills to length of k\"\"\"\n filled_count = 0\n for i, row in enumerate(self.solution):\n for j, el in enumerate(row):\n if self.puzzle[i, j] > 0 and not closest_closed(i, j, self.solution):\n filled_count += self.fill_from_dot(i, j, k)\n return filled_count\n\n def fill_from_dot(self, i, j, k=0, block=None):\n \"\"\"\n Fills block from given dot.\n :param k: describes how far from dot algorithm will attempt to fill puzzle\n :param i: position\n :param j: position\n :param block: if not empty, function can use only points in block\n :return: how many walls were put in\n \"\"\"\n filled_count = 0\n queue = define_block(i, j)\n visited = []\n no_queue = False\n while queue:\n p = queue.pop()\n visited.append(p)\n next_ones = []\n for n in adjacent_squares(p[0], p[1]):\n if 0 < k < point_dist(n[0], n[1], i, j):\n no_queue = True\n wall = wall_between(n[0], n[1], p[0], p[1])\n if n not in visited:\n if block is not None:\n if n in block:\n if not (self.is_inside(*wall) and self.puzzle[wall[0], wall[1]] > 0) \\\n and not (self.is_inside(*n) and self.solution[n[0], n[1]] < 0):\n next_ones.append(n)\n else:\n if not (self.is_inside(*wall) and self.puzzle[wall[0], wall[1]] > 0) \\\n and not (self.is_inside(*n) and self.puzzle[n[0], n[1]] > 0):\n next_ones.append(n)\n for n in next_ones:\n n_sym = symmetric_point(i, j, n[0], n[1])\n p_sym = symmetric_point(i, j, p[0], p[1])\n new_wall = wall_between(p_sym[0], p_sym[1], n_sym[0], n_sym[1])\n curr_wall = wall_between(p[0], p[1], n[0], n[1])\n if self.is_wall(*curr_wall) and \\\n self.is_inside(*new_wall) and not (self.is_wall(*new_wall)\n or self.puzzle[new_wall[0], new_wall[1]] > 0):\n self.solution[new_wall[0], new_wall[1]] = 1\n filled_count += 1\n if self.is_wall(*new_wall) and \\\n self.is_inside(*curr_wall) and not (self.is_wall(*curr_wall)\n or self.puzzle[curr_wall[0], curr_wall[1]] > 0):\n self.solution[curr_wall[0], curr_wall[1]] = 1\n filled_count += 1\n if not no_queue:\n for n in next_ones:\n curr_wall = wall_between(p[0], p[1], n[0], n[1])\n if not self.is_wall(*curr_wall) and \\\n self.is_inside(*n) and self.solution[n[0], n[1]] < 1:\n queue.append(n)\n\n if self.puzzle[i, j] > 0:\n block = get_unique(np.array(visited))\n if self.block_is_closed(block, self.solution):\n for b in block:\n self.solution[b[0], b[1]] = self.puzzle[i, j]\n\n return filled_count\n\n def check_closed(self):\n \"\"\"Checks if there are new closed blocks.\"\"\"\n for i, row in enumerate(self.solution):\n for j, el in enumerate(row):\n if self.puzzle[i, j] > 0 and not closest_closed(i, j, self.solution):\n queue = define_block(i, j)\n visited = []\n while queue:\n p = queue.pop()\n visited.append(p)\n next_ones = adjacent_squares(p[0], p[1])\n for n in next_ones:\n if self.is_inside(*n) and not self.puzzle[n[0], n[1]] < 0 \\\n and not self.is_wall(*wall_between(p[0], p[1], n[0], n[1])) \\\n and n not in visited:\n n_sym = symmetric_point(i, j, n[0], n[1])\n p_sym = symmetric_point(i, j, p[0], p[1])\n if (self.is_inside(*n_sym) and self.is_inside(*p_sym)) and \\\n not self.puzzle[n_sym[0], n_sym[1]] < 0 or \\\n not self.is_wall(*wall_between(p_sym[0], p_sym[1], n_sym[0], n_sym[1])):\n queue.append(n)\n if self.puzzle[i, j] > 0:\n block = get_unique(np.array(visited))\n if self.block_is_closed(block, self.solution):\n for b in block:\n self.solution[b[0], b[1]] = self.puzzle[i, j]\n\n def find_blocked_regions(self):\n \"\"\"Finds parts of blocks with all walls checked and one dot.\n Then fills symmetric part of that block.\"\"\"\n filled_count = 0\n for i, row in enumerate(self.solution):\n for j, el in enumerate(row):\n if i % 2 == 0 and j % 2 == 0 and el == 0:\n queue = []\n dots = []\n visited = [[i, j]]\n\n for p in adjacent_squares(i, j):\n pos_wall = wall_between(i, j, p[0], p[1])\n cor_dot = self.dot_in_corner(i, j, p[0], p[1])\n if self.is_inside(*pos_wall) and self.puzzle[pos_wall[0], pos_wall[1]] > 0:\n dots.append(pos_wall)\n elif not self.is_wall(*pos_wall) and self.is_inside(*p) and self.puzzle[p[0], p[1]] > 0:\n dots.append(p)\n elif not self.is_wall(*pos_wall):\n queue.append(p)\n if not cor_dot == [-1, -1]:\n dots.append(cor_dot)\n while queue:\n p = queue.pop()\n sym_part = False\n if len(dots) == 1:\n for d in dots:\n s = symmetric_point(d[0], d[1], p[0], p[1])\n if [s[0], s[1]] in visited:\n sym_part = True\n if not sym_part:\n visited.append(p)\n next_ones = adjacent_squares(p[0], p[1])\n for n in next_ones:\n pos_wall = wall_between(p[0], p[1], n[0], n[1])\n if n not in visited and not self.is_wall(*pos_wall):\n corner_dot = self.dot_in_corner(n[0], n[1], p[0], p[1])\n if self.is_inside(*pos_wall) and self.puzzle[pos_wall[0], pos_wall[1]] > 0 \\\n and pos_wall not in dots:\n dots.append(pos_wall)\n elif self.is_inside(*n) and self.puzzle[n[0], n[1]] > 0 and n not in dots:\n dots.append(n)\n elif self.is_inside(*n) and n not in visited and n not in dots:\n queue.append(n)\n if not corner_dot == [-1, -1] and corner_dot not in dots:\n dots.append(corner_dot)\n block = get_unique(np.array(visited))\n if len(dots) == 1 and len(block) > 0:\n dot = dots[0]\n filled_count += self.fill_from_dot(dot[0], dot[1], k=0, block=block)\n elif len(dots) > 1 and len(block) > 0:\n self.test_dots(i, j, dots)\n return filled_count\n\n def block_is_closed(self, block, array):\n \"\"\"\n Checks if all walls around block are closed.\n :param block: block to be checked\n :param array: solution or user_solution\n :return: bool\n \"\"\"\n all_walls = []\n for b in block:\n all_walls.append(define_frame(b[0], b[1]))\n all_walls = np.array(all_walls).reshape(-1, 2)\n all_walls = np.array([x for x in all_walls if count(all_walls, x) == 1])\n for w in all_walls:\n if 0 <= w[0] < self.size[0] and 0 <= w[1] < self.size[1] and array[w[0], w[1]] != 1:\n return False\n return True\n\n def test_dots(self, x, y, dots):\n \"\"\"\n Tests from x, y to dots if it can be filled\n :param x: starting position\n :param y: starting position\n :param dots: list of dots to be tested\n :return:\n \"\"\"\n ok_dots = []\n for d in dots:\n p = symmetric_point(d[0], d[1], x, y)\n if self.is_inside(*p) and self.solution[p[0], p[1]] == 0:\n ok_dots.append(d)\n if len(ok_dots) == 1:\n d = ok_dots[0]\n walls = define_frame(x, y)\n for w in walls:\n sym_w = symmetric_point(d[0], d[1], w[0], w[1])\n if self.is_wall(*w) and self.is_inside(*sym_w):\n self.solution[sym_w[0], sym_w[1]] = 1\n elif self.is_wall(*sym_w) and self.is_inside(*w):\n self.solution[w[0], w[1]] = 1\n\n def is_wall(self, x, y, user=False):\n \"\"\"\n Checks if point is wall.\n :param x: position\n :param y: position\n :param user: whether to check user solution or not\n :return: bool\n \"\"\"\n if user:\n array = self.user_solution\n else:\n array = self.solution\n if x in [-1, self.size[0]]:\n return True\n elif y in [-1, self.size[1]]:\n return True\n elif 0 <= x < self.size[0] and 0 <= y < self.size[1] and array[x, y] == 1:\n return True\n return False\n\n def is_inside(self, i, j):\n \"\"\"\n Checks if point is inside the board.\n :param i: position\n :param j: position\n :return:\n \"\"\"\n if 0 <= i < self.size[0] and 0 <= j < self.size[1]:\n return True\n else:\n return False\n\n def is_solved(self):\n \"\"\"Checks if puzzle is finished: if all squares are filled (value grater then 0).\"\"\"\n for i in range(0, self.size[0], 2):\n for j in range(0, self.size[1], 2):\n if self.solution[i, j] == 0:\n return False\n return True\n\n def correct_solution(self):\n \"\"\"Corrects solution.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.puzzle[i, j] > 0:\n queue = define_block(i, j)\n visited = []\n while queue:\n q = queue.pop()\n visited.append(q)\n for p in adjacent_squares(*q):\n p_sym = symmetric_point(i, j, *p)\n q_sym = symmetric_point(i, j, *q)\n pos_wall = wall_between(p[0], p[1], q[0], q[1])\n sym_wall = wall_between(p_sym[0], p_sym[1], q_sym[0], q_sym[1])\n if not self.is_wall(*pos_wall) and not self.is_wall(*sym_wall) and p not in visited:\n queue.append(p)\n elif self.is_wall(*pos_wall) and not self.is_wall(*sym_wall):\n self.solution[sym_wall[0], sym_wall[1]] = 1\n elif not self.is_wall(*pos_wall) and self.is_wall(*sym_wall):\n self.solution[pos_wall[0], pos_wall[1]] = 1\n block = get_unique(visited)\n for b in block:\n self.solution[b[0], b[1]] = self.puzzle[i, j]\n\n def print_solution(self):\n \"\"\"For tests: prints solution\"\"\"\n for i, row in enumerate(self.solution):\n txt = ''\n for j, el in enumerate(row):\n if el == -4:\n txt += 'O '\n elif el == -3:\n txt += 'x '\n elif el == -2:\n txt += 'o '\n elif el == -1:\n if i % 2 == 0 and j % 2 == 0:\n txt += ' '\n elif i % 2 == 0 and j % 2 > 0:\n txt += '| '\n elif i % 2 > 0 and j % 2 == 0:\n txt += '_ '\n elif i % 2 > 0 and j % 2 > 0:\n txt += '+ '\n elif el == 0:\n if i % 2 == 0 and j % 2 == 0:\n txt += ' '\n elif i % 2 == 0 and j % 2 > 0:\n txt += 'l '\n elif i % 2 > 0 and j % 2 == 0:\n txt += '. '\n elif i % 2 > 0 and j % 2 > 0:\n txt += '+ '\n elif el == 1:\n if i % 2 == 0 and j % 2 == 0:\n txt += ' '\n elif i % 2 == 0 and j % 2 > 0:\n txt += '||'\n elif i % 2 > 0 and j % 2 == 0:\n txt += '__'\n elif i % 2 > 0 and j % 2 > 0:\n txt += '+ '\n print(txt)\n\n def get_user_solution(self):\n \"\"\"Returns user's solution.\"\"\"\n return self.user_solution\n\n def get_color_board(self):\n \"\"\"Returns current colors and color list.\"\"\"\n return self.fill_color\n\n def get_colors(self):\n \"\"\"Returns colors used in puzzle.\"\"\"\n return self.colors\n\n def get_user_value(self, i, j):\n \"\"\"Reads value chosen by user.\"\"\"\n if 0 <= i < self.size[0] and 0 <= j < self.size[1]:\n return self.user_solution[i, j]\n\n def clear_user_board(self):\n \"\"\"Clears user's solution.\"\"\"\n for i in range(0, self.size[0], 2):\n for j in range(0, self.size[1], 2):\n self.user_solution[i, j] = 0\n\n def set_user_value(self, x, y, val):\n \"\"\"Sets value chosen by user.\"\"\"\n self.clear_user_board()\n self.user_solution[x, y] = val\n self.update_user_filling()\n\n def update_user_filling(self):\n \"\"\"Updates blocked regions and fills them.\"\"\"\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if self.puzzle[i, j] > 0:\n block = []\n if self.block_is_closed(define_block(i, j), self.user_solution):\n block = define_block(i, j)\n else:\n queue = define_block(i, j)\n visited = []\n search = True\n while queue and search:\n p = queue.pop()\n visited.append(p)\n next_ones = adjacent_squares(p[0], p[1])\n for n in next_ones:\n if self.is_inside(*n) and n not in visited:\n if not self.is_wall(*wall_between(p[0], p[1], n[0], n[1]), user=True):\n queue.append(n)\n if self.puzzle[n[0], n[1]] > 0 and \\\n not self.is_wall(*wall_between(p[0], p[1], n[0], n[1])):\n search = False\n break\n if search:\n block = get_unique(np.array(visited))\n if len(block) > 0:\n if self.block_is_closed(block, self.user_solution):\n for b in block:\n self.user_solution[b[0], b[1]] = self.puzzle[i, j]\n for i, row in enumerate(self.user_solution):\n for j, el in enumerate(row):\n self.fill_color[i, j] = el if i % 2 == 0 and j % 2 == 0 and el > 0 else 0\n\n def set_solved(self):\n \"\"\"Sets user solution to real solution.\"\"\"\n self.user_solution = copy.deepcopy(self.solution)\n for i, row in enumerate(self.user_solution):\n for j, el in enumerate(row):\n self.fill_color[i, j] = el if i % 2 == 0 and j % 2 == 0 and el > 0 else -1\n\n def clear_user_solution(self):\n \"\"\"Resets user solution.\"\"\"\n self.user_solution = np.zeros(self.size, int)\n self.fill_color = np.zeros(self.size, int) - 1\n\n def check_user_solution(self):\n \"\"\"Checks user solution. Omits unsure squares.\"\"\"\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if not (i % 2 == 0 and j % 2 == 0) and not (i % 2 > 0 and j % 2 > 0):\n if self.solution[i, j] != self.user_solution[i, j] and self.user_solution[i, j] != 0:\n if i % 2 == 0:\n i /= 2\n else:\n i = (i - 1) / 2\n if j % 2 == 0:\n j /= 2\n else:\n j = (j - 1) / 2\n return int(i), int(j)\n return -1, -1\n\n def is_solved_by_user(self):\n \"\"\"Checks if puzzle is solved by user.\"\"\"\n filled_count = 0\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if not (i % 2 == 0 and j % 2 == 0) and not (i % 2 > 0 and j % 2 > 0):\n if self.user_solution[i, j] != self.solution[i, j]:\n filled_count += 1\n if filled_count == 0:\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.7889447212219238, "alphanum_fraction": 0.7889447212219238, "avg_line_length": 49, "blob_id": "ffee530ea7e482a7261d8b2c3b1aca69e7c9760f", "content_id": "c87aef34afa7525f96eb1a64121a4ebd6d173a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 199, "license_type": "no_license", "max_line_length": 64, "num_lines": 4, "path": "/README.md", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "# Python_projekt_sym-a-pix_fill-a-pix\nGenerator and solver for puzzles:\nSym-a-pix: insert line to create symmetric blocks around dots.\nFill-a-pix: Mark block as black depending on numbers in squares." }, { "alpha_fraction": 0.4417004883289337, "alphanum_fraction": 0.46180984377861023, "avg_line_length": 37.54421615600586, "blob_id": "18fa665ab90c15a17c90497541ef4c53a150edcb", "content_id": "f7efeda23939314049d57d2448bb75c9b51575d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5669, "license_type": "no_license", "max_line_length": 107, "num_lines": 147, "path": "/symapix/puzzle/generator.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Container for puzzle.\n\"\"\"\n\nimport numpy as np\n\nimport common.misc as misc\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass Generator:\n \"\"\"Generator class for sym-a-pix puzzle.\"\"\"\n def __init__(self, solver, container):\n self.solver = solver\n self.container = container\n self.size = self.container.size\n self.colors = len(self.container.colors)\n\n def generate_random(self):\n \"\"\"\n Generates random sym-a-pix puzzle.\n :returns: None\"\"\"\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if self.solver.solution[i, j] == 0 and np.random.random() < 0.25:\n c = np.random.randint(1, self.colors + 1)\n if self.populate(i, j):\n self.container.puzzle[i, j] = c\n self.solver.solution[i, j] = -2\n\n def correct_lines(self):\n \"\"\"Checks if lines were not put in place of dot.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if not (i % 2 == 0 and j % 2 == 0) and not (i % 2 > 0 and j % 2 > 0):\n if self.solver.puzzle[i, j] > 0:\n self.solver.solution[i, j] = -2\n [a, b], [c, d] = misc.squares_next_to(i, j)\n corner_dot = self.solver.dot_in_corner(a, b, c, d)\n if corner_dot != [-1, -1]:\n self.solver.solution[i, j] = -2\n\n def populate(self, x, y):\n \"\"\"\n Given point, creates symmetric shape around.\n :param x: position\n :param y: position\n :return: if it was successful\n \"\"\"\n frame = misc.define_frame(x, y)\n closed = True\n for f in frame:\n if not self.solver.is_wall(*f):\n closed = False\n if closed:\n return closed\n visited = misc.define_block(x, y)\n for v in visited:\n if self.solver.contains_dot(*v):\n return False\n return True\n\n def remove_redundant_walls(self):\n \"\"\"Removes any redundant walls inside blocks.\"\"\"\n for i in range(0, self.size[0]):\n for j in range(0, self.size[1]):\n if self.solver.puzzle[i, j] > 0:\n queue = misc.define_block(i, j)\n visited = []\n while queue:\n q = queue.pop()\n visited.append(q)\n queue2 = misc.adjacent_squares(*q)\n for q2 in queue2:\n if q2 not in visited and \\\n not self.solver.is_wall(*misc.wall_between(q[0], q[1], q2[0], q2[1])) and \\\n self.solver.is_inside(*q2):\n queue.append(q2)\n\n block = misc.get_unique(np.array(visited))\n all_walls = []\n for b in block:\n all_walls.append(misc.define_frame(b[0], b[1]))\n all_walls = np.array(all_walls).reshape(-1, 2)\n red_walls = np.array([x for x in all_walls if misc.count(all_walls, x) > 1])\n for w in red_walls:\n self.solver.solution[w[0], w[1]] = 0\n\n def fill_dots(self):\n \"\"\"Fills dots in empty blocks.\"\"\"\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if i % 2 == 0 and j % 2 == 0 and self.solver.solution[i, j] == 0:\n if self.fill_block(i, j, np.random.randint(1, self.colors + 1)):\n return\n\n def fill_block(self, x, y, c):\n \"\"\"\n Fills unfilled blocks in puzzle with dots.\n :param x: position\n :param y: position\n :param c: color to fill\n :return:\n \"\"\"\n queue = misc.define_block(x, y)\n visited = []\n while queue:\n q = queue.pop()\n visited.append(q)\n queue2 = misc.adjacent_squares(*q)\n for q2 in queue2:\n if q2 not in visited and \\\n not self.solver.is_wall(*misc.wall_between(q[0], q[1], q2[0], q2[1])) and \\\n self.solver.is_inside(*q2):\n queue.append(q2)\n\n block = misc.get_unique(np.array(visited))\n if len(block) == 1:\n b = block[0]\n self.solver.puzzle[b[0], b[1]] = c\n self.solver.solution[b[0], b[1]] = c\n elif len(block) == 2:\n new_dot = misc.wall_between(block[0][0], block[0][1], block[1][0], block[1][1])\n self.solver.puzzle[new_dot[0], new_dot[1]] = c\n self.solver.solution[block[0][0], block[0][1]] = c\n self.solver.solution[block[1][0], block[1][1]] = c\n else:\n # check if symmetric\n xs = [a[0] for a in block]\n ys = [a[1] for a in block]\n dot = [int((min(xs) + max(xs))/2), int((min(ys) + max(ys))/2)]\n symmetric = True\n for b in block:\n sym_b = misc.symmetric_point(dot[0], dot[1], b[0], b[1])\n if [sym_b[0], sym_b[1]] not in block.tolist():\n symmetric = False\n if symmetric:\n self.solver.puzzle[dot[0], dot[1]] = c\n for b in block:\n self.solver.solution[b[0], b[1]] = c\n else:\n new_dot = block[np.random.randint(len(block))]\n self.solver.puzzle[new_dot[0], new_dot[1]] = c\n return True\n return False\n\n\n\n" }, { "alpha_fraction": 0.4243106245994568, "alphanum_fraction": 0.43922340869903564, "avg_line_length": 33.49514389038086, "blob_id": "bb89e53b78c9ec6dd2b1d16e54efbd94b8c20f14", "content_id": "5ddc1439472a04eac0301857b45dd1868b035e9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3554, "license_type": "no_license", "max_line_length": 94, "num_lines": 103, "path": "/fillapix/puzzle/container.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Container for puzzle.\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport pickle\nimport sys\n\nfrom classifiers import classifier\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass Container:\n \"\"\"Stores puzzle data.\"\"\"\n def __init__(self, size, from_file=True):\n \"\"\" Initialization of container.\n :param size: size of a puzzle\n :param from_file: loads classifier if puzzle is initialized from file\n \"\"\"\n self.size = size\n self.puzzle = np.zeros((size[0], size[1]))\n if from_file:\n if sys.version_info < (3, 0):\n self.classifier = pickle.load(classifier.get('digit'))\n else:\n self.classifier = pickle.load(classifier.get('digit'), encoding='latin1')\n\n def insert(self, image, x, y):\n \"\"\"\n Inserts data into puzzle.\n :param image: fragment of full image to be processed\n :param x: position\n :param y: position\n :return: None\n \"\"\"\n image = image[:-2, :]\n image = cv2.resize(image, (15, 15))\n number = self.classifier.predict(image.reshape(1, -1))\n self.puzzle[x, y] = int(number)\n\n def print_puzzle(self):\n \"\"\"\n For testing: prints current puzzle.\n :return: None\n \"\"\"\n for row in self.puzzle:\n txt = ''\n for el in row:\n if el == 100:\n txt += '_ '\n else:\n txt += str(int(el)) + ' '\n print(txt)\n\n def get_board(self):\n \"\"\"\n Getter for puzzle board\n :return: puzzle board\n \"\"\"\n return self.puzzle\n\n def generate_random(self):\n \"\"\"\n Generates random fill-a-pix puzzle.\n :return: solution of generated puzzle\n \"\"\"\n self.puzzle += 100\n solution = np.zeros(self.size)\n for i, row in enumerate(self.puzzle):\n for j, el in enumerate(row):\n if np.random.random() < 0.5:\n # number of black squares in neighbourhood\n curr = len([[a, b] for a in range(max(0, i - 1), min(i + 2, self.size[0]))\n for b in range(max(0, j - 1), min(j + 2, self.size[1]))\n if solution[a, b] == 1])\n\n # unfilled squares in neighbourhood (not including surely unfilled)\n small = [[a, b] for a in range(max(0, i - 1), min(i + 2, self.size[0]))\n for b in range(max(0, j - 1), min(j + 2, self.size[1]))\n if solution[a, b] == 0]\n if curr < len(small):\n el = np.random.randint(curr, len(small) + 1)\n self.puzzle[i, j] = el\n while curr < el:\n for (x, y) in small:\n if solution[x, y] == 0:\n if np.random.random() < 0.9:\n solution[x, y] = 1\n curr += 1\n if el == curr:\n break\n for (x, y) in small:\n if solution[x, y] == 0:\n solution[x, y] = -1\n\n for i in range(self.size[0]):\n for j in range(self.size[1]):\n if solution[i, j] == 0:\n solution[i, j] = -1\n return solution\n\n" }, { "alpha_fraction": 0.5114465355873108, "alphanum_fraction": 0.543647825717926, "avg_line_length": 43.16666793823242, "blob_id": "93764b90abefecac5f569cb0dff20c87ee910362", "content_id": "245f8f67ec8032e0d892aae3303fb324b909fc9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3975, "license_type": "no_license", "max_line_length": 116, "num_lines": 90, "path": "/symapix/imageops/reader.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Sym-a-pix: Processing operation on images - reading puzzle from image.\n\"\"\"\n\nimport cv2\n\nfrom common.imageops import get_line_positions\nfrom symapix.puzzle.container import Container\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\nclass SymAPixReader:\n \"\"\"Reader for sym-a-pix puzzle.\"\"\"\n\n def __init__(self, filename):\n \"\"\" Reads puzzle from picture.\n :param filename: name of file with image of puzzle.\n :return: None\n \"\"\"\n self.img_rgb = cv2.imread(str(filename), cv2.IMREAD_COLOR)\n if self.img_rgb is None:\n raise IOError('File not found')\n self.img_gray = cv2.cvtColor(self.img_rgb, cv2.COLOR_BGR2GRAY)\n self.img_edges = None\n self.rho_vertical = []\n self.rho_horizontal = []\n # self.count = 0\n\n def create_puzzle(self):\n \"\"\"\n Creates new puzzle. Detects lines on image then cuts smaller images and passes them to container.\n :return: puzzle\n \"\"\"\n self.rho_horizontal, self.rho_vertical = get_line_positions(self.img_gray)\n puzzle = Container((len(self.rho_horizontal) - 1, len(self.rho_vertical) - 1))\n # normal\n for x in range(len(self.rho_horizontal) - 1):\n for y in range(len(self.rho_vertical) - 1):\n puzzle.insert(self.cut_image(x, y, 0), x, y, 0)\n # shifted in x\n for x in range(1, len(self.rho_horizontal) - 1):\n for y in range(len(self.rho_vertical) - 1):\n puzzle.insert(self.cut_image(x, y, 1), x, y, 1)\n # shifted in y\n for x in range(len(self.rho_horizontal) - 1):\n for y in range(1, len(self.rho_vertical) - 1):\n puzzle.insert(self.cut_image(x, y, 2), x, y, 2)\n # shifted in both\n for x in range(1, len(self.rho_horizontal) - 1):\n for y in range(1, len(self.rho_vertical) - 1):\n puzzle.insert(self.cut_image(x, y, 3), x, y, 3)\n return puzzle\n\n def cut_image(self, x, y, mode=0):\n \"\"\" Cuts part of an image depending on position of lines.\n :param x: position\n :param y: position\n :param mode: mode=0 - cuts normally, mode=1 cuts shifted in x, mode=2 cuts shifted in y, mode=3 cuts shifted\n in x and y\n :return: part of an image\n \"\"\"\n if mode == 0:\n i1, i2 = 2 + self.rho_horizontal[x], self.rho_horizontal[x + 1] - 1\n j1, j2 = 2 + self.rho_vertical[y], self.rho_vertical[y + 1] - 1\n elif mode == 1:\n assert (0 < x < len(self.rho_horizontal) - 1)\n i1, i2 = 2 + (self.rho_horizontal[x - 1] + self.rho_horizontal[x]) / 2.0, \\\n (self.rho_horizontal[x] + self.rho_horizontal[x + 1]) / 2.0 - 1\n j1, j2 = 2 + self.rho_vertical[y], self.rho_vertical[y + 1] - 1\n elif mode == 2:\n assert (0 < y < len(self.rho_vertical) - 1)\n i1, i2 = 2 + self.rho_horizontal[x], self.rho_horizontal[x + 1] - 1\n j1, j2 = 1 + (self.rho_vertical[y - 1] + self.rho_vertical[y]) / 2.0, \\\n (self.rho_vertical[y] + self.rho_vertical[y + 1]) / 2.0 - 1\n elif mode == 3:\n assert (0 < x < len(self.rho_horizontal) - 1 and 0 < y < len(self.rho_vertical) - 1)\n i1, i2 = 2 + (self.rho_horizontal[x - 1] + self.rho_horizontal[x]) / 2.0, \\\n (self.rho_horizontal[x] + self.rho_horizontal[x + 1]) / 2.0 - 1\n j1, j2 = 1 + (self.rho_vertical[y - 1] + self.rho_vertical[y]) / 2.0, \\\n (self.rho_vertical[y] + self.rho_vertical[y + 1]) / 2.0 - 1\n else:\n i1, i2, j1, j2 = 0, 0, 0, 0\n i1, i2, j1, j2 = int(i1), int(i2), int(j1), int(j2)\n return self.img_rgb[i1: i2, j1: j2]\n\n def get_lines(self):\n \"\"\"Returns number of vertical in horizontal lines (this is also size + 1)\"\"\"\n return len(self.rho_horizontal), len(self.rho_vertical)\n" }, { "alpha_fraction": 0.45008718967437744, "alphanum_fraction": 0.4860505759716034, "avg_line_length": 31.08391571044922, "blob_id": "e6c6a98236408f3097cd94d4eb3201abc3250fde", "content_id": "4e860480a65ec837fb12390f895faf41f0e7bf32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4588, "license_type": "no_license", "max_line_length": 106, "num_lines": 143, "path": "/symapix/puzzle/container.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Container for puzzle.\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport pickle\nimport math\nimport sys\n\nfrom classifiers import classifier\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\n# Colors possible to use when creating random game.\nCOLORS = [[0, 0, 0], [255, 255, 255], [60, 69, 177],\n [17, 23, 105], [60, 133, 177], [127, 202, 247],\n [116, 75, 46], [69, 39, 16], [62, 135, 46],\n [113, 189, 97]]\n\n\ndef dist(x, y):\n \"\"\"Turns bgr points to float, returns distance between points\"\"\"\n x = np.array(x, float)\n y = np.array(y, float)\n return math.sqrt((x[0]-y[0])**2 + (x[1] - y[1])**2 + (x[2] - y[2])**2)\n\n\nclass Container:\n \"\"\"Stores puzzle data.\"\"\"\n def __init__(self, size):\n \"\"\"\n Initialization of container.\n :param: size: width and height of puzzle\n :returns: None\n \"\"\"\n self.size = (size[0] * 2 - 1, size[1] * 2 - 1)\n self.puzzle = np.zeros((self.size[0], self.size[1])) - 1\n self.colors = []\n if sys.version_info < (3, 0):\n self.sq_clf = pickle.load(classifier.get('square'))\n self.horiz_clf = pickle.load(classifier.get('horizontal'))\n self.vert_clf = pickle.load(classifier.get('vertical'))\n self.x_clf = pickle.load(classifier.get('x'))\n else:\n self.sq_clf = pickle.load(classifier.get('square'), encoding='latin1')\n self.horiz_clf = pickle.load(classifier.get('horizontal'), encoding='latin1')\n self.vert_clf = pickle.load(classifier.get('vertical'), encoding='latin1')\n self.x_clf = pickle.load(classifier.get('x'), encoding='latin1')\n\n def set_puzzle(self, puzzle):\n \"\"\"\n Sets puzzle from given array\n :param puzzle: new puzzle\n :return:\n \"\"\"\n self.puzzle = puzzle\n\n def get_board(self):\n \"\"\"Returns puzzle board.\"\"\"\n return self.puzzle\n\n def set_colors(self, color):\n \"\"\"Sets possible colors depending on number chosen by user.\"\"\"\n self.colors = COLORS[: color]\n\n def insert(self, img_rgb, x, y, mode):\n \"\"\"\n Inserts data into puzzle.\n :param img_rgb: fragment of full image to be processed in rgb\n :param x: position\n :param y: position\n :param mode: part of puzzle, 0 - window, 1 - horizontal line, 2 - vertical line, 3 - line crossing\n :return: None\n \"\"\"\n img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)\n image = cv2.resize(img_gray, (20, 20))\n number = 0\n i, j = 0, 0\n if mode == 0:\n number = self.sq_clf.predict(image.reshape(1, -1))\n i = 2 * x\n j = 2 * y\n elif mode == 1:\n number = self.horiz_clf.predict(image.reshape(1, -1))\n i = 2 * x - 1\n j = 2 * y\n elif mode == 2:\n number = self.vert_clf.predict(image.reshape(1, -1))\n i = 2 * x\n j = 2 * y - 1\n elif mode == 3:\n number = self.x_clf.predict(image.reshape(1, -1))\n i = 2 * x - 1\n j = 2 * y - 1\n if number > 0:\n number = self.get_color(img_rgb)\n self.puzzle[i, j] = int(number)\n\n def print_puzzle(self):\n \"\"\"\n For tests: prints current puzzle.\n :return: None\n \"\"\"\n for i, row in enumerate(self.puzzle):\n txt = ''\n for j, el in enumerate(row):\n if el == 0:\n if i % 2 == 0 and j % 2 == 0:\n txt += ' '\n elif i % 2 == 0 and j % 2 > 0:\n txt += '| '\n elif i % 2 > 0 and j % 2 == 0:\n txt += '_ '\n elif i % 2 > 0 and j % 2 > 0:\n txt += '+ '\n else:\n txt += str(int(el)) + ' '\n print(txt)\n\n def get_color(self, img):\n \"\"\"Reads color of dot on image and adds to list of colors (if color is not on it, yet)\"\"\"\n w, h, _ = img.shape\n color = img[int(w/2.0), int(h/2.0)]\n curr = 0\n if len(self.colors) == 0:\n self.colors.append(color)\n return 1\n for i, c in enumerate(self.colors):\n if dist(c, color) < 10:\n curr = i + 1\n break\n if curr == 0:\n self.colors.append(color)\n return len(self.colors)\n else:\n return curr\n\n def get_colors(self):\n \"\"\"Returns list of colors.\"\"\"\n return self.colors\n" }, { "alpha_fraction": 0.5474961400032043, "alphanum_fraction": 0.5588022470474243, "avg_line_length": 40.38888931274414, "blob_id": "0bc717ca603f40a645d7923c160668434fb3cc49", "content_id": "04ba0209f6fa0a1729aedcf7384d277d21abcd38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19370, "license_type": "no_license", "max_line_length": 118, "num_lines": 468, "path": "/gui/main_window.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Main window of Sym-a-pix and Fill-a-pix solver/generator program.\n\"\"\"\nfrom __future__ import division, print_function\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import Qt\nimport sys\n\nfrom fillapix.puzzle import container as fc\nfrom symapix.puzzle import container as sc\nfrom symapix.imageops.reader import SymAPixReader\nfrom symapix.solver.solver import SymAPixSolver\nfrom symapix.puzzle.generator import Generator\nfrom fillapix.imageops.reader import FillAPixReader\nfrom fillapix.solver.solver import FillAPixSolver\nfrom gui.generate_fill_dialog import GenerateFillDialog\nfrom gui.generate_sym_dialog import GenerateSymDialog\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\nSIZE = 800\nSQUARE = 30\nEPS = 5\n\n\nclass MainWindow(QtGui.QMainWindow):\n def __init__(self):\n \"\"\"Initialization of class.\"\"\"\n super(MainWindow, self).__init__()\n self.gfd = GenerateFillDialog(self)\n self.gsd = GenerateSymDialog(self)\n self.status_bar = self.statusBar()\n self.l = QtGui.QVBoxLayout()\n self.content = QtGui.QVBoxLayout()\n\n self.button_part = QtGui.QHBoxLayout()\n self.curr_game_label = QtGui.QLabel('Currently playing: no game')\n self.curr_game = 0\n self.solve_btn = QtGui.QPushButton('Solve')\n self.clear_btn = QtGui.QPushButton('Clear')\n self.check_btn = QtGui.QPushButton('Check')\n\n self.puzzle_part = QtGui.QVBoxLayout()\n self.painter = QtGui.QPainter()\n self.board = QtGui.QLabel()\n self.pix_map = QtGui.QPixmap(SIZE, SIZE)\n\n self.puzzle = None\n self.solver = None\n self.vertical_lines = 0\n self.horizontal_lines = 0\n self.game_size = []\n\n self.init_gui()\n\n def init_gui(self):\n \"\"\"Initialization of UI.\"\"\"\n # Window setup\n self.setWindowTitle('Puzzles')\n self.resize(SIZE, SIZE + 100)\n cw = QtGui.QWidget()\n self.setCentralWidget(cw)\n cw.setLayout(self.l)\n\n # Menu setup\n # Sym-a-pix actions\n load_sym = QtGui.QAction('Load puzzle', self)\n load_sym.setStatusTip('Sym-a-pix: Load puzzle from file.')\n load_sym.triggered.connect(self.load_sym_from_file)\n\n gen_sym = QtGui.QAction('Generate puzzle', self)\n gen_sym.setStatusTip('Sym-a-pix: Generate random puzzle.')\n gen_sym.triggered.connect(self.generate_sym)\n\n # Fill-a-pix actions\n load_fill = QtGui.QAction('Load puzzle', self)\n load_fill.setStatusTip('Fill-a-pix: Load puzzle from file.')\n load_fill.triggered.connect(self.load_fill_from_file)\n\n gen_fill = QtGui.QAction('Generate puzzle', self)\n gen_fill.setStatusTip('Fill-a-pix: Generate random puzzle.')\n gen_fill.triggered.connect(self.generate_fill)\n\n menu_bar = self.menuBar()\n sym_menu = menu_bar.addMenu('&Sym-a-pix')\n sym_menu.addAction(load_sym)\n sym_menu.addAction(gen_sym)\n\n fill_menu = menu_bar.addMenu('&Fill-a-pix')\n fill_menu.addAction(load_fill)\n fill_menu.addAction(gen_fill)\n\n # Window's content setup\n self.content.addWidget(self.curr_game_label)\n # Canvas\n self.pix_map.fill(Qt.white)\n\n self.board.setPixmap(self.pix_map)\n self.board.setMouseTracking(True)\n self.puzzle_part.addWidget(self.board)\n self.content.addLayout(self.puzzle_part)\n # Buttons\n self.solve_btn.clicked.connect(self.solve_game)\n self.clear_btn.clicked.connect(self.clear_game)\n self.check_btn.clicked.connect(self.check_game)\n self.button_part.addWidget(self.solve_btn)\n self.button_part.addWidget(self.clear_btn)\n self.button_part.addWidget(self.check_btn)\n self.button_part.setAlignment(Qt.AlignTop)\n self.content.addLayout(self.button_part)\n\n self.l.addLayout(self.content)\n self.show()\n\n def load_sym_from_file(self):\n \"\"\"Loads sym-a-pix puzzle from file.\"\"\"\n self.status_bar.showMessage('Solving...')\n file_name = QtGui.QFileDialog.getOpenFileName(parent=self, caption='Open file', directory='.', filter='*.jpg')\n try:\n if '.jpg' not in file_name:\n raise IOError\n self.change_curr_game(1)\n reader = SymAPixReader(file_name)\n self.puzzle = reader.create_puzzle()\n self.horizontal_lines, self.vertical_lines = reader.get_lines()\n self.solver = SymAPixSolver(self.puzzle)\n self.game_size = self.solver.size\n self.solver.solve()\n self.draw_game()\n self.status_bar.showMessage('Loaded puzzle from file: {}'.format(file_name.split('/')[-1]))\n except IOError:\n self.status_bar.showMessage('Cannot read file: {}'.format(file_name.split('/')[-1]))\n\n def generate_sym(self):\n \"\"\"Opens dialog where user can set size of puzzle to be generated.\"\"\"\n self.gsd.show()\n\n def generate_new_sym(self, width, height, color):\n \"\"\"\n Generates new puzzle, puzzle is then showed to user.\n :param width: width of puzzle\n :param height: height of puzzle\n :param color: number of colors used\n :return:\n \"\"\"\n self.change_curr_game(1)\n self.puzzle = sc.Container((height, width))\n self.puzzle.set_colors(color)\n self.horizontal_lines, self.vertical_lines = width + 1, height + 1\n self.solver = SymAPixSolver(self.puzzle)\n self.game_size = self.solver.size\n generator = Generator(self.solver, self.puzzle)\n generator.generate_random()\n while not self.solver.is_solved():\n self.solver.solve()\n self.solver.correct_solution()\n generator.correct_lines()\n generator.fill_dots()\n self.solver.correct_solution()\n generator.correct_lines()\n generator.remove_redundant_walls()\n self.draw_game()\n\n def load_fill_from_file(self):\n \"\"\"Loads fill-a-pix puzzle from file.\"\"\"\n self.status_bar.showMessage('Solving...')\n file_name = QtGui.QFileDialog.getOpenFileName(parent=self, caption='Open file', directory='.', filter='*.jpg')\n try:\n if '.jpg' not in file_name:\n raise IOError\n self.change_curr_game(2)\n reader = FillAPixReader(file_name)\n self.puzzle = reader.create_puzzle()\n self.horizontal_lines, self.vertical_lines = reader.get_lines()\n self.solver = FillAPixSolver(self.puzzle)\n self.game_size = self.solver.size\n self.solver.solve()\n self.draw_game()\n self.status_bar.showMessage('Loaded puzzle from file: {}'.format(file_name.split('/')[-1]))\n except IOError:\n self.status_bar.showMessage('Cannot read file: {}'.format(file_name.split('/')[-1]))\n\n def generate_fill(self):\n \"\"\"Opens dialog where user can set size of puzzle to be generated.\"\"\"\n self.gfd.show()\n\n def generate_new_fill(self, width, height):\n \"\"\"\n Generates new puzzle, puzzle is then showed to user.\n :param width: width of puzzle\n :param height: height of puzzle\n :return:\n \"\"\"\n self.change_curr_game(2)\n self.puzzle = fc.Container((height, width))\n solution = self.puzzle.generate_random()\n self.horizontal_lines, self.vertical_lines = width + 1, height + 1\n self.solver = FillAPixSolver(self.puzzle)\n self.game_size = self.solver.size\n self.solver.set_solution(solution)\n self.draw_game()\n\n def change_curr_game(self, game):\n \"\"\"Sets value of label with current game.\"\"\"\n self.curr_game = game\n if self.curr_game == 0:\n self.curr_game_label.setText('Currently playing: no game')\n elif self.curr_game == 1:\n self.curr_game_label.setText('Currently playing: Sym-a-pix')\n elif self.curr_game == 2:\n self.curr_game_label.setText('Currently playing: Fill-a-pix')\n\n def mousePressEvent(self, event):\n \"\"\"Overwrites QWidget function: catches mouse press events.\n Depending on type of game performs action.\n After that checks if game is solved.\"\"\"\n x, y = self.get_painter_pos(event.x(), event.y())\n if x == -1 and y == -1:\n return\n if self.curr_game == 1:\n if x % SQUARE < EPS:\n self.change_line(int((x - x % SQUARE) / SQUARE * 2 - 1), int((y - y % SQUARE) / SQUARE * 2))\n elif SQUARE - EPS < x % SQUARE:\n self.change_line(int((x - x % SQUARE + SQUARE) / SQUARE * 2 - 1), int((y - y % SQUARE) / SQUARE * 2))\n elif y % SQUARE < EPS:\n self.change_line(int((x - x % SQUARE) / SQUARE * 2), int((y - y % SQUARE) / SQUARE * 2 - 1))\n elif SQUARE - EPS < y % SQUARE:\n self.change_line(int((x - x % SQUARE) / SQUARE * 2), int((y - y % SQUARE + SQUARE) / SQUARE * 2 - 1))\n self.draw_game()\n\n elif self.curr_game == 2:\n if 0 <= x < self.vertical_lines - 1 and 0 <= y < self.horizontal_lines - 1:\n self.change_square(x, y)\n self.draw_game()\n\n self.check_solved()\n\n def get_painter_pos(self, i, j):\n \"\"\"Given position of mouse click and type of game, returns clicked line or square position.\"\"\"\n i = (i - 5) * ((self.vertical_lines + 1) * SQUARE) / 800\n j = (j - 55) * ((self.horizontal_lines + 1) * SQUARE) / 800\n if self.curr_game == 1:\n if i > SQUARE and j > SQUARE:\n return i - SQUARE, j - SQUARE\n else:\n return -1, -1\n\n elif self.curr_game == 2:\n if i > SQUARE and j > SQUARE:\n return int((i - SQUARE) / SQUARE), int((j - SQUARE) / SQUARE)\n else:\n return -1, -1\n return -1, -1\n\n def draw_game(self):\n \"\"\"Chooses what game to draw.\"\"\"\n self.draw_lines()\n if self.curr_game == 1:\n self.draw_sym()\n self.draw_border()\n elif self.curr_game == 2:\n self.draw_fill()\n\n def draw_sym(self):\n \"\"\"Draws sym-a-pix game.\"\"\"\n self.draw_squares_sym()\n self.draw_solution_lines()\n self.draw_circles()\n\n def draw_fill(self):\n \"\"\"Draws fill-a-pix game.\"\"\"\n self.draw_squares_fill()\n self.draw_numbers()\n\n def draw_lines(self):\n \"\"\"Draws lines of game.\"\"\"\n self.pix_map.fill(Qt.white)\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n for line in range(1, self.horizontal_lines + 1):\n if self.curr_game == 2:\n self.painter.setPen(Qt.black)\n else:\n self.painter.setPen(Qt.lightGray)\n self.painter.drawLine(SQUARE, line * SQUARE, self.vertical_lines * SQUARE, line * SQUARE)\n for line in range(1, self.vertical_lines + 1):\n if self.curr_game == 2:\n self.painter.setPen(Qt.black)\n else:\n self.painter.setPen(Qt.lightGray)\n self.painter.drawLine(line * SQUARE, SQUARE, line * SQUARE, self.horizontal_lines * SQUARE)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def draw_border(self):\n \"\"\"Draws border of the sym-a-pix game.\"\"\"\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n for line in range(1, self.horizontal_lines + 1):\n if line in [1, self.horizontal_lines]:\n pen = QtGui.QPen()\n pen.setColor(Qt.black)\n pen.setWidth(3)\n self.painter.setPen(pen)\n self.painter.drawLine(SQUARE, line * SQUARE, self.vertical_lines * SQUARE, line * SQUARE)\n for line in range(1, self.vertical_lines + 1):\n if line in [1, self.vertical_lines]:\n pen = QtGui.QPen()\n pen.setColor(Qt.black)\n pen.setWidth(3)\n self.painter.setPen(pen)\n self.painter.drawLine(line * SQUARE, SQUARE, line * SQUARE, self.horizontal_lines * SQUARE)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def draw_solution_lines(self):\n \"\"\"Draws user selected lines in sym-a-pix game.\"\"\"\n curr_user_solution = self.solver.get_user_solution()\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n pen = QtGui.QPen()\n pen.setColor(Qt.darkGray)\n pen.setWidth(3)\n self.painter.setPen(pen)\n for i, row in enumerate(curr_user_solution):\n for j, el in enumerate(row):\n if not (i % 2 == 0 and j % 2 == 0) and not (i % 2 == 1 and j % 2 == 1):\n try:\n if curr_user_solution[j, i] == 1:\n if i % 2 == 0:\n self.painter.drawLine(SQUARE * (i/2 + 1), SQUARE * (j/2+1.5),\n SQUARE * (i/2 + 2), SQUARE * (j/2+1.5))\n elif j % 2 == 0:\n self.painter.drawLine(SQUARE * (i/2+1.5), SQUARE * (j/2 + 1),\n SQUARE * (i/2+1.5), SQUARE * (j/2 + 2))\n except IndexError:\n pass\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def draw_numbers(self):\n \"\"\"Draws numbers in fill-a-pix game.\"\"\"\n curr_user_solution = self.solver.get_user_solution()\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n font = QtGui.QFont('Arial')\n font.setPointSize(22)\n self.painter.setFont(font)\n for i, row in enumerate(self.solver.puzzle):\n for j, el in enumerate(row):\n if el < 100:\n val = str(int(el))\n if curr_user_solution[i, j] == 1:\n self.painter.setPen(Qt.white)\n else:\n self.painter.setPen(Qt.black)\n self.painter.drawText(1.25 * SQUARE + j * SQUARE, 1.85 * SQUARE + i * SQUARE, val)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def draw_circles(self):\n \"\"\"Draws circles in sym-a-pix.\"\"\"\n colors = self.puzzle.get_colors()\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n for i, row in enumerate(self.solver.puzzle):\n for j, el in enumerate(row):\n if el > 0:\n color = colors[int(el) - 1]\n if color[0] == 0 and color[1] == 0 and color[2] == 0:\n self.painter.setPen(Qt.lightGray)\n else:\n self.painter.setPen(Qt.black)\n self.painter.setBrush(QtGui.QColor(color[2], color[1], color[0]))\n self.painter.drawEllipse(QtCore.QPoint(SQUARE * 1.5 + SQUARE * j / 2.0,\n SQUARE * 1.5 + SQUARE * i / 2.0), 5, 5)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def change_square(self, i, j):\n \"\"\"Changes color of square and value of user solution in solver.\"\"\"\n i, j = j, i\n curr_val = self.solver.get_user_value(i, j)\n if curr_val == 1:\n self.solver.set_user_value(i, j, -1)\n else:\n self.solver.set_user_value(i, j, curr_val + 1)\n\n def change_line(self, i, j):\n \"\"\"Changes line selected by user. Line unselected <-> line selected.\"\"\"\n i, j = j, i\n val = self.solver.get_user_value(i, j)\n if val is not None:\n self.solver.set_user_value(i, j, (val + 1) % 2)\n\n def draw_squares_sym(self):\n \"\"\"Fills squares in sym-a-pix game, if they are part of closed block.\"\"\"\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n color_board = self.solver.get_color_board()\n colors = self.solver.get_colors()\n for i, row in enumerate(color_board):\n for j, el in enumerate(row):\n if i % 2 == 0 and j % 2 == 0 and el > 0:\n c = colors[el - 1]\n self.painter.setBrush(QtGui.QColor(c[2], c[1], c[0]))\n self.painter.setPen(QtGui.QColor(c[2], c[1], c[0]))\n self.painter.drawRect(SQUARE * (j/2 + 1), SQUARE * (i/2 + 1),\n SQUARE, SQUARE)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def draw_squares_fill(self):\n \"\"\"Draws squares in fill-a-pix game: filled, unfilled, unsure.\"\"\"\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n curr_user_solution = self.solver.get_user_solution()\n for i, row in enumerate(curr_user_solution):\n for j, el in enumerate(row):\n if el == -1:\n self.painter.setBrush(Qt.lightGray)\n elif el == 1:\n self.painter.setBrush(Qt.black)\n if el != 0:\n self.painter.drawRect(SQUARE * (j + 1), SQUARE * (i + 1),\n SQUARE, SQUARE)\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n def solve_game(self):\n \"\"\"Gives solution to user.\"\"\"\n self.solver.set_solved()\n self.draw_game()\n\n def clear_game(self):\n \"\"\"Clears game to initial state.\"\"\"\n self.solver.clear_user_solution()\n self.draw_game()\n\n def check_game(self):\n \"\"\"Let's user allow if there are any mistakes.\"\"\"\n x, y = self.solver.check_user_solution()\n if x > -1 and y > -1:\n self.status_bar.showMessage('You have mistake in: ({}, {})'.format(y + 1, x + 1))\n else:\n self.status_bar.showMessage('Correct!')\n\n def check_solved(self):\n \"\"\"Checks if user solved the game.\"\"\"\n if self.solver is not None:\n if self.solver.is_solved_by_user():\n self.painter.begin(self.pix_map)\n self.painter.setWindow(0, 0, (self.vertical_lines + 1) * SQUARE, (self.horizontal_lines + 1) * SQUARE)\n font = QtGui.QFont('Arial')\n font.setPointSize(22)\n self.painter.setFont(font)\n self.painter.setPen(Qt.red)\n self.painter.drawText(((self.vertical_lines - 2) * SQUARE)/2, SQUARE - 1, 'SOLVED!')\n self.painter.end()\n self.board.setPixmap(self.pix_map)\n\n\ndef main_window():\n \"\"\"Runs game's main window.\"\"\"\n app = QtGui.QApplication(sys.argv)\n ex = MainWindow()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5730336904525757, "alphanum_fraction": 0.6037847399711609, "avg_line_length": 25.841270446777344, "blob_id": "68b0fc91c9bb46202331047aa238a07be93f94a4", "content_id": "892c14b59dd6383d636edfcd74c7a6344dc861d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1691, "license_type": "no_license", "max_line_length": 98, "num_lines": 63, "path": "/common/imageops.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\" Common image operations.\n\"\"\"\n\nimport numpy as np\nimport math\n\nimport cv2\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\nDEGREE_VERTICAL = 0 # 0 degrees\nDEGREE_HORIZONTAL = 1.5708 # pi/2 degrees\nEPS = 0.0001\n\n\ndef get_unique_lines(rhos):\n \"\"\"\n Joins lines that are to close to each other.\n :param rhos: list of lines' positions\n :return: list without duplicates\n \"\"\"\n rhos.sort()\n tmp = []\n it = 0\n while it < len(rhos) - 1:\n if rhos[it + 1] - rhos[it] < 10:\n tmp.append(int((rhos[it] + rhos[it+1])/2.0))\n it += 1\n else:\n tmp.append(int(rhos[it]))\n it += 1\n if rhos[-1] - tmp[-1] > 10:\n tmp.append(int(rhos[-1]))\n return tmp\n\n\ndef get_line_positions(img, sensitivity=100):\n \"\"\"\n Using Hough transformation detects lines on image. Detects only vertical and horizontal lines.\n :param sensitivity: Hough transformation parameter\n :param img: Image\n :return: positions of horizontal and vertical lines\n \"\"\"\n edges = cv2.Canny(img, 50, 150, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, sensitivity)\n if lines is None:\n lines = cv2.HoughLines(edges, 1, np.pi / 180, int(sensitivity/2))\n\n rho_horizontal = []\n rho_vertical = []\n for row in lines:\n rho, theta = row[0]\n if math.fabs(theta - DEGREE_HORIZONTAL) < EPS:\n rho_horizontal.append(rho)\n elif math.fabs(theta - DEGREE_VERTICAL) < EPS:\n rho_vertical.append(rho)\n\n rho_horizontal = get_unique_lines(rho_horizontal)\n rho_vertical = get_unique_lines(rho_vertical)\n\n return rho_horizontal, rho_vertical\n" }, { "alpha_fraction": 0.40894338488578796, "alphanum_fraction": 0.4507753252983093, "avg_line_length": 27.295917510986328, "blob_id": "4e4e8c0cd9a1f3a864815e5b976919867cbd0b94", "content_id": "ae5572ac89af1dd7df7da76b5fb7abdc0b9b7934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2773, "license_type": "no_license", "max_line_length": 103, "num_lines": 98, "path": "/common/misc.py", "repo_name": "JrMasterno1/Python-project-sym-a-pix-fill-a-pix", "src_encoding": "UTF-8", "text": "\"\"\"Miscellaneous common functions.\"\"\"\n\nimport math\nimport numpy as np\n\n__author__ = 'Adriana Borowa'\n__email__ = '[email protected]'\n\n\ndef get_unique(a):\n \"\"\"Returns unique items in np.array\n :param a: array\n :return: unique elements of array\n \"\"\"\n if len(a) > 0:\n a = np.array(a)\n b = np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))\n _, idx = np.unique(b, return_index=True)\n return a[idx]\n else:\n return np.array([])\n\n\ndef define_frame(i, j):\n \"\"\"Defines frame of closest possible walls.\"\"\"\n if i % 2 == 0 and j % 2 == 0:\n return [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]\n elif i % 2 == 0 and j % 2 > 0:\n return [[i, j - 2], [i, j + 2], [i - 1, j - 1], [i - 1, j + 1], [i + 1, j - 1], [i + 1, j + 1]]\n elif i % 2 > 0 and j % 2 == 0:\n return [[i - 2, j], [i + 2, j], [i - 1, j - 1], [i - 1, j + 1], [i + 1, j - 1], [i + 1, j + 1]]\n elif i % 2 > 0 and j % 2 > 0:\n return [[i - 2, j - 1], [i - 2, j + 1], [i - 1, j - 2], [i - 1, j + 2],\n [i + 1, j - 2], [i + 1, j + 2], [i + 2, j - 1], [i + 2, j + 1]]\n\n\ndef define_block(i, j):\n \"\"\"Defines squares in block.\"\"\"\n if i % 2 == 0 and j % 2 == 0:\n return [[i, j]]\n elif i % 2 == 0 and j % 2 > 0:\n return [[i, j - 1], [i, j + 1]]\n elif i % 2 > 0 and j % 2 == 0:\n return [[i - 1, j], [i + 1, j]]\n elif i % 2 > 0 and j % 2 > 0:\n return [[i - 1, j - 1], [i - 1, j + 1],\n [i + 1, j - 1], [i + 1, j + 1]]\n\n\ndef symmetric_point(x, y, a, b):\n \"\"\"Find wall symmetric to given: x, y - point of circle, a, b - point of line\"\"\"\n return 2 * x - a, 2 * y - b\n\n\ndef wall_between(x, y, i, j):\n \"\"\"Finds location of the wall between two squares.\"\"\"\n if x == i:\n return [x, int((y + j) / 2.0)]\n elif y == j:\n return [int((x + i) / 2.0), y]\n\n\ndef squares_next_to(x, y):\n \"\"\"Returns 2 squares next to a wall.\"\"\"\n if x % 2 == 0:\n return [[x, y - 1], [x, y + 1]]\n elif y % 2 == 0:\n return [[x - 1, y], [x + 1, y]]\n return []\n\n\ndef count(array, el):\n \"\"\"Counts elements el in numpy array\"\"\"\n c = 0\n for a in array:\n if a[0] == el[0] and a[1] == el[1]:\n c += 1\n return c\n\n\ndef point_dist(x, y, i, j):\n \"\"\"Calculates distance between points.\"\"\"\n return math.sqrt((x - i) ** 2 + (y - j) ** 2)\n\n\ndef adjacent_squares(x, y):\n \"\"\"Returns list of squares adjacent to given.\"\"\"\n return [[x - 2, y], [x + 2, y], [x, y - 2], [x, y + 2]]\n\n\ndef closest_closed(i, j, array):\n \"\"\"Checks if closest block to dot are filled.\"\"\"\n block = define_block(i, j)\n closed = True\n for b in block:\n if array[b[0], b[1]] < 1:\n closed = False\n return closed\n" } ]
19
marcoslmori/python-fundamentals
https://github.com/marcoslmori/python-fundamentals
c5288b1bcb704d2377ef9a7e5fcef808da95b2b6
027c0f5781fc88bb8cd56c254f706fbb2df6529b
c85cb84b37bbdcf1f7df5ca3d96b5bb81b0955ce
refs/heads/master
2021-01-19T04:13:03.277525
2017-04-14T01:26:47
2017-04-14T01:26:47
87,359,666
0
0
null
2017-04-05T21:48:46
2017-04-05T21:27:42
2017-04-05T21:27:41
null
[ { "alpha_fraction": 0.6853281855583191, "alphanum_fraction": 0.6872586607933044, "avg_line_length": 24.75, "blob_id": "ff47124c90a50792cf5de155ddc8c5ac2ac2a129", "content_id": "ed86c033a044bc78e0684a1b221b9382b7be0cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 85, "num_lines": 40, "path": "/HandsOn/Aula07/exerc2-versionprof.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#exercicio2.py\n#exercicio criar uma lista com varios mais de 2 nomes e insira todos de uma vez sim \n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\nengine = create_engine('sqlite:///banco.db')\nBase = declarative_base()\n\nclass Usuario(Base):\n\t__tablename__ = 'usuarios'\n\tid = Column(Integer, primary_key=True)\n\tnome = Column(String)\n\n# todos as execucoes so serao executadas ai dentro como se fosse no console\n\n\nif __name__ == '__main__':\n Base.metadata.create_all(engine)\n #abre uma sessao\n Session = sessionmaker()\n Session.configure(bind=engine)\n session = Session()\ntry:\n lista_nomes=['Joao', 'Jose', 'Alexandra', 'Sandra']\n \n for i in lista_nomes:\n usuario = Usuario(nome=i)\n session.add(usuario)\n session.commit()\n\n for i in session.query(Usuario).all():\n print i.nome, i.id\n\nexcept exception as e:\n print e\n session.roolback()\n\n\n " }, { "alpha_fraction": 0.6676300764083862, "alphanum_fraction": 0.6705202460289001, "avg_line_length": 23.33333396911621, "blob_id": "14e3d204df6a3aa08309b7b7c8c5178084cbcfdb", "content_id": "30040a79d7e58c6b6f38d3293073772124bd19d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 75, "num_lines": 42, "path": "/HandsOn/Aula07/buscar.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n\nengine = create_engine('sqlite:///banco.db')\nBase = declarative_base()\n\nclass Usuario(Base):\n\t__tablename__ = 'usuarios'\n\tid = Column(Integer, primary_key=True)\n\tnome = Column(String)\n\n\n\n# todos as execucoes so serao executadas ai dentro como se fosse no console\nif __name__ == '__main__':\n Base.metadata.create_all(engine)\n #abre uma sessao\n Session = sessionmaker()\n Session.configure(bind=engine)\n session = Session()\ntry:\n \t# usuario = Usuario(nome=\"Mori\")\n \t# session.add(usuario)\n \t# session.commit()\n\n # esta buscando o id 1\n usuario= session.query(Usuario).get(1)\n # trazer todos usuario = session.query(Usuarios).all()\n # print session.query(Usuario).filter_by(id=1, nome='Mori').all()\n print usuario.nome\n\n \n\n\n\n\nexcept exception as e:\n\tprint e\n\tsession.roolback()\n\n\n\t\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6313559412956238, "alphanum_fraction": 0.6355932354927063, "avg_line_length": 12.941176414489746, "blob_id": "1b2b152b6851637323658fa21202413d1252d446", "content_id": "acf743176a2e461533b4f5e6bf7e9e557514e3a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 22, "num_lines": 17, "path": "/old-class/aula02/decisao.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#decisao.py\nnome = 'B'\n\nif nome:\n\tprint 'PRIMEIRO IF'\n\tif nome == 'D':\n\t\tprint 'SEGUNDO IF'\nelif nome == 'A':\n\tprint 'PRIMEIRO ELIF'\nelif nome == 'C':\n\tprint 'SEGUNDO ELIF'\nelse:\n\tprint 'PRIMEIRO ELSE'\n\nnumero = 1\n\n# switch (numero) dfs" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5098921060562134, "avg_line_length": 24, "blob_id": "75c53a9dcb8826995b99ae3ae255d3f7c97847fc", "content_id": "8b7ea235e156ef7de7a29c13ec2d24119d970584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2224, "license_type": "no_license", "max_line_length": 91, "num_lines": 89, "path": "/HandsOn/Aula08/exec-mongo.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# exec-mongo.py\n\nfrom pymongo import MongoClient\nimport os\n\nflag = True\n\n# quando instancia ja executa\nclient = MongoClient('127.0.0.1')\ndb = client['devops']\n\n\nsession = False\n\nwhile flag:\n banner = '''Menu:\n1) Logar\n2) Cadastrar usuario\n3) Lista usuario\n4) Sair\nSelecione a opcao: '''\n\n option = int(raw_input(banner))\n \n if option == 1:\n os.system(\"clear\")\n user = raw_input('Username: ')\n pswd = raw_input('Password: ')\n\n # query = \"SELECT * FROM users WHERE usuario='%s' AND pass='%s'\" % (user, pswd)\n query = db.fila.find({\"nome\" : user, \"senha\" : pswd })\n\n # cur.execute(query)\n\n # usuario = cur.fetchone()\n\n\n if query.count() != 0:\n session=True\n print 'Login com sucesso'\n else:\n print 'Username ou password invalidos'\n \n elif option == 2:\n os.system(\"clear\")\n if not session:\n print 'Usuario nao logado'\n continue\n\n print 'Opcao 2 selecionada'\n print 'Digite as informacoes: '\n user = raw_input('Username: ')\n pswd = raw_input('Password: ')\n \n # cadastrar = \"INSERT INTO users (usuario, pass) VALUES('%s', '%s')\" % (user, pswd)\n cadastrar = db.fila.insert({ \"nome\": user, \"senha\": pswd})\n\t\t# cadastrar = db.fila.insert({\"nome\": user, \"senha\": pswd})\n\n \n elif option == 3:\n os.system(\"clear\")\n print 'Opcao 3 selecionada'\n print 'lista usuarios'\n user = raw_input('Usuario: ')\n # mostrar = \"SELECT * FROM users WHERE usuario LIKE '%%%s%%'\" % user;\n mostrar = db.fila.find({\"nome\": user})\n\n # cur.execute(mostrar)\n # usuario = cur.fetchone()\n\n ## checar nao funcionou\n\n if mostrar.count() != 0: \n print '==================='\n print 'Usuario: %s\\nSenha: %s' %(mostrar[0]['nome'], mostrar[0]['senha'])\n print '==================='\n\n\n # print '===================='\n # print 'Usuario: %s\\nSenha: %s' % (result[0]['usuario'], result[0]['senha'])\n # print '===================='\n\n\n\n\n elif option == 4:\n os.system(\"clear\")\n print 'Volte sempre'\n exit()" }, { "alpha_fraction": 0.6557376980781555, "alphanum_fraction": 0.6659836173057556, "avg_line_length": 12.583333015441895, "blob_id": "12aeece4aeb679f4e32011841532698840502e2e", "content_id": "48e4e071db0a30cd2183dc6cbb1ccdf0c51e64e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 488, "license_type": "no_license", "max_line_length": 47, "num_lines": 36, "path": "/HandsOn/Aula03/funcao_lambda.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# funcao_lambda.py\n# funcoes anonimas\n\nf = lambda x,y,z: x + y + z\n\nprint f(2,3,4)\n\nwords = ('pera', 'uva', 'mamao')\n\n\ndef size(words):\n\treturn [len(w) for w in words]\n\nprint size(words)\n\n\n# transformando em lambda\n\nfrutas = lambda words: [len(w) for w in words]\nfrutas(words)\n\nprint frutas(words)\n\n\n# outra forma de fazer a funcao acima\n\ndef size(words):\n\tlista = []\n\tfor w in words:\n\t\tlista.append(w)\n\treturn lista\n\nfrutas2 = lambda words: [len(w) for w in words]\n\n\nprint frutas2(words)" }, { "alpha_fraction": 0.7282850742340088, "alphanum_fraction": 0.7405345439910889, "avg_line_length": 23.243244171142578, "blob_id": "2217c276dce05f8e39034b8f6fdf78a79a892710", "content_id": "276c2d529ae661336c737c27290715b404820ca6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 898, "license_type": "no_license", "max_line_length": 67, "num_lines": 37, "path": "/HandsOn/Aula04/runssh.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "from paramiko.client import SSHClient\nimport paramiko\nimport os\n\nclient = SSHClient()\n\n\nclient.load_system_host_keys()\nclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n# client.connect(hostname=host, username=user, password=password)\n#ip da maquina fisica - para saber veja ifconfig\nhost = '192.168.202.3'\nuser = 'noturno'\npassword = '4linux'\n\n#executa no servidor conectado\nclient.connect(hostname=host, username=user, password=password)\n\nstdin, stdout, stderr = client.exec_command(\"la -la\")\nprint stdout.read()\n\n# Controle de erro\nif stderr.channel.recv_exit_status() != 0:\n\tprint stderr.channel.recv_exit_status()\n\tprint stderr.read()\nelse:\n\tprint stdout.read()\n\nstdin, stdout, stderr = client.exec_command(\"/sbin/ifconfig\")\nprint stdout.read()\n\n# executa local \nprint os.popen(\"ls -la\").read()\n\n# status da execucao do comando \n# $? --> fica o status do sucesso do comando\n\n" }, { "alpha_fraction": 0.6279069781303406, "alphanum_fraction": 0.6511628031730652, "avg_line_length": 8.666666984558105, "blob_id": "a3bc823027e96588c275a4eacf919efd34733775", "content_id": "ff1189c999da3ff0d2b9effbef5d6ac38ed117d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 23, "num_lines": 9, "path": "/HandsOn/Aula04/runmod.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#runmod.py\nfrom lib.funcs import *\n\na = 2\nb = 2\n\nprint soma(a,b)\n\nprint subtrair(a,b)" }, { "alpha_fraction": 0.6279069781303406, "alphanum_fraction": 0.6366279125213623, "avg_line_length": 16.049999237060547, "blob_id": "879b5929d87bad17e955e7378df6104c45207b6f", "content_id": "97acd55e34e7165d5ac085045d0ce3bc51d123b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 54, "num_lines": 20, "path": "/HandsOn/Aula06/runbanco.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#runbanco.py\nimport psycopg2\n\ncon = psycopg2.connect(\n\t\"host=%s dbname=%s user=%s password=%s\" % (\n 'localhost', 'projeto', 'postgres', '4linux-mori'\n )\n)\n\n# trazer uma sessao\ncur = con.cursor()\n\n# executa um acao\n\ncur.execute(\" \\\n\tINSERT INTO posts(conteudo, titulo) \\\n\tVALUES('A crise no Brasil', 'bla, bla bla')\"\n\t)\n\ncon.commit()\n\n\n\n" }, { "alpha_fraction": 0.7253169417381287, "alphanum_fraction": 0.7314636707305908, "avg_line_length": 15.47468376159668, "blob_id": "68ad2a721b21e18280b0fd8f4c822630626d937e", "content_id": "c9f1aa319d33377e91e4fb3711b8f8c53fb10b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2603, "license_type": "no_license", "max_line_length": 45, "num_lines": 158, "path": "/old-class/aula02/lacos.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#lacos.py\n\ni = 0\n\nwhile i < 10:\n\tprint i\n\ti += 1\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\ni = 0 \n\nwhile i < 10:\n\tif i == 5: \n\t\t#break\n\t\ti += 1\n\t\tcontinue\n\tprint i\n\ti += 1\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nfor value in ['pera','uva', 'banana']:\n\tprint value\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nfor value in ['pera','uva', 'banana']:\n\tif value == 'uva':\n\t\tcontinue\n\tprint value\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nfor value in 'PYTHON':\n\tprint value\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nfor value in 'PYTHON':\n\tif value == 'T':\n\t\tcontinue\n\tprint value\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nfor value in 'PYTHON':\n\tif value == 'T':\n\t\tcontinue\n\tprint value\nelse:\n\tprint 'Close a conexao'\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\nanimais.remove('gato')\nprint animais\n#retira o ultimo da lista \nanimais.pop()\nprint animais\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\nanimais.remove('gato')\nprint animais\n#retira o ultimo da lista \nanimais.pop()\nprint animais\nanimais.count('tigre')\nprint animais\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\nanimais.remove('gato')\nprint animais\n#retira o ultimo da lista \nanimais.pop()\nprint animais\nprint animais.count('tigre')\nprint animais\nprint len(animais)\n\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\nanimais.remove('gato')\nprint animais\n#retira o ultimo da lista \nanimais.pop()\nprint animais\nprint animais.count('tigre')\nprint animais\nprint len(animais)\n\nif 'tigre' in animais:\n\tprint 'encontrei o tigre'\n\nprint 'xxxxxxxxxxxxxxxxxxxxxxxxx'\n\nanimais = ['gato', 'cachorro', 'passarinho']\nanimais.append('boi')\nprint animais\nanimais.insert(1, 'tigre')\nprint animais\nanimais.remove('gato')\nprint animais\n#retira o ultimo da lista \nanimais.pop()\nprint animais\nprint animais.count('tigre')\nprint animais\nprint len(animais)\nprint animais.index('tigre')\nanimais.reverse()\nprint animais\nif 'tigre' in animais:\n\tprint 'encontrei o tigre'\n" }, { "alpha_fraction": 0.5099099278450012, "alphanum_fraction": 0.5648648738861084, "avg_line_length": 26.575000762939453, "blob_id": "4e5c87fc3e58c7082f7c78ff56fe4f10aff37655", "content_id": "ffbabe8cc3b958f2c5e706c980151cd5b33cf17c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 84, "num_lines": 40, "path": "/HandsOn/Aula04/rundatahorario.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#rundatahorario.py\n\nfrom datetime import datetime, timedelta\n#timedelta consegue guardar o periodo de um tempo\n\nprint datetime.now()\nprint '-----------------------'\nprint datetime.now().hour\nprint '-----------------------'\n# https://docs.python.org/3/library/datetime.html?highlight=datetime#module-datetime\nprint datetime.now().strftime('%H - %d - %b')\nprint '-----------------------'\nprint datetime(1990, 8, 1, 0,0,0)\nprint '-----------------------'\nprint datetime(1990, 8, 1, 0,0,0).strftime('%d/%b/%Y')\nprint '-----------------------'\n# O resultado eh o data atual mais 4 dias do timedelta\nprint datetime.now() + timedelta(4)\nprint '-----------------------'\nprint timedelta(4)\nprint '-----------------------'\nprint datetime.now() + timedelta(hours=3)\nprint '-----------------------'\nprint datetime.now() + timedelta(\n\tdays=4,\n\tseconds=1231,\n\tmilliseconds=123,\n\tminutes=21,\n\thours=4,\n\tweeks=1\n )\nprint '-----------------------'\n\ndata1 = datetime(1990, 8, 1, 0,0,0)\ndata2 = datetime(1990, 8, 1, 0,1,0)\n\nif (data1 - data2).total_seconds() > 3600:\n\tprint 'prazo expirado'\nelse:\n\tprint 'dentro do prazo'\n\n\t\n\n\n\n\n" }, { "alpha_fraction": 0.584269642829895, "alphanum_fraction": 0.6329588294029236, "avg_line_length": 12.300000190734863, "blob_id": "df26cb3c497c7bb51ff14c0db1e6b916a5423efc", "content_id": "ab1b905881cad8d2b728851b821bdb02bc82f14b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 37, "num_lines": 20, "path": "/HandsOn/Aula03/function3.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# function3.py\n\ndef subtrair(*args): \n\tsaida = ''\n\tfor a in args:\n\t\tsaida = saida + str(a)\n\tprint saida\n\n\nsubtrair(2,3,10,50)\n\n\ndef multiplicar (*args, **kwargs):\n\tprint args\n\tprint kwargs\n\t\n\t# chamar help\n\t#print help(kwargs)\n\nmultiplicar(2, 3, a=2, b=1, c=4, d=6)\n\n" }, { "alpha_fraction": 0.5639097690582275, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 14.411765098571777, "blob_id": "330a810339ef0dc247453a62dc3f62281981dd94", "content_id": "b560639a8119bcc989d74e3f46b95282e8156fda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/old-class/aula02/operadores.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#operadores\n\n\n# num1 = 5\n# num2 = 4\n\n\nnum1 = int(raw_input(\"insira o primeiro valor1: \"))\nnum2 = int(raw_input(\"insira o primeiro valor2: \"))\n\n\nprint num1 * num2\nprint ((num1 * num2) +5) \nprint num1 + num2\nprint num1 - num2\nprint num1 / num2\nprint num1 % num2\n\n\n\n\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6594203114509583, "avg_line_length": 15.757575988769531, "blob_id": "10753249d888d3035ecb0c234e7de19efbc75327", "content_id": "d736879566328c816b8bb0af9d46da150d1bebae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 62, "num_lines": 33, "path": "/HandsOn/Aula09/classe.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# classe.py\n# orientado a objeto\n\n#definicao de classe\n\n# init eh o construtor\n\nimport psycopg2\n\n\nclass Banco:\n\n\tcon = None\n\n\tcur = None\n\n\n\tdef __init__(self, host, db, user, passwd):\n\t\tself.con = psycopg2.connect(\n\t\t\t\"host=%s dbname=%s user=%s password=%s\" %\n\t\t\t(host, db, user, passwd)\n# acima sao variaveis\n\t\t)\n\t\tself.cur = self.con.cursor()\n\n\tdef find_one(self, id):\n\t\tself.cur.execute(\"SELECT * FROM posts WHERE id=%s\" % id)\n\t\t\n\t\treturn self.cur.fetchone()\n\nobjeto = Banco('localhost','projeto','postgres','4linux-mori')\n\nprint objeto.find_one(1)" }, { "alpha_fraction": 0.5777027010917664, "alphanum_fraction": 0.587837815284729, "avg_line_length": 15.914285659790039, "blob_id": "d88fa56d54bd74ae812e21a7e4ba6d613bd0edf1", "content_id": "dbc9d2022ab4c734fd17d93a80dd5eb2a6b6cabb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/HandsOn/Aula03/function2.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# function2.py\n\nanimais = ['tigre', 'boi', 'galinha']\n\ndef exibir_lista(lista):\n\t# esta importando a variavel animais\n\tglobal animais\n\tfor a in lista:\n\t\tprint a\n\n#exemplo\n# parametro opcional\n#def somar(a,b=2): se passar o valor sera subscrito\n# na declaracao resultado = somar (b=2, a=4)\n\n\ndef somar(a,b):\n\treturn a+b\n\t\n\nprint '--------------------------'\n\nexibir_lista(animais)\n\nprint '--------------------------'\n\nprint somar (2,2)\n\nprint '--------------------------'\na=int(raw_input('Valor a: '))\nb=int(raw_input('Valor b: '))\n\nresultado = somar(a, b)\nprint resultado\n# dando erro checar\n" }, { "alpha_fraction": 0.7099999785423279, "alphanum_fraction": 0.7099999785423279, "avg_line_length": 13.949999809265137, "blob_id": "b93b7830b601393b908f0bcec70dcf0fc429df35", "content_id": "4db45600bd04bfcb81fa0e7f845651353ea87abc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "no_license", "max_line_length": 43, "num_lines": 20, "path": "/HandsOn/Aula03/function.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# function.py\n# funcoes - codigos para ser reaproveitados\n\nanimais = ['tigre', 'boi', 'galinha']\n\ndef exibir_lista(lista):\n\t# esta importando a variavel animais\n\tglobal animais\n\tfor a in lista:\n\t\tprint a\n\n#exemplo\ndef printar(string):\n\t#variavel local\n\tc= 'c'\n\n\tprint string\n\n\nexibir_lista(animais)\n\n" }, { "alpha_fraction": 0.6651162505149841, "alphanum_fraction": 0.669767439365387, "avg_line_length": 42, "blob_id": "c4e872a9f38c605808abdc91263c4888bc873107", "content_id": "b5fa2bfbacf4f7c85fe0b8882153add6404a0ac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/old-class/aula02/strings1.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "host = raw_input('Insira o hostname: ')\nuser = raw_input('Insira o usuario: ')\nsenha = raw_input('Insira a senha: ')\n# python 3 so input, nao tem mais raw_input\nprint \"acessando host %s:%s %s\" % (user, host, senha)\n" }, { "alpha_fraction": 0.6463104486465454, "alphanum_fraction": 0.6768447756767273, "avg_line_length": 10.142857551574707, "blob_id": "cdce05ca29bbafe1a93bdcb4fd74a784dd16c739", "content_id": "9f62d1a9629ecb02ef1a9d83275bd6d8a0869b54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 34, "num_lines": 35, "path": "/old-class/aula02/operadores2.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# operadores2\n\nnumero = 5\n\n# pode ser usado para contador\nnumero = numero + 5\n# deu pau o meu teste numero1 += 5\n\nprint numero\n\n# print numero1\n\n\n# operadores relacionais\nprint 'Operadores relacionais'\n\nnumero = 5\nnumero2 = 10\n\nnumero = numero + 5\nnumero += 5\n\n\n# operadores logico s\nprint \"operadores logicos\"\n\na = 'a'\nb = 'b'\n\nif a and not b:\n\n\tprint 'verdadeiro'\n\nelse: \n\tprint 'falso'\n\n\n\n" }, { "alpha_fraction": 0.5863874554634094, "alphanum_fraction": 0.5968586206436157, "avg_line_length": 10.9375, "blob_id": "db463b401ff3dad00b6d291bb7a691ed0efece0c", "content_id": "2138bc0062f784027739b53b3887f7831f1f2805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 40, "num_lines": 48, "path": "/HandsOn/Aula03/tryexcept.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#tryexcept.py\n\n# def func():\n#\tpass\n\ntry:\n\tprint 'primeira linha'\n\tfunc()\n\ta = 3 + 3\n\t\nexcept Exception as e:\n\tprint e \n\tprint 'algo de errado aconteceu'\n\n\n\nprint '-------------------------'\n\ndef func(valor):\n\tif valor:\n\t\traise Exception('Deu ruim!!')\n\ntry:\n\tprint 'primeira linha'\n\tfunc(True)\n\tprint 3 + 3\n\t\nexcept Exception as e:\n\tprint e \n\n\n\nprint '-----Finally--------------------'\n\ndef func(valor):\n\tif valor:\n\t\traise Exception('Deu ruim!!')\n\ntry:\n\tprint 'primeira linha'\n\tfunc(True)\n\tprint 3 + 3\n\t\nexcept Exception as e:\n\tprint e \n\nfinally:\n\tprint 'sempre executa'\n" }, { "alpha_fraction": 0.4972350299358368, "alphanum_fraction": 0.504147469997406, "avg_line_length": 24.845237731933594, "blob_id": "a2613cdb1ba7028e2f1f67d261bcc0d750d6cb5a", "content_id": "e9c6a39694f71e1d7fd55ce77784ffba1e4f1dd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2170, "license_type": "no_license", "max_line_length": 96, "num_lines": 84, "path": "/HandsOn/Aula06/step2-rev.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#step2\nimport psycopg2\nimport os\n\nflag = True\n\nhost = 'localhost'\ndbname = 'projeto'\nuser = 'postgres'\npassword = '4linux-mori'\n\ncon = psycopg2.connect(\"host=%s dbname=%s user=%s password=%s\" % (host, dbname, user, password))\ncur = con.cursor()\n\nsession = False\n\nwhile flag:\n banner = '''Menu:\n1) Logar\n2) Cadastrar usuario\n3) Lista usuario\n4) Sair\nSelecione a opcao: '''\n\n option = int(raw_input(banner))\n\n \n if option == 1:\n os.system(\"clear\")\n user = raw_input('Username: ')\n pswd = raw_input('Password: ')\n\n query = \"SELECT * FROM users WHERE usuario='%s' AND pass='%s'\" % (user, pswd)\n cur.execute(query)\n\n usuario = cur.fetchone()\n\n if usuario:\n session=True\n print 'Login com sucesso'\n else:\n print 'Username ou password invalidos'\n elif option == 2:\n os.system(\"clear\")\n if not session:\n print 'Usuario nao logado'\n continue\n\n print 'Opcao 2 selecionada'\n print 'Digite as informacoes: '\n user = raw_input('Username: ')\n pswd = raw_input('Password: ')\n \n cadastrar = \"INSERT INTO users (usuario, pass) VALUES('%s', '%s')\" % (user, pswd)\n \n try:\n\n cur.execute(cadastrar)\n if cur.rowcount:\n con.commit()\n print '-----------------------------'\n print 'Registro inserido com sucesso!'\n print '-----------------------------'\n except Exception as e:\n cur.roolback()\n print 'falha ao cadastrar' \n \n elif option == 3:\n os.system(\"clear\")\n print 'Opcao 3 selecionada'\n print 'lista usuarios'\n user = raw_input('Usuario: ')\n mostrar = \"SELECT * FROM users WHERE usuario LIKE '%%%s%%'\" % user;\n cur.execute(mostrar)\n usuario = cur.fetchone()\n if usuario: \n print '==================='\n print 'Usuario: %s\\nSenha: %s' %(usuario[1], usuario[2])\n print '==================='\n\n elif option == 4:\n os.system(\"clear\")\n print 'Volte sempre'\n exit()" }, { "alpha_fraction": 0.33898305892944336, "alphanum_fraction": 0.35593220591545105, "avg_line_length": 17.44444465637207, "blob_id": "5b8c5efd6336ae678abd223f2bc1eba3c992b90c", "content_id": "16c00d1d101867d512a1a95daee9df163bf3b2f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/old-class/aula02/strings.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "string = \"Python\"\nprint \"-----------------------\"\nprint string[3]\n\nprint \"-----------------------\"\nprint string[:3]\n\nprint \"-----------------------\"\nprint string[3:]\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5233119130134583, "alphanum_fraction": 0.5265273451805115, "avg_line_length": 27.930233001708984, "blob_id": "035616ed51f78617341b744fd0b70c52a9dccb4f", "content_id": "1f11adb8e52c9ae104e8b63032e40b020dacdb9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1244, "license_type": "no_license", "max_line_length": 93, "num_lines": 43, "path": "/HandsOn/Aula09/exercicio.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "\n# aula9 do teacher para verificar o que deu errado\n\nimport psycopg2\n\nclass Conexao:\n @staticmethod\n def conectar(host, dbname, user, passwd):\n con = psycopg2.connect(\n \"host=%s dbname=%s user=%s password=%s\" %(\n host, dbname, user, passwd)\n )\n cur = con.cursor()\n return con, cur\n\nclass Banco:\n con = None\n cur = None\n\n def __init__(self, host, dbname, user, passwd):\n self.con, self.cur = Conexao.conectar(host, dbname, user, passwd)\n\n def find_one(self, id):\n self.cur.execute(\"SELECT * FROM posts WHERE id=%s\" % id)\n return self.cur.fetchone()\n\nclass Cadastrar:\n def ingressar(id, titulo):\n self.cur.execute (\"INSERT INTO posts (id, titulo) VALUES('%s', '%s')\" % (id, titulo))\n try:\n \n if self.cur.rowcount:\n con.commit()\n print '-----------------------------'\n print 'Registro inserido com sucesso!'\n print '-----------------------------'\n except Exception as e:\n cur.roolback()\n print 'falha ao cadastrar' \n \n\n\nobjeto = Banco('localhost', 'projeto', 'postgres', '4linux-mori')\nCadastrar.ingressar('xico','xica')" }, { "alpha_fraction": 0.5997506380081177, "alphanum_fraction": 0.6097257137298584, "avg_line_length": 11.919354438781738, "blob_id": "a1e5d5399a198c1304dfd28f1388d49e1aaed522", "content_id": "0aa4b359e01bae030d7fe2ac09013406514d50f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 802, "license_type": "no_license", "max_line_length": 67, "num_lines": 62, "path": "/HandsOn/Aula06/mysql.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# mysql\nimport MySQLdb\ncon = MySQLdb.connect(\n\t\thost='127.0.0.1', user='admin', passwd='4linux-mori', db='projeto'\n\t)\n\nprint con\n\n# abri sessao\ncur = con.cursor()\n\n#insert\n\ntry:\n\tcur.execute(\n\t\t\t\"INSERT INTO posts(titulo, conteudo) \\\n\t\t\t VALUES('Meu titulo', 'Meu conteudo')\"\n\n\t\t)\n\tcon.commit()\n\nexcept Exception as e:\n\tcon.rollback()\n\n\n#update\n\ntry:\n\tcur.execute(\n\t\t\t\"UPDATE posts SET titulo='Novo titulo' \\\n\t\t\tWHERE ID=2\"\n\t\t)\n\tcon.commit()\n\nexcept Exception as e:\n\tcon.roolback()\n\n\n#SELECT ONE\n\ncur.execute(\n\t\t'SELECT * FROM posts WHERE ID=2'\n\t)\n\nprint cur.fetchone()\nprint '-----------------------------'\n\ncur.execute(\n\t\t'SELECT * FROM posts'\n\t)\n\n\n\nprint 'Ultimo comando executado '\nprint cur._last_executed\nprint '-----------------------------'\n\nfor row in cur.fetchall():\n\tprint row\n\n\ncon.close()\n\n" }, { "alpha_fraction": 0.6725146174430847, "alphanum_fraction": 0.6725146174430847, "avg_line_length": 11.142857551574707, "blob_id": "c0b5982ac49920014347d93a9d598391036cb879", "content_id": "7989dfadc5c86bf2a08eec0959d1136a2622a232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 31, "num_lines": 14, "path": "/HandsOn/Aula04/lib/funcs.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# funcs.py\n# biblioteca arquivo de funcoes\n\ndef soma(a,b):\n\treturn a+b\n\t\ndef subtrair(a,b):\n\treturn a-b\n\ndef multiplicar(a,b):\n\treturn a*b\n\ndef dividir(a,b):\n\treturn a/b\n\t" }, { "alpha_fraction": 0.586410641670227, "alphanum_fraction": 0.5923190712928772, "avg_line_length": 24.11111068725586, "blob_id": "104b6976586e21e47c89fd39cc8decf28af1f3cf", "content_id": "0fa1786df53e413eb68779f8267720da0ef2716c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 73, "num_lines": 27, "path": "/HandsOn/Aula09/metodoestatico.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "import psycopg2\n\nclass Conexao:\n @staticmethod\n def conectar(host, dbname, user, passwd):\n con = psycopg2.connect(\n \"host=%s dbname=%s user=%s password=%s\" %(\n host, dbname, user, passwd)\n )\n cur = con.cursor()\n return con, cur\n\nclass Banco:\n con = None\n cur = None\n\n def __init__(self, host, dbname, user, passwd):\n self.con, self.cur = Conexao.conectar(host, dbname, user, passwd)\n\n def find_one(self, id):\n self.cur.execute(\"SELECT * FROM posts WHERE id=%s\" % id)\n return self.cur.fetchone()\n\n\n\nobjeto = Banco('localhost', 'projeto', 'postgres', '4linux-mori')\nprint objeto.find_one(1)" }, { "alpha_fraction": 0.5233050584793091, "alphanum_fraction": 0.5508474707603455, "avg_line_length": 10.974358558654785, "blob_id": "a2ebe32027695c1e1b3af0cfc1e24e7dff5d83b4", "content_id": "78988344b57c287c59152589605215fd34ba625d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 33, "num_lines": 39, "path": "/HandsOn/Aula08/mongodb.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# mongodb.py\nfrom pymongo import MongoClient\n\n\nclient = MongoClient('127.0.0.1')\ndb = client['devops']\n\n#insert\n\n db.fila.insert({\n \t\t\"_id\": 2, \n \t\t\"servico\": \"intranet\",\n \t\t\"status\": 0\n \t})\n\n\ndb.fila.insert({\n \t\t\"_id\": 3, \n \t\t\"servico\": \"dns\",\n \t\t\"status\": 0\n \t})\n# control + / para comentar tudo\n\n\n#update\n\n\ndb.fila.update(\n\t{\"_id\": 1, \"servico\": \"dns\"},\n\t{\"$set\": {\"status\": 1}}\n\n\t)\n\n# remove\ndb.fila.remove({\"_id\": 2})\n\n# find\nfor d in db.fila.find({}):\n\tprint d\n\n\n\n\n\n" }, { "alpha_fraction": 0.6534653306007385, "alphanum_fraction": 0.6633663177490234, "avg_line_length": 24.5, "blob_id": "aa9508143c68e186bb62a6fd6dd5070750df91aa", "content_id": "bee62dade54577799d27e9f620c4341c391cab32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/HandsOn/exercicios-gitlab/task1.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#task1\nuser = raw_input('Username: ')\npswd = raw_input('Password: ')\nprint 'Seja bem-vindo, %s' %user" }, { "alpha_fraction": 0.6806083917617798, "alphanum_fraction": 0.6844106316566467, "avg_line_length": 20.83333396911621, "blob_id": "e0155846c3510e1e82268acc8a04369ddc2f4701", "content_id": "09016cc66cd7e718d18817a7675f997e42d55f87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 40, "num_lines": 12, "path": "/HandsOn/exercicios-gitlab/task2.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "#task2\nuser = raw_input('Username: ')\npswd = raw_input('Password: ')\n\nuserval = 'arthur.dent'\npswdval = 'mochileiro'\n\nif user == userval and pswd == pswdval:\n\tprint 'usuario autenticado com sucesso'\n\tprint 'Seja bem-vindo, %s' %user\nelse:\n\tprint 'acesso negado'\n\n" }, { "alpha_fraction": 0.6272727251052856, "alphanum_fraction": 0.6381818056106567, "avg_line_length": 21.70833396911621, "blob_id": "2e7f049496ca1a57cf3d2eb0310fe1af5ccedba7", "content_id": "022eab7047fccaea3e6477d006551700f0772b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/old-class/aula02/exec1.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# exec1.py\n\nalcool = raw_input('Esta alcoolizada?(S/N): ').upper() \nidade = raw_input('Digite a sua idade: ')\nif idade is None: \n\tidade = 5\n\tprint 'idade'\nhabilitacao = raw_input('Tem Habilitacao?(S/N): ').upper()\n\nif alcool == 'S':\n\tprint 'Proibida de dirigir'\nelse:\n\tif int(idade) >= 18:\n\t\tprint 'OK, pode dirigir'\n\telif habilitacao == 'S':\n\t\tprint 'OK, pode dirigir'\n\telse: \n\t\tprint 'nao pode dirigir'\n\n# forma mais enchuta\n#if idade >= 18 and habilitacao == 'S' and alcool == 'N':\n#\t print 'Pode dirigir'\n#\telse:\n#\t\tprint 'Nao pode dirigir'\n\n\n\n\n\n" }, { "alpha_fraction": 0.6696696877479553, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 13.5, "blob_id": "c54fb5b1e680b236e3dfb9deb2d00dc720d7857f", "content_id": "6b75aba8547e11e96a91b40eae33afd2a71d3c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "no_license", "max_line_length": 64, "num_lines": 46, "path": "/HandsOn/Aula09/heranca.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "# classe.py\n# orientado a objeto\n# heranca\n\n#definicao de classe\n\n# init eh o construtor\n\nimport psycopg2\n\n\n\nclass Conexao:\n\n\tcon = None\n\tcur = None\n\n\n\tdef conectar(self, lista):\n\t\tself.con = psycopg2.connect(\n\t\t\t\"host=%s dbname=%s user=%s password=%s\" %\n\t\t\tlista\n\t\t)\n\t\tself.cur = self.con.cursor()\n\n\n# permite heranca multipla class Banco(Conexao, Exception)\n\nclass Banco(Conexao):\n\n\tdef __init__(self, lista):\n\t\tself.conectar(lista)\n\t\n\tdef find_one(self, id):\n\t\tself.cur.execute(\"SELECT * FROM posts WHERE id=%s\" % id)\n\t\t\n\t\treturn self.cur.fetchone()\n\n\n\nobjeto = Banco(('localhost','projeto','postgres','4linux-mori'))\n\n\nprint objeto.cur\n\nprint objeto.find_one(1)" }, { "alpha_fraction": 0.7021968960762024, "alphanum_fraction": 0.7095199227333069, "avg_line_length": 24.102041244506836, "blob_id": "f96bcba0dd068082814cab8831050b8ea70f5c62", "content_id": "7ddd8bc77ee359202ddd8369384e784a8ee5d0c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1229, "license_type": "no_license", "max_line_length": 66, "num_lines": 49, "path": "/HandsOn/Aula07/funcionarios.py", "repo_name": "marcoslmori/python-fundamentals", "src_encoding": "UTF-8", "text": "from sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship\n\n\nengine = create_engine('sqlite:///banco.db')\nBase = declarative_base()\n\n\nclass Funcionario(Base):\n __tablename__='funcionario'\n id = Column(Integer, primary_key=True)\n nome = Column(String)\n dependentes = relationship(\"Dependentes\")\n\n\n\nclass Dependentes(Base):\n __tablename__= 'dependentes'\n id = Column(Integer, primary_key=True)\n nome = Column(String)\n \n funcionario_id = Column(Integer, ForeignKey('funcionario.id'))\n\n\nif __name__=='__main__':\n Base.metadata.create_all(engine)\n Session = sessionmaker()\n Session.configure(bind=engine)\n session=Session()\n\n\ntry:\n funcionario = Funcionario(id=1, nome='Joaquim da Silva')\n session.add(funcionario)\n\n dependente1 = Dependentes(id=1, nome= \"joao\")\n dependente2 = Dependentes(id=2, nome= \"maria\")\n\n funcionario.dependentes.append(dependente1)\n funcionario.dependentes.append(dependente2)\n\n session.add(dependente1)\n session.add(dependente2)\n session.commit()\nexcept Exception as e:\n print e \n session.rollback()" } ]
30
Dorothylyly/proxyPool
https://github.com/Dorothylyly/proxyPool
d478bac9fa49e3a1d43d24b1e2c4114820196b9e
f24d6c51cc6538f30ee17f625adc8d8680635c75
219a571241b6597159c243d542b41cc92358ecb5
refs/heads/master
2020-03-25T23:32:18.975290
2018-08-10T11:36:27
2018-08-10T11:36:27
144,279,627
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6383763551712036, "alphanum_fraction": 0.6383763551712036, "avg_line_length": 23.636363983154297, "blob_id": "7570ed557bc5be32d366b8e9b8d9878ff4e83efc", "content_id": "dddc6e27ba30767fe3ec8773ba22e6365d73dae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 72, "num_lines": 11, "path": "/loggingCustom.py", "repo_name": "Dorothylyly/proxyPool", "src_encoding": "UTF-8", "text": "import logging\n\n\nLOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\nDATE_FORMAT = \"%m/%d/%Y %H:%M:%S %p\"\n\n\ndef log():\n logging.basicConfig(filename='RedisClient.log', level=logging.DEBUG,\n format=LOG_FORMAT, datefmt=DATE_FORMAT)\n return logging\n" }, { "alpha_fraction": 0.5490699410438538, "alphanum_fraction": 0.5577293038368225, "avg_line_length": 25.615385055541992, "blob_id": "cefb6bcf78b7f6056daad3134d0d5cc17bfc02d2", "content_id": "dae13dc4765f7a2b5f61c34ab455c2e49b116d07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3664, "license_type": "no_license", "max_line_length": 116, "num_lines": 117, "path": "/RedisClient.py", "repo_name": "Dorothylyly/proxyPool", "src_encoding": "UTF-8", "text": "\nimport redis\n# 生成随机数\nfrom random import choice\n\"\"\"\n 操作缓存数据库的有序集合,实现分数的设置,代理的获取\n 检测代理\n\"\"\"\n# 最大分数 100分为高可用\nMAX_SCORE = 100\n# 最低分数 一旦低于0分 立即剔除\nMIN_SCORE = 0\n# 刚爬取到的代理的初始化分数\nINITIAL_SCORE = 10\n#\n# #LOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\n# DATE_FORMAT = \"%m/%d/%Y %H:%M:%S %p\"\n\n\nREDIS_HOST = \"localhost\"\nREDIS_PORT = 6379\nREDIS_PASSWORD = \"123456\"\nREDIS_KEY = \"proxies\"\nfrom loggingCustom import log as logging\n\nclass RedisClient(object):\n\n # logging.basicConfig(filename='RedisClient.#log', level=logging.DEBUG, format=#LOG_FORMAT, datefmt=DATE_FORMAT)\n\n def __init__(self, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD):\n \"\"\"\n 初始化\n :param host: 地址\n :param port: 端口\n :param password: 密码\n \"\"\"\n self.db = redis.StrictRedis(host=host, port=port, password=password, decode_responses=True)\n\n def add(self, proxy, score=INITIAL_SCORE):\n \"\"\"\n 添加代理,设置分数为最高\n :param proxy:\n :param score:\n :return:\n \"\"\"\n\n # 如果redis里面没有 这个proxy 就将代理添加进redis\n if not self.db.zscore(REDIS_KEY, proxy):\n return self.db.zadd(REDIS_KEY, score, proxy)\n\n def random(self):\n \"\"\"\n 随机获取有效代理,首先尝试获取最高代理分数,如果最高分数不存在,则按排名获取,否则异常\n :return: 随机代理\n \"\"\"\n # result 返回score等于100的所有代理列表 大于等于MAX_SCORE小于等于MAX_SCORE\n result = self.db.zrangebyscore(REDIS_KEY, MAX_SCORE, MAX_SCORE)\n if len(result):\n # 在result列表中 随机选择一个,实现负载均衡\n return choice(result)\n # 如果不存在100分的代理\n else:\n result = self.db.zrevrange(REDIS_KEY, 0, 100)\n # 当result不为空时\n if len(result):\n return choice(result)\n else:\n logging().warning(\"raise PoolEmptyError\")\n raise TimeoutError\n\n def decrease(self, proxy):\n \"\"\"\n 代理值减一分,分数小于最小值,则代理删除\n :param proxy: 代理\n :return: 修改后的代理的分数\n \"\"\"\n score = self.db.zscore(REDIS_KEY, proxy)\n if score and score > MIN_SCORE:\n logging().info(\"proxy{}score{} - 1\".format(proxy, score))\n print(\"proxy\", proxy, \"score\", score, \"-1\")\n return self.db.zincrby(REDIS_KEY, proxy, -1)\n else:\n print(\"proxy\", proxy, \"score too low,out\")\n return self.db.zrem(REDIS_KEY, proxy)\n\n def exits(self,proxy):\n \"\"\"\n 判断代理是否存在\n :param proxy: 代理\n :return: 是否存在\n \"\"\"\n return not self.db.zscore(REDIS_KEY, proxy) is None\n\n def max(self, proxy):\n \"\"\"\n 将代理设置为 MAX_SCORE\n :param proxy: 代理\n :return:\n \"\"\"\n\n logging().info(\"proxy{}ok,set score {}\".format(proxy, MAX_SCORE))\n\n print(\"proxy\", proxy, \"ok,set score\", MAX_SCORE)\n return self.db.zadd(REDIS_KEY, MAX_SCORE, proxy)\n\n def count(self):\n \"\"\"\n 获取代理数量\n :return: 代理数量\n \"\"\"\n return self.db.zcard(REDIS_KEY)\n\n def all(self):\n \"\"\"\n 获取全部代理列表\n :return:\n \"\"\"\n return self.db.zrangebyscore(REDIS_KEY, MIN_SCORE, MAX_SCORE)\n\n\n\n" }, { "alpha_fraction": 0.5498633980751038, "alphanum_fraction": 0.5525956153869629, "avg_line_length": 20.80596923828125, "blob_id": "8112572c89a72747c8c23d5a0bee2364517da4eb", "content_id": "3c8d30a57a94ef6f26238acbe782748de944e523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1610, "license_type": "no_license", "max_line_length": 65, "num_lines": 67, "path": "/together.py", "repo_name": "Dorothylyly/proxyPool", "src_encoding": "UTF-8", "text": "from loggingCustom import log as logging\nfrom tester import Tester\nfrom Getter import Getter\nimport time\n\n# 多线程模块\nfrom multiprocessing import Process\nfrom flaskWeb import app\n\nAPI_ENABLE = True\nTESTER_CYCLE = 20\nGETTER_CYCLE = 20\nTESTER_ENABLED = True\nGETTER_ENABLE = True\n\n\n\n\n\nclass Scheduler():\n\n def schedule_tester(self, cycle=TESTER_CYCLE):\n \"\"\"\n 定时检测代理\n :param cycle:\n :return:\n \"\"\"\n tester = Tester()\n while True:\n logging().info(\"测试器开始运行\")\n print(\"测试器开始运行\")\n tester.run()\n time.sleep(cycle)\n\n def schedule_getter(self, cycle=GETTER_CYCLE):\n getter = Getter()\n while True:\n logging().info(\"开始抓取代理\")\n print(\"开始抓取代理\")\n # 抓取器开始运行\n getter.run()\n time.sleep(cycle)\n\n def schedule_api(self):\n \"\"\"\n 开启api\n :return:\n \"\"\"\n app.run()\n\n def run(self):\n logging().info(\"代理池开始运行\")\n print(\"代理池开始运行\")\n # 以主线程为父线程 创建子线程\n if TESTER_ENABLED:\n tester_process = Process(target=self.schedule_tester)\n tester_process.start()\n if GETTER_ENABLE:\n getter_process = Process(target=self.schedule_getter)\n getter_process.start()\n if API_ENABLE:\n api_process = Process(target=self.schedule_api)\n api_process.start()\n\n\nif __name__==\"__main__\":\n Scheduler().run()\n\n\n\n" }, { "alpha_fraction": 0.5076788067817688, "alphanum_fraction": 0.5168933868408203, "avg_line_length": 30.54166603088379, "blob_id": "08ea01c18ce762330b73793b530e7cde92599348", "content_id": "14026092a27e426eac7bdaf5a428a769b9bda8b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2593, "license_type": "no_license", "max_line_length": 100, "num_lines": 72, "path": "/tester.py", "repo_name": "Dorothylyly/proxyPool", "src_encoding": "UTF-8", "text": "\nfrom RedisClient import RedisClient\nimport aiohttp\nimport asyncio\nimport time\n# 定义合法的状态码\nVALID_STATUS_CODE = [200]\n\nTEST_URL = \"http://desk.zol.com.cn/fengjing/\"\n# 定义一次最多验证多少个代理IP\nBATCH_TEST_SIZE = 100\n\n# aiohttp 其实表示协程\n\n\nclass Tester(object):\n def __init__(self):\n self.redis = RedisClient()\n\n # 异步的方法\n async def test_single_proxy(self, proxy):\n \"\"\"\n 方法用于检测一个代理是否合法\n :param proxy: 需要检测的代理\n :return:\n \"\"\"\n\n # 用来设置一次最大连接数量 参数用来防止ssl报错\n conn = aiohttp.TCPConnector(verify_ssl=False)\n # 用来创建一个Session连接\n async with aiohttp.ClientSession(connector=conn) as session:\n try:\n # 检测proxy是否为bytes类型\n if isinstance(proxy,bytes):\n # 如果是的话 用utf-8进行proxy编码\n proxy = proxy.decode('utf-8')\n real_proxy=\"http://\"+proxy\n print(\"testing...\", proxy)\n # 发起get请求\n async with session.get(TEST_URL, proxy=real_proxy, timeout=15) as response:\n # 如果响应状态码是200\n if response.status in VALID_STATUS_CODE:\n # 将proxy的分数设置为 100\n self.redis.max(proxy)\n print(\"proxy ok\", proxy)\n else:\n # 将代理分数减一\n self.redis.decrease(proxy)\n print(\"return code is illegal\", proxy)\n except (aiohttp.ClientError, aiohttp.ClientConnectorError, TimeoutError,AttributeError):\n self.redis.decrease(proxy)\n print(\"proxy request fail\", proxy)\n\n def run(self):\n \"\"\"\n 测试主函数\n :return:\n \"\"\"\n print(\"测试器开始运行\")\n try:\n proxies = self.redis.all()\n # 创建消息循环队列\n loop = asyncio.get_event_loop()\n # 进行批量测试\n for i in range(0, len(proxies), BATCH_TEST_SIZE):\n # 一次测试 100 个代理\n test_proxies = proxies[i:i+BATCH_TEST_SIZE]\n tasks = [self.test_single_proxy(proxy) for proxy in test_proxies]\n loop.run_until_complete(asyncio.wait(tasks))\n time.sleep(5)\n except Exception as e:\n\n print(\"error\", e.args)\n\n\n\n\n\n\n\n" } ]
4
molguin92/MiniSynCPP
https://github.com/molguin92/MiniSynCPP
b6c3f44d510b2194abda3bfdb00f6817a2ecb1ca
85e3f07fd90410866a934c5116fb076c2f5bb841
7ba824f75da519dd571e872b700f083a512ed335
refs/heads/master
2020-05-03T04:54:40.644591
2019-05-29T12:40:54
2019-05-29T12:40:54
178,435,154
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6693121790885925, "avg_line_length": 33.3636360168457, "blob_id": "0dad2e1c80e22b0311a6421407fb0b9491a98f37", "content_id": "cf778fa39bf186a7f1da41c94aba14ab90242681", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 378, "license_type": "permissive", "max_line_length": 92, "num_lines": 11, "path": "/install_raspi_xcompiler.sh", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nwget \"https://sourceforge.net/projects/raspberry-pi-cross-compilers/files/latest/download\" \\\n--verbose -O /tmp/gcc-pi.tar.gz;\n\nXGCC_EXTRACTED=\"$(tar -xzvf /tmp/gcc-pi.tar.gz -C /opt)\";\n\nXGCC_ROOT=\"$(head -n1 <<< ${XGCC_EXTRACTED})\";\nXGCC_PATH=\"/opt/${XGCC_ROOT%/}\";\necho \"export RASPI_GCC_PATH=${XGCC_PATH}\" > /opt/raspi_gcc.env;\nrm -rf /tmp/gcc-pi.tar.gz;\n" }, { "alpha_fraction": 0.6847297549247742, "alphanum_fraction": 0.6957065463066101, "avg_line_length": 36.87894821166992, "blob_id": "2dd3b28a73cb237fd7c00713e9229aa794853aa6", "content_id": "8031d79f3b7f51953b712ab74db226da6b75aa38", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 7197, "license_type": "permissive", "max_line_length": 111, "num_lines": 190, "path": "/CMakeLists.txt", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.11)\nproject(LibMiniSynCPP CXX)\nset(CMAKE_CXX_STANDARD 11)\ninclude(FetchContent REQUIRED)\n\n# show fetchcontent progress\nset(FETCHCONTENT_QUIET OFF CACHE BOOL \"Turn off FetchContent verbose output.\" FORCE)\n\n# demo requires loguru\nif (LIBMINISYNCPP_BUILD_DEMO)\n set(LIBMINISYNCPP_ENABLE_LOGURU TRUE)\nendif ()\n\nif (UNIX)\n # statically link everything on Linux\n # on OS X we only statically link libminisyncpp and libprotobuf\n set(CMAKE_FIND_LIBRARY_SUFFIXES \".a\")\n set(CMAKE_EXE_LINKER_FLAGS \"-static-libgcc -static-libstdc++\")\nendif ()\n\n# directories\ninclude_directories(include ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/include)\nlink_directories(lib lib/static)\n\n# dinamically fetch Loguru if required\nif (LIBMINISYNCPP_ENABLE_LOGURU)\n set(LOGURU_VERSION \"2.0.0\")\n set(LOGURU_URL \"https://github.com/emilk/loguru\")\n\n FetchContent_Declare(\n loguru\n # download\n GIT_REPOSITORY \"${LOGURU_URL}.git\"\n GIT_TAG \"v${LOGURU_VERSION}\"\n # ---\n )\n FetchContent_GetProperties(loguru)\n if (NOT loguru_POPULATED)\n message(STATUS \"Populating Loguru sources...\")\n FetchContent_Populate(loguru)\n include_directories(${loguru_SOURCE_DIR})\n set(LOGURU_SRC ${loguru_SOURCE_DIR}/loguru.hpp ${loguru_SOURCE_DIR}/loguru.cpp)\n message(STATUS \"Populating Loguru sources: done\")\n endif ()\nendif ()\n\n### Set up reqs for Python bindings\nif (LIBMINISYNCPP_WITH_PYTHON)\n message(STATUS \"Configuring requirements for Python bindings...\")\n\n set(PYBIND11_VERSION \"2.2.4\")\n set(PYBIND11_URL \"https://github.com/pybind/pybind11\")\n set(PYBIND11_CPP_STANDARD -std=c++11)\n set(PYBIND11_PYTHON_VERSION 3.6)\n\n FIND_PACKAGE(PythonLibs ${PYBIND11_PYTHON_VERSION} REQUIRED)\n\n FetchContent_Declare(\n pybind11\n # download\n GIT_REPOSITORY \"${PYBIND11_URL}.git\"\n GIT_TAG \"v${PYBIND11_VERSION}\"\n # ---\n )\n FetchContent_GetProperties(pybind11)\n if (NOT pybind11_POPULATED)\n message(STATUS \"Populating PyBind11 sources...\")\n FetchContent_Populate(pybind11)\n include_directories(${PYTHON_INCLUDE_DIRS} ${pybind11_SOURCE_DIR}/include)\n add_subdirectory(${pybind11_SOURCE_DIR})\n message(STATUS \"Populating PyBind11 sources: done\")\n endif ()\n message(STATUS \"Configuring requirements for Python bindings: done\")\nendif ()\n\n### LIBRARY SETUP\n# library config\nset(LIBMINISYNCPP_BUILD_VERSION \"1.0.1\")\nset(LIBMINISYNCPP_ABI_VERSION \"1\")\nconfigure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/libminisyncpp/lib_config.h.in\n ${CMAKE_CURRENT_BINARY_DIR}/include/lib_config.h)\n\n# copy the header to the binary directory\nconfigure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/libminisyncpp/minisync_api.h\n ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h\n COPYONLY)\n# export a global variables for easy use\nset(LIBMINISYNCPP_HDR ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h CACHE INTERNAL \"libminisyncpp header\")\nset(LIBMINISYNCPP_INCLUDE ${CMAKE_CURRENT_BINARY_DIR}/include/ CACHE INTERNAL \"libminisyncpp include dir\")\n\n## add library for just the algorithm\nlist(APPEND LIB_SRC\n ${CMAKE_CURRENT_BINARY_DIR}/include/lib_config.h\n ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h\n src/libminisyncpp/constraints.h src/libminisyncpp/constraints.cpp\n src/libminisyncpp/minisync.h src/libminisyncpp/minisync.cpp\n src/libminisyncpp/minisync_api.h src/libminisyncpp/minisync_api.cpp)\n\nif (LIBMINISYNCPP_ENABLE_LOGURU)\n list(APPEND LIB_SRC ${LOGURU_SRC})\nendif ()\n\nset(LIB_PROPERTIES\n LINK_SEARCH_START_STATIC 1\n LINK_SEARCH_END_STATIC 1\n VERSION ${LIBMINISYNCPP_BUILD_VERSION}\n SOVERSION ${LIBMINISYNCPP_ABI_VERSION}\n ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib/static\"\n LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib\"\n RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/bin\"\n OUTPUT_NAME minisyncpp)\n\nadd_library(libminisyncpp_static STATIC ${LIB_SRC})\nadd_library(libminisyncpp_shared SHARED ${LIB_SRC})\n\nif (LIBMINISYNCPP_ENABLE_LOGURU)\n find_package(Threads REQUIRED)\n set(CMAKE_THREAD_PREFER_PTHREAD TRUE)\n set(THREADS_PREFER_PTHREAD_FLAG TRUE)\n target_link_libraries(libminisyncpp_static dl ${CMAKE_THREAD_LIBS_INIT})\n target_link_libraries(libminisyncpp_shared dl ${CMAKE_THREAD_LIBS_INIT})\n target_compile_definitions(libminisyncpp_static PUBLIC -DLIBMINISYNCPP_LOGURU_ENABLE)\n target_compile_definitions(libminisyncpp_shared PUBLIC -DLIBMINISYNCPP_LOGURU_ENABLE)\nendif ()\n\nset_target_properties(libminisyncpp_static PROPERTIES ${LIB_PROPERTIES})\nset_target_properties(libminisyncpp_shared PROPERTIES ${LIB_PROPERTIES})\n\n### build Python bindings\nif (LIBMINISYNCPP_WITH_PYTHON)\n pybind11_add_module(pyminisyncpp\n MODULE\n src/python_bindings/pyminisyncpp_gen.cpp\n ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h)\n set_target_properties(pyminisyncpp PROPERTIES\n # LINK_SEARCH_START_STATIC 1\n # LINK_SEARCH_END_STATIC 1\n VERSION ${LIBMINISYNCPP_BUILD_VERSION}\n SOVERSION ${LIBMINISYNCPP_ABI_VERSION}\n ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/python\"\n LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/python\"\n RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/python\")\n target_link_libraries(pyminisyncpp PRIVATE libminisyncpp_shared)\nendif ()\n\n### Library tests setup\nif (LIBMINISYNCPP_BUILD_TESTS)\n message(STATUS \"Configuring tests...\")\n\n set(CATCH2_VERSION \"2.8.0\")\n set(CATCH2_URL \"https://github.com/catchorg/Catch2\")\n\n FetchContent_Declare(\n catch2\n # download\n GIT_REPOSITORY \"${CATCH2_URL}.git\"\n GIT_TAG \"v${CATCH2_VERSION}\"\n # ---\n )\n FetchContent_GetProperties(catch2)\n if (NOT catch2_POPULATED)\n message(STATUS \"Populating Catch2 sources...\")\n FetchContent_Populate(catch2)\n add_subdirectory(${catch2_SOURCE_DIR} ${catch2_BINARY_DIR})\n message(STATUS \"Populating Catch2 sources: done\")\n endif ()\n\n add_executable(libminisyncpp_tests\n ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h\n ${CMAKE_CURRENT_SOURCE_DIR}/src/tests/tests.cpp\n ${CMAKE_CURRENT_SOURCE_DIR}/src/tests/tests_main.cpp)\n\n add_dependencies(libminisyncpp_tests libminisyncpp_static Catch2::Catch2)\n target_link_libraries(libminisyncpp_tests libminisyncpp_static dl ${CMAKE_THREAD_LIBS_INIT} Catch2::Catch2)\n\n set_target_properties(libminisyncpp_tests\n PROPERTIES\n LINK_SEARCH_START_STATIC 1\n LINK_SEARCH_END_STATIC 1\n ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib/static\"\n LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib\"\n RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/tests\"\n OUTPUT_NAME minisyncpp)\n\n message(STATUS \"Configuring tests: done\")\nendif ()\n\nif (LIBMINISYNCPP_BUILD_DEMO)\n include(demo_build.cmake)\nendif ()\n" }, { "alpha_fraction": 0.7033993005752563, "alphanum_fraction": 0.7273613810539246, "avg_line_length": 38.877777099609375, "blob_id": "804cae8e561e4b77500034ad73647906e7be0d17", "content_id": "f4dacf512ed97726c4a88b564bd91d96605aa877", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7179, "license_type": "permissive", "max_line_length": 127, "num_lines": 180, "path": "/README.md", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "# MiniSynCPP\n[![Build Status](https://travis-ci.org/molguin92/MiniSynCPP.svg?branch=master)](https://travis-ci.org/molguin92/MiniSynCPP)\n\nReference implementation in C++11 of the MiniSync/TinySync time synchronization algorithms detailed in [\\[1, 2\\]](#references).\nNote that this implementation is still pretty naive and probably should not be used for anything critical (yet).\n\n## Compilation\n### Containerized\nThe easiest way to compile the project is by invoking the `docker_build.sh` script, which sets up a complete, \nconfigured \nbuild environment inside a Docker container based on Ubuntu 18.04 and uses it to build:\n\n- Native x86_64 binaries, C++ and Python 3.6+ libraries for Linux.\n- Native ARMv7 binaries and C++ libraries intended for the Raspberry Pi 2/3/3 A/B+.\n*The cross-compilers used for this can be found [here.](https://github.com/abhiTronix/raspberry-pi-cross-compilers)*\n\n### Native\nThe requirements for native compilation are:\n\n- CMAKE\n- C++11 Compiler (gcc, g++, clang).\n- Python 3.6+, along with the associated development headers.\n\nAn easy way to install all necessary dependencies on Ubuntu is:\n```bash\n$ sudo apt install build-essential cmake gcc g++ clang \\\n python3-all python3-all-dev libpython3-all-dev \\\n python3-setuptools python3-distutils python3-distutils-extra\n```\n\nCompilation is then just a matter of running:\n```bash\n$> mkdir ./cmake_build \n$> cd ./cmake_build\n$> cmake -DCMAKE_BUILD_TYPE=Release .. # (*)\n$> cmake --build . --target all -- -j 4\n$> tests/minisyncpp # run some tests\n```\n\n(*) The CMAKE configure command accepts the following option flags:\n\n- `-DCMAKE_BUILD_TYPE={Debug/Release}`: Specifies the build type. Debug builds include additional debugging output.\n- `-DLIBMINISYNCPP_BUILD_DEMO={TRUE/FALSE}`: Whether to build an additional demo program to showcase the workings of \nthe library.\n- `-DLIBMINISYNCPP_BUILD_TESTS={TRUE/FALSE}`: Build unittests.\n- `-DLIBMINISYNCPP_ENABLE_LOGURU={TRUE/FALSE}`: For library-only builds, whether to build with Loguru logging support.\n- `-DLIBMINISYNCPP_WITH_PYTHON={TRUE/FALSE}`: Build Python 3.6+ library. Requires Python 3.6+ with the development \nheaders. On Ubuntu, these can be installed with `sudo apt install python3.7 python3.7-dev`.\n\nNote: Even though the project uses the Google Protobuf libraries, it is not necessary to have these installed when \ncompiling, as the build chain will download its own copy anyway to statically link them. This is mainly done for \nportability and cross-compilation purposes.\n\n## Usage\n\n### Library\n\nBy default the CMAKE toolchain builds static and shared copies of the library, using the CMAKE targets \n`libminisyncpp_static` and `libminisyncpp_static`. These can be used by compiling your program with the interface \nheader `minisync_api.h` and linking it with the library.\n\nThe easiest way of achieving this is by including the libraries as a CMAKE subproject (e.g. through `FetchContent` \npaired with `add_subdirectory`):\n\n```cmake\ninclude(FetchContent REQUIRED)\n### Set some CMAKE flags\nset(LIBMINISYNCPP_ENABLE_LOGURU TRUE CACHE BOOL \"\" FORCE) # use loguru\nset(LIBMINISYNCPP_WITH_PYTHON TRUE CACHE BOOL \"\" FORCE) # build python library\n### Fetch libminisyncpp\nFetchContent_Declare(\n minisyncpp\n # download\n GIT_REPOSITORY \"https://github.com/molguin92/MiniSynCPP.git\"\n GIT_TAG \"master\" # or a specific release tag\n # ---\n )\nFetchContent_GetProperties(minisyncpp)\nif (NOT minisyncpp_POPULATED)\n FetchContent_Populate(minisyncpp)\n add_subdirectory(${minisyncpp_SOURCE_DIR})\n \n ### The project exports two variables for easy use:\n # LIBMINISYNCPP_HDR: the full path to the api header file minisyncp_api.h\n # LIBMINISYNCPP_INCLUDE: the full path to the library include directory\n \n include_directories(${LIBMINISYNCPP_INCLUDE})\nendif ()\n\n# ...\n\nadd_executable(myexe foo.cpp bar.hpp ${LIBMINISYNCPP_HDR})\nadd_dependencies(myexe libminisyncpp_static)\ntarget_link_libraries(myexe libminisyncpp_static)\n\n```\n\nFor details on the API, see the pretty self-explanatory [minisync_api.h](src/libminisyncpp/minisync_api.h).\n\n### Demo Program\n\nThe demo program includes a help message accessible through the ```-h, --help``` flags.\n\n```bash\n$> MiniSynCPP --help\nMiniSynCPP v0.4. Standalone demo implementation of the Tiny/MiniSync time synchronization algorithms.\nUsage: MiniSynCPP [OPTIONS] SUBCOMMAND\n\nOptions:\n -h,--help Print this help message and exit\n\nSubcommands:\n REF_MODE Start node in reference mode; i.e. other peers synchronize to this node's clock.\n SYNC_MODE Start node in synchronization mode.\n```\n\nHelp is also available per application mode:\n```bash\n$> MiniSynCPP SYNC_MODE --help\nStart node in synchronization mode.\nUsage: MiniSynCPP SYNC_MODE [OPTIONS] BIND_PORT ADDRESS PORT\n\nPositionals:\n BIND_PORT UINT REQUIRED Local UDP port to bind to.\n ADDRESS TEXT REQUIRED Address of peer to synchronize with.\n PORT UINT REQUIRED Target UDP Port on peer.\n\nOptions:\n -h,--help Print this help message and exit\n -v INT=-2 Set verbosity level.\n -o,--output TEXT Output stats to file.\n -b,--bandwidth FLOAT Nominal bandwidth in Mbps, for minimum delay estimation.\n -p,--ping FLOAT Nominal minimum ICMP ping RTT in milliseconds for better minimum delay estimation.\n\n$> MiniSynCPP REF_MODE --help\nStart node in reference mode; i.e. other peers synchronize to this node's clock.\nUsage: MiniSynCPP REF_MODE [OPTIONS] BIND_PORT\n\nPositionals:\n BIND_PORT UINT REQUIRED Local UDP port to bind to.\n\nOptions:\n -h,--help Print this help message and exit\n -v INT=-2 Set verbosity level.\n```\n\nBasic usage involves:\n\n1. Initializing a node on one client in reference mode. *Reference mode* means that the node will act as a reference \nto other clocks, i.e. its clock remains unaltered and other clocks synchronize to it.\n\nExample: \n```bash\nuser@ref_node $> MiniSynCPP -v 0 REF_MODE 1338\n```\n\n2. Initializing a node on another client in sync mode, and point it to the reference node. \n\nExample:\n\n```bash\nuser@sync_node $> MiniSynCPP -v 0 SYNC_MODE 1338 192.168.0.123 1338 --bandwidth 300 --ping 1.20\n```\n\n## References\n[1] S. Yoon, C. Veerarittiphan, and M. L. Sichitiu. 2007. Tiny-sync: Tight time synchronization for wireless sensor \nnetworks. ACM Trans. Sen. Netw. 3, 2, Article 8 (June 2007). \nDOI: 10.1145/1240226.1240228 \n\n[2] M. L. Sichitiu and C. Veerarittiphan, \"Simple, accurate time synchronization for wireless sensor networks,\" 2003 \nIEEE Wireless Communications and Networking, 2003. WCNC 2003., New Orleans, LA, USA, 2003, pp. 1266-1273 vol.2. DOI: \n10.1109/WCNC.2003.1200555. URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1200555&isnumber=27029\n\n## Copyright\n [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nCode is Copyright© (2019 -) of Manuel Olguín Muñoz \\<[email protected]\\>, provided under an MIT License.\nSee [LICENSE](LICENSE) for details.\n\nThe TinySync and MiniSync algorithms are owned by the authors of the referenced papers [1, 2].\n" }, { "alpha_fraction": 0.5134899616241455, "alphanum_fraction": 0.5335074067115784, "avg_line_length": 33.818180084228516, "blob_id": "ce3f71c19f7acb474eabba4306e2ebdf3d6ad35a", "content_id": "950f2c22fa06ac6b5d626e86d1444792f4ba4916", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "permissive", "max_line_length": 71, "num_lines": 33, "path": "/analysis/analysis.py", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "import pandas\nfrom matplotlib import pyplot as plt\n\nif __name__ == '__main__':\n df = pandas.read_csv(\"./stats.csv\", sep=';', index_col=False)\n # df = df.drop([0])\n # df.plot(x='Sample', y='Drift', yerr='Drift Error')\n fig, ax = plt.subplots()\n ax.plot(df['Sample'], df['Drift'], label='Drift', color='blue')\n ax.fill_between(df['Sample'],\n df['Drift'] - df['Drift Error'],\n df['Drift'] + df['Drift Error'],\n color='gray', alpha=0.2)\n ax.legend()\n # ax.set_yscale('symlog', basey=10)\n ax.set_xscale('symlog', basex=10)\n plt.show()\n fig.savefig('drift.png')\n\n fig, ax = plt.subplots()\n offsets_ms = (df['Offset']) / 1000.0\n e_offsets_ms = df['Offset Error'] / 1000.0\n\n ax.plot(df['Sample'], offsets_ms, label='Offset [ms]', color='red')\n ax.fill_between(df['Sample'],\n offsets_ms - e_offsets_ms,\n offsets_ms + e_offsets_ms,\n color='gray', alpha=0.2)\n # ax.set_yscale('symlog', basey=10)\n ax.set_xscale('symlog', basex=10)\n ax.legend()\n plt.show()\n fig.savefig('offset.png')\n" }, { "alpha_fraction": 0.6829160451889038, "alphanum_fraction": 0.7052958011627197, "avg_line_length": 35.69105529785156, "blob_id": "617f2cc3721d63183488b77739e67b345f16466b", "content_id": "9237d78ad56386552a7b395a1d10b0326c2f38a4", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4513, "license_type": "permissive", "max_line_length": 114, "num_lines": 123, "path": "/demo_build.cmake", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "### DEMO SETUP\ninclude(FetchContent REQUIRED)\n\nset(MINISYNCPP_DEMO_VERSION_MAJOR \"0\")\nset(MINISYNCPP_DEMO_VERSION_MINOR \"5.2\")\nset(MINISYNCPP_PROTO_VERSION_MAJOR 1)\nset(MINISYNCPP_PROTO_VERSION_MINOR 0)\nconfigure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/demo/demo_config.h.in\n ${CMAKE_CURRENT_BINARY_DIR}/include/demo_config.h)\n\nset(PROTOBUF_URL https://github.com/protocolbuffers/protobuf)\nset(PROTOBUF_VERSION \"3.7.1\")\n\nif (APPLE)\n set(PROTOC_ARCHIVE\n \"${PROTOBUF_URL}/releases/download/v${PROTOBUF_VERSION}/protoc-${PROTOBUF_VERSION}-osx-x86_64.zip\")\n set(PROTOC_MD5 \"2e211695af8062f7f02dfcfa499fc0a7\")\nelseif (UNIX)\n set(PROTOC_ARCHIVE\n \"${PROTOBUF_URL}/releases/download//v${PROTOBUF_VERSION}/protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\")\n set(PROTOC_MD5 \"8927139bc77e63c32ea017cbea891f46\")\nendif ()\n\n# set options ahead of protobuf download\nset(protobuf_BUILD_TESTS OFF CACHE BOOL \"Turn off Protobuf tests\" FORCE)\nset(protobuf_BUILD_EXAMPLES OFF CACHE BOOL \"Turn off Protobuf examples\" FORCE)\nset(protobuf_WITH_ZLIB OFF CACHE BOOL \"Turn off Protobuf with zlib\" FORCE)\nset(protobuf_BUILD_SHARED_LIBS OFF CACHE BOOL \"Force Protobuf static libs\" FORCE)\nset(protobuf_BUILD_PROTOC_BINARIES OFF CACHE BOOL \"Don't build Protoc\" FORCE)\n\nFetchContent_Declare(\n protobuf\n # download\n GIT_REPOSITORY \"${PROTOBUF_URL}.git\"\n GIT_TAG \"v${PROTOBUF_VERSION}\"\n # ---\n)\nFetchContent_GetProperties(protobuf)\nif (NOT protobuf_POPULATED)\n message(STATUS \"Populating Protobuf sources...\")\n FetchContent_Populate(protobuf)\n add_subdirectory(\"${protobuf_SOURCE_DIR}/cmake\" \"${protobuf_BINARY_DIR}/cmake\")\n message(STATUS \"Populating Protobuf sources: done\")\nendif ()\n\n# get CLI11\nset(CLI_TESTING OFF CACHE BOOL \"Turn off CLI11 tests\" FORCE)\nset(CLI_EXAMPLES OFF CACHE BOOL \"Turn off CLI11 examples\" FORCE)\nset(CLI11_URL https://github.com/CLIUtils/CLI11)\nset(CLI11_VERSION \"1.7.1\")\nFetchContent_Declare(\n cli11\n # download\n GIT_REPOSITORY \"${CLI11_URL}.git\"\n GIT_TAG \"v${CLI11_VERSION}\"\n # ---\n)\nFetchContent_GetProperties(cli11)\nif (NOT cli11_POPULATED)\n message(STATUS \"Populating CLI11 sources...\")\n FetchContent_Populate(cli11)\n add_subdirectory(\"${cli11_SOURCE_DIR}\" \"${cli11_BINARY_DIR}\")\n message(STATUS \"Populating Protobuf sources: done\")\nendif ()\n\ninclude_directories(include\n ${CMAKE_CURRENT_BINARY_DIR}\n ${CMAKE_CURRENT_BINARY_DIR}/include)\n\n\nlink_directories(lib lib/static\n ${CMAKE_CURRENT_BINARY_DIR}/lib\n ${CMAKE_CURRENT_BINARY_DIR}/lib/static)\n\nFetchContent_Declare(\n protoc\n URL ${PROTOC_ARCHIVE}\n URL_MD5 ${PROTOC_MD5}\n)\nFetchContent_GetProperties(protoc)\nif (NOT protoc_POPULATED)\n message(STATUS \"Fetching Protobuf Compiler...\")\n FetchContent_Populate(protoc)\n set(PROTOC_PATH ${protoc_SOURCE_DIR}/bin/protoc)\n message(STATUS \"Fetching Protobuf Compiler: Done\")\nendif ()\n\n\n# generate protobuf definitions\nset(PROTO_SRC ${CMAKE_CURRENT_BINARY_DIR}/protocol.pb.cc ${CMAKE_CURRENT_BINARY_DIR}/protocol.pb.h)\nadd_custom_command(OUTPUT ${PROTO_SRC}\n COMMAND ${PROTOC_PATH} protocol.proto --cpp_out=${CMAKE_CURRENT_BINARY_DIR}\n MAIN_DEPENDENCY ${CMAKE_CURRENT_SOURCE_DIR}/src/demo/net/protocol.proto\n COMMENT \"Generating Protobuf definitions...\"\n WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/demo/net)\n\nadd_executable(MiniSyncDemo\n ${CMAKE_CURRENT_BINARY_DIR}/include/demo_config.h\n ${CMAKE_CURRENT_BINARY_DIR}/include/minisync_api.h\n src/demo/main.cpp\n src/demo/node.cpp src/demo/node.h\n src/demo/exception.cpp src/demo/exception.h\n src/demo/stats.cpp src/demo/stats.h\n ${PROTO_SRC}\n ${LOGURU_SRC} # loguru, credit to emilk@github\n )\n\nadd_dependencies(MiniSyncDemo libprotobuf libminisyncpp_static CLI11)\n\nset_target_properties(MiniSyncDemo\n PROPERTIES\n LINK_SEARCH_START_STATIC 1\n LINK_SEARCH_END_STATIC 1\n VERSION \"${MINISYNCPP_DEMO_VERSION_MAJOR}.${MINISYNCPP_DEMO_VERSION_MINOR}\"\n ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib/static\"\n LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/lib\"\n RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/bin\")\n\ntarget_link_libraries(MiniSyncDemo\n libminisyncpp_static # link against the algorithm\n libprotobuf # link against protobuf\n CLI11 # link against CLI11\n dl ${CMAKE_THREAD_LIBS_INIT})\n" }, { "alpha_fraction": 0.4971058964729309, "alphanum_fraction": 0.5018726587295532, "avg_line_length": 18.45033073425293, "blob_id": "91a4ae276750eac67a2a5e81ba2b687272069ee9", "content_id": "c7c3cb76bf65f2f3023ebd6c3904f0fa65ee6876", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2938, "license_type": "permissive", "max_line_length": 102, "num_lines": 151, "path": "/src/libminisyncpp/constraints.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef MINISYNCPP_CONSTRAINTS_H\n#define MINISYNCPP_CONSTRAINTS_H\n\n# include <tuple>\n# include <exception>\n# include <map>\n# include <set>\n# include \"minisync_api.h\"\n\nnamespace MiniSync\n{\n\n class Point\n {\n private:\n us_t x;\n us_t y;\n public:\n Point() : x(0), y(0)\n {};\n\n Point(us_t x, us_t y) : x(x), y(y)\n {};\n\n const us_t& getX() const\n {\n return this->x;\n }\n\n const us_t& getY() const\n {\n return this->y;\n }\n\n protected:\n Point(const Point& o) = default;\n bool operator==(const Point& o) const;\n };\n\n class LowPoint : public Point\n {\n public:\n LowPoint() : Point()\n {}\n\n LowPoint(us_t x, us_t y) : Point(x, y)\n {}\n\n LowPoint(const LowPoint& o) = default;\n\n bool operator==(const LowPoint& o) const\n {\n return Point::operator==(o);\n };\n\n bool operator!=(const LowPoint& o) const\n {\n return !Point::operator==(o);\n }\n\n bool operator<(const LowPoint& o) const\n {\n return this->getX() < o.getX();\n }\n\n bool operator>(const LowPoint& o) const\n {\n return this->getX() > o.getX();\n }\n };\n\n class HighPoint : public Point\n {\n public:\n HighPoint() : Point()\n {}\n\n HighPoint(us_t x, us_t y) : Point(x, y)\n {}\n\n HighPoint(const HighPoint& o) = default;\n\n bool operator==(const HighPoint& o) const\n {\n return Point::operator==(o);\n };\n\n bool operator!=(const HighPoint& o) const\n {\n return !Point::operator==(o);\n }\n\n bool operator<(const HighPoint& o) const\n {\n return this->getX() < o.getX();\n }\n\n bool operator>(const HighPoint& o) const\n {\n return this->getX() > o.getX();\n }\n };\n\n class ConstraintLine\n {\n public:\n\n ConstraintLine() : A(0), B(0)\n {};\n ConstraintLine(const LowPoint& p1, const HighPoint& p2);\n\n ConstraintLine(const HighPoint& p1, const LowPoint& p2) : ConstraintLine(p2, p1)\n {};\n\n ConstraintLine(const ConstraintLine& o) :\n A(o.getA()), B(o.getB())\n {}\n\n long double getA() const\n { return this->A; }\n\n us_t getB() const\n { return this->B; }\n\n bool operator==(const ConstraintLine& o) const;\n\n std::string toString() const;\n\n private:\n long double A;\n us_t B;\n\n };\n}\n\nnamespace std\n{\n template<>\n struct hash<MiniSync::Point>\n {\n size_t operator()(const MiniSync::Point& point) const;\n };\n}\n#endif //MINISYNCPP_CONSTRAINTS_H\n" }, { "alpha_fraction": 0.7137870788574219, "alphanum_fraction": 0.7207679152488708, "avg_line_length": 27.649999618530273, "blob_id": "884449ec5b6cac33e2f95e0b57bdcf7dc278ee7a", "content_id": "7bb3b43f81d6a489450ec38f3f2bbf4737412447", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 574, "license_type": "permissive", "max_line_length": 102, "num_lines": 20, "path": "/src/libminisyncpp/minisync_api.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include \"minisync_api.h\"\n#include \"minisync.h\"\n\n\nstd::shared_ptr<MiniSync::API::Algorithm> MiniSync::API::Factory::createTinySync()\n{\n return std::shared_ptr<MiniSync::API::Algorithm>(new MiniSync::Algorithms::TinySync());\n}\n\nstd::shared_ptr<MiniSync::API::Algorithm> MiniSync::API::Factory::createMiniSync()\n{\n return std::shared_ptr<MiniSync::API::Algorithm>(new MiniSync::Algorithms::MiniSync());\n}\n" }, { "alpha_fraction": 0.551997184753418, "alphanum_fraction": 0.5603857040405273, "avg_line_length": 38.61335372924805, "blob_id": "0d8a16676bde82bc91f325d3d5d308f239c60ae0", "content_id": "107a9e8c3b9ceac6900274d28b8e43fb63c00517", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25524, "license_type": "permissive", "max_line_length": 121, "num_lines": 644, "path": "/src/demo/node.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include <utility>\n#include <cstring>\n#include <unistd.h>\n#include <protocol.pb.h>\n#include <google/protobuf/message.h>\n#include <thread>\n#include <loguru.hpp>\n#include <demo_config.h>\n#include \"node.h\"\n#include \"exception.h\"\n//#include \"algorithms/constraints.h\"\n\n#ifdef __x86_64__\n#define PRISIZE_T PRIu64\n#else\n#define PRISIZE_T PRId32\n#endif\n\nMiniSync::Node::Node(uint16_t bind_port, MiniSync::Protocol::NodeMode mode) :\n bind_port(bind_port), local_addr(SOCKADDR{}), mode(mode), running(true)\n{\n this->sock_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);\n int enable = 1;\n setsockopt(this->sock_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));\n\n memset(&this->local_addr, 0, sizeof(this->local_addr));\n this->local_addr.sin_family = AF_INET;\n this->local_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n this->local_addr.sin_port = htons(bind_port);\n\n LOG_F(INFO, \"Binding UDP socket to port %\"\n PRIu16\n \"\", this->bind_port);\n CHECK_GE_F(bind(this->sock_fd, (struct sockaddr*) &this->local_addr, sizeof(this->local_addr)), 0,\n \"Failed to bind socket to UDP port %\"\n PRIu16, bind_port);\n\n // estimate minimum possible delay by looping messages on the loopback interface\n int loop_in_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);\n int loop_out_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);\n uint16_t loopback_port = 5555; // TODO: Parametrize hardcoded port\n uint_fast32_t total_samples = 5000; // TODO: parametrize\n uint_fast32_t considered_samples = 1000;\n\n setsockopt(loop_in_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));\n setsockopt(loop_out_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));\n\n sockaddr_in loopback_addr{0x00};\n memset(&loopback_addr, 0, sizeof(loopback_addr));\n loopback_addr.sin_family = AF_INET;\n inet_aton(\"127.0.0.1\", &loopback_addr.sin_addr);\n loopback_addr.sin_port = htons(loopback_port);\n\n CHECK_GE_F(bind(loop_in_fd, (struct sockaddr*) &loopback_addr, sizeof(loopback_addr)), 0,\n \"Failed to bind UDP socket to loopback interface, port %d\", loopback_port);\n\n // estimate\n // set a global time reference point for using steady_clock timestamps\n auto T0 = std::chrono::steady_clock::now();\n // set up a separate thread for echoing messages\n std::thread t([loop_in_fd, total_samples, T0]()\n {\n uint8_t in_buf[MAX_MSG_LEN] = {0x00};\n uint8_t out_buf[MAX_MSG_LEN] = {0x00};\n sockaddr_in reply_to{0x00};\n socklen_t reply_to_len = sizeof(sockaddr_in);\n ssize_t in_msg_len;\n ssize_t out_msg_len;\n\n MiniSync::Protocol::MiniSyncMsg msg_bcn{};\n MiniSync::Protocol::MiniSyncMsg reply{};\n reply.set_allocated_beacon_r(new MiniSync::Protocol::BeaconReply{});\n\n std::chrono::steady_clock::time_point t_in;\n\n for (int_fast32_t i = 0; i < total_samples; ++i)\n {\n // read incoming\n CHECK_GE_F((in_msg_len = recvfrom(loop_in_fd, in_buf, MAX_MSG_LEN, 0,\n (sockaddr*) &reply_to, &reply_to_len)), 0,\n \"Error reading from socket on loopback interface...\");\n t_in = std::chrono::steady_clock::now();\n\n msg_bcn.ParseFromArray(in_buf, in_msg_len);\n reply.mutable_beacon_r()->set_seq(msg_bcn.beacon().seq());\n reply.mutable_beacon_r()->set_beacon_recv_time(\n std::chrono::duration_cast<std::chrono::nanoseconds>(t_in - T0).count()\n );\n reply.mutable_beacon_r()->set_reply_send_time(\n std::chrono::duration_cast<std::chrono::nanoseconds>(\n std::chrono::steady_clock::now() - T0).count()\n );\n\n // send it right back...\n out_msg_len = reply.ByteSizeLong();\n reply.SerializeToArray(out_buf, out_msg_len);\n CHECK_GE_F(sendto(loop_in_fd, out_buf, out_msg_len, 0,\n (sockaddr*) &reply_to, reply_to_len), 0,\n \"Error writing to socket on loopback interface.\");\n\n // cleanup\n memset(in_buf, 0x00, MAX_MSG_LEN);\n memset(out_buf, 0x00, MAX_MSG_LEN);\n memset(&reply_to, 0x00, reply_to_len);\n }\n });\n\n // measure\n MiniSync::Protocol::MiniSyncMsg bcn_msg{};\n MiniSync::Protocol::MiniSyncMsg rpl_msg{};\n bcn_msg.set_allocated_beacon(new MiniSync::Protocol::Beacon{});\n uint8_t beacon_buf[MAX_MSG_LEN] = {0x00};\n uint8_t reply_buf[MAX_MSG_LEN] = {0x00};\n ssize_t out_sz, in_sz;\n\n us_t min_bcn_delay{std::numeric_limits<long double>::max()};\n us_t min_rpl_delay{std::numeric_limits<long double>::max()};\n std::chrono::steady_clock::duration t_out, t_in;\n socklen_t addr_sz = sizeof(sockaddr_in);\n for (int_fast32_t i = 0; i < total_samples; ++i)\n {\n bcn_msg.mutable_beacon()->set_seq(i % UINT8_MAX);\n out_sz = bcn_msg.ByteSizeLong();\n bcn_msg.SerializeToArray(beacon_buf, out_sz);\n t_out = std::chrono::steady_clock::now() - T0;\n // send payload\n CHECK_GE_F(sendto(loop_out_fd, beacon_buf, out_sz, 0, (sockaddr*) &loopback_addr, addr_sz), 0,\n \"Error writing to socket on loopback interface.\");\n\n // get reply\n CHECK_GE_F((in_sz = recvfrom(loop_out_fd, reply_buf, MAX_MSG_LEN, 0, nullptr, nullptr)), 0,\n \"Error reading from socket on loopback interface...\");\n t_in = std::chrono::steady_clock::now() - T0;\n rpl_msg.ParseFromArray(reply_buf, in_sz);\n\n if (i >= total_samples - considered_samples)\n {\n // only consider the last n samples, to give the processor some time to spin up\n // TODO: parametrize number of considered samples and total number of samples\n // delays include both the delay through the network stack on the way out and on the way in, so divide by 2.0\n // we assume symmetric delays\n auto bcn_delay = (std::chrono::nanoseconds{rpl_msg.beacon_r().beacon_recv_time()} - t_out) / 2.0;\n auto rpl_delay = (t_in - std::chrono::nanoseconds{rpl_msg.beacon_r().reply_send_time()}) / 2.0;\n min_bcn_delay = std::min(std::chrono::duration_cast<us_t>(bcn_delay), min_bcn_delay);\n min_rpl_delay = std::min(std::chrono::duration_cast<us_t>(rpl_delay), min_rpl_delay);\n }\n\n // cleanup\n memset(beacon_buf, 0x00, MAX_MSG_LEN);\n memset(reply_buf, 0x00, MAX_MSG_LEN);\n }\n t.join();\n\n this->minimum_delays.beacon = min_bcn_delay;\n this->minimum_delays.beacon_reply = min_rpl_delay;\n\n LOG_F(INFO, \"Minimum latencies through the network stack:\");\n LOG_F(INFO, \"Beacons: %Lf µs\", min_bcn_delay.count());\n LOG_F(INFO, \"Beacon replies: %Lf µs\", min_rpl_delay.count());\n shutdown(loop_in_fd, SHUT_RDWR);\n shutdown(loop_out_fd, SHUT_RDWR);\n close(loop_in_fd);\n close(loop_out_fd);\n}\n\nMiniSync::Node::~Node()\n{\n // close the socket on destruction\n LOG_F(WARNING, \"Shutting down, bye bye!\");\n if (this->running.load())\n this->shut_down();\n // shutdown(this->sock_fd, SHUT_RDWR);\n // close(this->sock_fd);\n}\n\nMiniSync::us_t\nMiniSync::Node::send_message(MiniSync::Protocol::MiniSyncMsg& msg, const sockaddr* dest)\n{\n size_t out_sz = msg.ByteSize();\n uint8_t reply_buf[out_sz];\n msg.SerializeToArray(reply_buf, out_sz);\n\n DLOG_F(INFO, \"Sending a message of size %\"\n PRISIZE_T\n \" bytes...\", out_sz);\n\n us_t timestamp = std::chrono::steady_clock::now() - start; // timestamp BEFORE passing on to network stack\n if (sendto(this->sock_fd, reply_buf, out_sz, 0, dest, sizeof(*dest)) != out_sz)\n {\n DLOG_F(WARNING, \"Could not write to socket.\");\n throw MiniSync::Exceptions::SocketWriteException();\n }\n\n DLOG_F(INFO, \"Sent a message of size %\"\n PRISIZE_T\n \" bytes with timestamp %Lf µs...\", out_sz, timestamp.count());\n return timestamp;\n}\n\nMiniSync::us_t\nMiniSync::Node::recv_message(MiniSync::Protocol::MiniSyncMsg& msg, struct sockaddr* reply_to)\n{\n uint8_t buf[MAX_MSG_LEN] = {0x00};\n ssize_t recv_sz;\n socklen_t reply_to_len = sizeof(struct sockaddr_in);\n msg.Clear();\n\n DLOG_F(INFO, \"Listening for incoming messages...\");\n if (reply_to != nullptr)\n memset(reply_to, 0x00, reply_to_len);\n\n if ((recv_sz = recvfrom(this->sock_fd, buf, MAX_MSG_LEN, 0, reply_to, &reply_to_len)) < 0)\n {\n if (errno == EAGAIN || errno == EWOULDBLOCK)\n {\n DLOG_F(WARNING, \"Timed out waiting for messages.\");\n throw MiniSync::Exceptions::TimeoutException();\n }\n else throw MiniSync::Exceptions::SocketReadException();\n }\n\n us_t timestamp = std::chrono::steady_clock::now() - start; // timestamp after receiving whole message\n\n DLOG_F(INFO, \"Got %\"\n PRISIZE_T\n \" bytes of data at time %Lf µs.\", recv_sz, timestamp.count());\n // deserialize buffer into a protobuf message\n if (!msg.ParseFromArray(buf, recv_sz))\n {\n DLOG_F(WARNING, \"Failed to deserialize payload.\");\n throw MiniSync::Exceptions::DeserializeMsgException();\n }\n return timestamp;\n}\n\nvoid MiniSync::Node::shut_down()\n{\n // force clean shut down\n this->running.store(false);\n shutdown(this->sock_fd, SHUT_RDWR);\n close(this->sock_fd);\n}\n\nvoid MiniSync::SyncNode::run()\n{\n this->handshake();\n this->sync();\n}\n\n/*\n * Simply listens for incoming beacons and replies accordingly.\n */\nvoid MiniSync::ReferenceNode::run()\n{\n this->wait_for_handshake();\n this->serve();\n}\n\nvoid MiniSync::SyncNode::handshake()\n{\n // send handshake request to peer\n MiniSync::Protocol::MiniSyncMsg msg{};\n msg.set_allocated_handshake(new MiniSync::Protocol::Handshake{});\n msg.mutable_handshake()->set_mode(this->mode);\n msg.mutable_handshake()->set_version_major(PROTOCOL_VERSION_MAJOR);\n msg.mutable_handshake()->set_version_minor(PROTOCOL_VERSION_MINOR);\n\n MiniSync::Protocol::MiniSyncMsg incoming{};\n while (this->running.load())\n {\n try\n {\n LOG_F(INFO, \"Initializing handshake with peer %s:%\"\n PRIu16\n \".\", this->peer.c_str(), this->peer_port);\n this->send_message(msg, (struct sockaddr*) &this->peer_addr);\n // wait for handshake response\n this->recv_message(incoming, (struct sockaddr*) &this->peer_addr);\n\n if (!incoming.has_handshake_r())\n {\n // message needs to be a handshake reply\n LOG_F(WARNING, \"Got a message from peer which was not a handshake reply.\");\n continue;\n }\n const MiniSync::Protocol::HandshakeReply& reply = incoming.handshake_r();\n switch (reply.status())\n {\n case Protocol::HandshakeReply_Status_SUCCESS:\n {\n // if success, we can \"connect\" the socket and move on to actually synchronizing.\n CHECK_GE_F(connect(this->sock_fd, (struct sockaddr*) &this->peer_addr, sizeof(this->peer_addr)), 0,\n \"Failed connecting socket to peer %s:%\"\n PRIu16, this->peer.c_str(), this->peer_port);\n // \"start\" local clock\n this->start = std::chrono::steady_clock::now();\n return;\n }\n\n case Protocol::HandshakeReply_Status_VERSION_MISMATCH:\n LOG_F(ERROR, \"Handshake failed: version mismatch.\");\n case Protocol::HandshakeReply_Status_MODE_MISMATCH:\n LOG_F(ERROR, \"Handshake failed: Mode mismatch between the nodes.\");\n case Protocol::HandshakeReply_Status_HandshakeReply_Status_INT_MIN_SENTINEL_DO_NOT_USE_:\n case Protocol::HandshakeReply_Status_HandshakeReply_Status_INT_MAX_SENTINEL_DO_NOT_USE_:\n case Protocol::HandshakeReply_Status_ERROR:\n LOG_F(ERROR, \"Handshake failed with unspecified error!\");\n this->running.store(false);\n }\n }\n // only catch expected exceptions, the rest we leave to the main code\n catch (MiniSync::Exceptions::TimeoutException& e)\n {\n // if timed out, repeat!\n LOG_F(INFO, \"Timed out waiting for handshake reply, retrying...\");\n continue;\n }\n catch (MiniSync::Exceptions::DeserializeMsgException& e)\n {\n // Error while receiving message, probably malformed so just discard it\n LOG_F(INFO, \"Failed to deserialize incoming message, retrying...\");\n continue;\n }\n }\n}\n\nvoid MiniSync::SyncNode::sync()\n{\n // send sync beacons and wait for timestamps\n MiniSync::Protocol::MiniSyncMsg msg{};\n\n us_t to, tbr, tbt, tr;\n uint8_t seq = 0;\n ssize_t send_sz, recv_sz;\n\n us_t min_uplink_delay{0}, min_downlink_delay{0};\n\n while (this->running.load())\n {\n auto t_i = std::chrono::steady_clock::now();\n msg.set_allocated_beacon(new MiniSync::Protocol::Beacon{});\n msg.mutable_beacon()->set_seq(seq);\n send_sz = msg.ByteSizeLong();\n\n LOG_F(INFO, \"Sending beacon (SEQ %\"\n PRIu8\n \").\", seq);\n\n MiniSync::Protocol::BeaconReply reply;\n\n try\n {\n // nullptr since we should already be connected\n to = this->send_message(msg, nullptr);\n\n for (;;)\n {\n // wait for reply without resending to avoid ugly feedback loops\n tr = this->recv_message(msg, nullptr);\n recv_sz = msg.ByteSizeLong();\n\n if (!msg.has_beacon_r())\n {\n LOG_F(WARNING, \"Got a message from peer which was not a beacon reply.\");\n continue;\n }\n else if ((reply = msg.beacon_r()).seq() != seq)\n {\n LOG_F(WARNING, \"Beacon reply was out of order, ignoring...\");\n continue;\n }\n else break; // reply is valid\n }\n }\n // only catch exceptions that we can work with\n catch (MiniSync::Exceptions::TimeoutException& e)\n {\n // timed out, retry sending beacon\n LOG_F(INFO, \"Timed out waiting for beacon reply, retrying...\");\n continue;\n }\n catch (MiniSync::Exceptions::DeserializeMsgException& e)\n {\n // could not parse incoming message, just retry\n LOG_F(WARNING, \"Could not deserialize incoming message, retrying...\");\n continue;\n }\n\n\n // timestamps are in nanoseconds, but protocol works with microseconds\n tbr = us_t{std::chrono::nanoseconds{reply.beacon_recv_time()}};\n tbt = us_t{std::chrono::nanoseconds{reply.reply_send_time()}};\n\n // adjust local timestamps with minimum delays for beacons and replies\n to += this->minimum_delays.beacon;\n tr -= this->minimum_delays.beacon_reply;\n\n // additional adjustment based on bandwidth\n if (this->bw_bytes_per_usecond > 0)\n {\n // ACK size on WiFi is 14 bytes, so let's use that as the minimum frame size\n send_sz = std::max(send_sz, static_cast<ssize_t>(14));\n recv_sz = std::max(recv_sz, static_cast<ssize_t>(14));\n min_uplink_delay = us_t{send_sz / bw_bytes_per_usecond};\n min_downlink_delay = us_t{recv_sz / bw_bytes_per_usecond};\n }\n\n // adjustment based on ping\n min_uplink_delay = std::max(min_uplink_delay, this->min_ping_oneway_us);\n min_downlink_delay = std::max(min_downlink_delay, this->min_ping_oneway_us);\n\n to += min_uplink_delay;\n tr -= min_downlink_delay;\n\n // add data points\n this->algo->addDataPoint(to, tbr, tr);\n this->algo->addDataPoint(to, tbt, tr);\n\n auto drift = algo->getDrift();\n auto drift_error = algo->getDriftError();\n auto offset = algo->getOffset();\n auto offset_error = algo->getOffsetError();\n\n auto\n adj_timestamp =\n std::chrono::duration_cast<us_t>(algo->getCurrentAdjustedTime().time_since_epoch());\n\n LOG_F(INFO, \"Current adjusted timestamp: %Lf µs\", adj_timestamp.count());\n LOG_F(INFO, \"Drift: %Lf | Error: +/- %Lf\", drift, drift_error);\n LOG_F(INFO, \"Offset: %Lf µs | Error: +/- %Lf µs\", offset.count(), offset_error.count());\n\n stats.add_sample(offset.count(), offset_error.count(), drift, drift_error);\n\n seq++;\n msg.Clear();\n // msg handles clearing beacon\n auto t_f = std::chrono::steady_clock::now();\n std::this_thread::sleep_for(std::chrono::milliseconds(100) - (t_f - t_i)); // TODO: parameterize\n }\n}\n\nMiniSync::SyncNode::SyncNode(uint16_t bind_port,\n std::string& peer,\n uint16_t peer_port,\n std::shared_ptr<MiniSync::API::Algorithm>&& sync_algo,\n std::string stat_file_path,\n double bandwidth_mbps,\n double min_ping_rtt_ms) :\n Node(bind_port, MiniSync::Protocol::NodeMode::SYNC),\n algo(std::move(sync_algo)), // take ownership of algorithm\n peer(peer),\n peer_port(peer_port),\n peer_addr({}),\n stats({}),\n stat_file_path(std::move(stat_file_path))\n{\n LOG_F(INFO, \"Initializing SyncNode.\");\n // set up peer addr\n memset(&this->peer_addr, 0, sizeof(SOCKADDR));\n\n peer_addr.sin_family = AF_INET;\n peer_addr.sin_addr.s_addr = inet_addr(this->peer.c_str());\n peer_addr.sin_port = htons(this->peer_port);\n\n // set a timeout for read operations, in order to send repeat beacons on timeouts\n struct timeval read_timeout{0x00};\n read_timeout.tv_sec = 0;\n read_timeout.tv_usec = MiniSync::SyncNode::RD_TIMEOUT_USEC;\n CHECK_EQ_F(setsockopt(this->sock_fd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof(read_timeout)), 0,\n \"Failed setting SO_RCVTIMEO option for socket.\");\n\n // store bandwidth in bytes/µsecond\n // 1 s = 1 000 000 µs\n // 1 Megabit = 1 000 000 bytes / 8\n // -> X * 1 Megabit / s = X * (1 000 000 bytes / 8) / 1 000 000 µs\n // = X / 8.0 bytes/µs\n if (bandwidth_mbps > 0)\n {\n this->bw_bytes_per_usecond = bandwidth_mbps / 8.0;\n LOG_F(INFO, \"User specified bandwidth: %f Mbps | %f bytes per µs\", bandwidth_mbps, bw_bytes_per_usecond);\n }\n else this->bw_bytes_per_usecond = -1.0;\n\n // ping rtt\n // we multiply it by a factor of 0.9 since we want the absolute minimum with a bit of leeway as well\n this->min_ping_oneway_us = min_ping_rtt_ms > 0 ? us_t{min_ping_rtt_ms * 1000.0 / 2.0 * 0.9} : us_t{-1.0};\n}\n\nMiniSync::SyncNode::~SyncNode()\n{\n if (!this->stat_file_path.empty())\n {\n this->stats.write_csv(this->stat_file_path);\n }\n}\n\nvoid MiniSync::ReferenceNode::serve()\n{\n // set up variables\n us_t recv_time;\n\n MiniSync::Protocol::MiniSyncMsg incoming{};\n MiniSync::Protocol::MiniSyncMsg outgoing{};\n\n // wait for beacons\n while (this->running.load())\n {\n // timestamp reception\n LOG_F(INFO, \"Listening for incoming beacons.\");\n try\n {\n recv_time = this->recv_message(incoming, nullptr);\n\n if (incoming.has_beacon())\n {\n // got beacon, so just reply\n const MiniSync::Protocol::Beacon& beacon = incoming.beacon();\n outgoing.set_allocated_beacon_r(new MiniSync::Protocol::BeaconReply{});\n outgoing.mutable_beacon_r()->set_seq(beacon.seq());\n outgoing.mutable_beacon_r()->set_beacon_recv_time(\n std::chrono::duration_cast<std::chrono::nanoseconds>(\n recv_time - this->minimum_delays.beacon).count()); // adjust with minimum delays\n\n LOG_F(INFO, \"Received a beacon (SEQ %\"\n PRIu8\n \").\", beacon.seq());\n\n outgoing.mutable_beacon_r()->set_reply_send_time(\n std::chrono::duration_cast<std::chrono::nanoseconds>(\n (std::chrono::steady_clock::now() - start) + this->minimum_delays.beacon_reply).count());\n\n LOG_F(INFO, \"Replying to beacon.\");\n this->send_message(outgoing, nullptr);\n }\n else if (incoming.has_goodbye())\n {\n // got goodbye, reply and shutdown\n LOG_F(WARNING, \"Got shutdown request.\");\n outgoing.set_allocated_goodbye_r(new MiniSync::Protocol::GoodByeReply{});\n this->send_message(outgoing, nullptr);\n this->running.store(false);\n }\n\n // clean up after send\n outgoing.Clear();\n // no need to clear up reply, outgoing takes care of it\n }\n catch (MiniSync::Exceptions::DeserializeMsgException& e)\n {\n // could not parse incoming message, just retry\n LOG_F(WARNING, \"Could not deserialize incoming message, retrying...\");\n continue;\n }\n }\n}\n\nvoid MiniSync::ReferenceNode::wait_for_handshake()\n{\n // set up variables\n struct sockaddr reply_to{};\n socklen_t reply_to_len = sizeof(reply_to);\n\n MiniSync::Protocol::MiniSyncMsg incoming{};\n MiniSync::Protocol::MiniSyncMsg outgoing{};\n\n // discard anything that is not a handshake request\n bool listening = true;\n while (listening && this->running.load())\n {\n // wait for handshake\n LOG_F(INFO, \"Waiting for incoming handshake requests.\");\n try\n {\n this->recv_message(incoming, &reply_to);\n if (incoming.has_handshake())\n {\n outgoing.set_allocated_handshake_r(new MiniSync::Protocol::HandshakeReply{});\n LOG_F(INFO, \"Received handshake request.\");\n using ReplyStatus = MiniSync::Protocol::HandshakeReply_Status;\n const auto& handshake = incoming.handshake();\n\n if (PROTOCOL_VERSION_MAJOR != handshake.version_major() ||\n PROTOCOL_VERSION_MINOR != handshake.version_minor())\n {\n LOG_F(WARNING, \"Handshake: Version mismatch.\");\n LOG_F(WARNING, \"Local version: %\"\n PRIu8\n \".%\"\n PRIu8\n \" - Remote version: %\"\n PRIu8\n \".%\"\n PRIu8,\n PROTOCOL_VERSION_MAJOR, PROTOCOL_VERSION_MINOR,\n handshake.version_major(), handshake.version_minor());\n outgoing.mutable_handshake_r()->set_status(ReplyStatus::HandshakeReply_Status_VERSION_MISMATCH);\n }\n else if (handshake.mode() == this->mode)\n {\n LOG_F(WARNING, \"Handshake: Mode mismatch.\");\n outgoing.mutable_handshake_r()->set_status(ReplyStatus::HandshakeReply_Status_MODE_MISMATCH);\n }\n else\n {\n // everything is ok, let's \"connect\"\n LOG_F(INFO, \"Handshake successful.\");\n outgoing.mutable_handshake_r()->set_status(ReplyStatus::HandshakeReply_Status_SUCCESS);\n // UDP is connectionless, this is merely to store the address of the client and \"fake\" a connection\n CHECK_GE_F(connect(this->sock_fd, &reply_to, reply_to_len), 0,\n \"Call to connect failed. ERRNO: %s\", strerror(errno));\n this->start = std::chrono::steady_clock::now(); // start counting time\n listening = false;\n }\n\n // reply is sent no matter what\n this->send_message(outgoing, &reply_to);\n // TODO: verify the handshake is received??\n\n // cleanup\n outgoing.Clear();\n // no need to clear reply, outgoing has ownership and will clear it\n }\n }\n catch (MiniSync::Exceptions::DeserializeMsgException& e)\n {\n // could not parse incoming message, just retry\n LOG_F(WARNING, \"Could not deserialize incoming message, retrying...\");\n continue;\n }\n }\n}\n\nMiniSync::ReferenceNode::ReferenceNode(uint16_t bind_port) :\n Node(bind_port, MiniSync::Protocol::NodeMode::REFERENCE)\n{\n LOG_F(INFO, \"Initializing ReferenceNode.\");\n}\n" }, { "alpha_fraction": 0.7386363744735718, "alphanum_fraction": 0.7431818246841431, "avg_line_length": 25.66666603088379, "blob_id": "524c425761b316ca3fda6f45266b62f632b82045", "content_id": "cece5e6dda541b105ed9ebdee288b779f9038094", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 881, "license_type": "permissive", "max_line_length": 102, "num_lines": 33, "path": "/src/demo/exception.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n* \n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include \"exception.h\"\n\nconst char* MiniSync::Exceptions::TimeoutException::what() const noexcept\n{\n return \"Operation timed out.\";\n}\n\nconst char* MiniSync::Exceptions::SocketReadException::what() const noexcept\n{\n return \"Error while trying to read from socket.\";\n}\n\nconst char* MiniSync::Exceptions::SocketWriteException::what() const noexcept\n{\n return \"Error while trying to write to socket.\";\n}\n\nconst char* MiniSync::Exceptions::DeserializeMsgException::what() const noexcept\n{\n return \"Error deserializing byte buffer into Protobuf Message.\";\n}\n\nconst char* MiniSync::Exceptions::SerializeMsgException::what() const noexcept\n{\n return \"Error serializing Protobuf Message into byte buffer.\";\n}\n" }, { "alpha_fraction": 0.5375536680221558, "alphanum_fraction": 0.5418455004692078, "avg_line_length": 30.066667556762695, "blob_id": "59ed2e933f1826d1529218301998bb42054bab58", "content_id": "f3004646cf8b44dc2ee57ff49879ec57604926a6", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1865, "license_type": "permissive", "max_line_length": 102, "num_lines": 60, "path": "/src/demo/stats.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include \"stats.h\"\n#include <chrono>\n#include <minisync_api.h>\n//#include \"algorithms/constraints.h\"\n#include <fstream>\n#include <loguru.hpp>\n\nvoid MiniSync::Stats::SyncStats::add_sample(long double offset,\n long double offset_error,\n long double drift,\n long double drift_error)\n{\n Sample n_sample;\n n_sample.current_timestamp = std::chrono::duration_cast<us_t>\n (std::chrono::system_clock::now().time_since_epoch()).count();\n n_sample.offset = offset;\n n_sample.offset_error = offset_error;\n n_sample.drift = drift;\n n_sample.drift_error = drift_error;\n\n this->samples.push_back(n_sample);\n}\n\nuint32_t MiniSync::Stats::SyncStats::write_csv(const std::string& path)\n{\n LOG_F(INFO, \"Writing CSV file with synchronization stats.\");\n int i = 0;\n try\n {\n std::ofstream outfile{path, std::ofstream::out};\n // write header\n outfile << \"Sample;Timestamp;Drift;Drift Error;Offset;Offset Error\" << std::endl;\n for (; i < this->samples.size(); i++)\n {\n const Sample& s = this->samples.at(i);\n outfile << i << \";\"\n << s.current_timestamp << \";\"\n << s.drift << \";\" << s.drift_error << \";\"\n << s.offset << \";\" << s.offset_error << std::endl;\n }\n // done\n outfile.close();\n }\n catch (...)\n {\n // in case of any error, (try to) remove the file\n LOG_F(ERROR, \"Writing to file failed!\");\n remove(path.c_str());\n throw;\n }\n\n return i - 1; // number of written records\n}\n" }, { "alpha_fraction": 0.5860806107521057, "alphanum_fraction": 0.5897436141967773, "avg_line_length": 20.84000015258789, "blob_id": "c12a97373e095c0f6cae1de696a58042886a94d6", "content_id": "5f99d9ecb3842ce23ca05d6f0c97b0505958e97d", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 102, "num_lines": 50, "path": "/src/demo/exception.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n* \n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef MINISYNCPP_EXCEPTION_H\n#define MINISYNCPP_EXCEPTION_H\n\n#include <exception>\n\nnamespace MiniSync\n{\n namespace Exceptions\n {\n class TimeoutException : public std::exception\n {\n public:\n const char* what() const noexcept final;\n };\n\n class SocketReadException : public std::exception\n {\n public:\n const char* what() const noexcept final;\n };\n\n class SocketWriteException : public std::exception\n {\n public:\n const char* what() const noexcept final;\n };\n\n class DeserializeMsgException : public std::exception\n {\n public:\n const char* what() const noexcept final;\n };\n\n class SerializeMsgException : public std::exception\n {\n public:\n const char* what() const noexcept final;\n };\n }\n}\n\n\n#endif //MINISYNCPP_EXCEPTION_H\n" }, { "alpha_fraction": 0.6057268977165222, "alphanum_fraction": 0.6309348940849304, "avg_line_length": 36.83333206176758, "blob_id": "5f7ae24d248d967099c8a98991b39cedaff9c256", "content_id": "7306ad3cd7028707756703ca7a6b0afe17b725da", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4088, "license_type": "permissive", "max_line_length": 107, "num_lines": 108, "path": "/src/tests/tests.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n#include <minisync_api.h>\n#include <catch2/catch.hpp>\n#include <sstream>\n#include <thread> // sleep_for\n#include <random>\n\nnamespace Catch\n{\n template<>\n struct StringMaker<MiniSync::us_t>\n {\n static std::string convert(const MiniSync::us_t& value)\n {\n auto ns = std::chrono::duration_cast<std::chrono::duration<long long int, std::nano>>(value);\n auto ms = (ns.count() / 1000) + ((ns.count() % 1000) / 1000.0);\n\n std::ostringstream os;\n os << ms << \" µs\";\n return os.str();\n }\n };\n}\n\nTEST_CASE(\"Basic testing of TinySync and MiniSync\", \"[TinySync, MiniSync]\")\n{\n\n std::shared_ptr<MiniSync::API::Algorithm> algorithm;\n REQUIRE(algorithm == nullptr);\n\n SECTION(\"Set up TinySync\")\n {\n algorithm = MiniSync::API::Factory::createTinySync();\n }\n SECTION(\"Set up MiniSync\")\n {\n algorithm = MiniSync::API::Factory::createMiniSync();\n }\n\n REQUIRE(algorithm != nullptr); // check that the algorithm is not a nullpointer\n REQUIRE(algorithm->getDrift() == Approx(1.0).epsilon(0.001));\n REQUIRE(algorithm->getDriftError() == Approx(0.0).epsilon(0.001));\n REQUIRE(algorithm->getOffset().count() == Approx(MiniSync::us_t{0}.count()).epsilon(0.001));\n REQUIRE(algorithm->getOffsetError().count() == Approx(MiniSync::us_t{0}.count()).epsilon(0.001));\n\n // initial conditions\n MiniSync::us_t To{-1}, Tbr{0}, Tbt{1}, Tr{2};\n\n // initial offset and drift\n // initial coordinates are on x = 0, so max_offset and min_offset should simply be the y coordinates\n auto high_drift = (To - Tr) / (Tbt - Tbr);\n auto low_drift = (Tr - To) / (Tbt - Tbr);\n auto init_drift = (high_drift + low_drift) / 2.0;\n auto init_drift_error = (low_drift - high_drift) / 2.0;\n\n auto init_offset = (To + Tr) / 2.0;\n auto init_offset_error = (Tr - To) / 2.0;\n\n algorithm->addDataPoint(To, Tbr, Tr);\n // just adding one point does not trigger an update\n REQUIRE(algorithm->getDrift() == Approx(1.0).epsilon(0.001));\n REQUIRE(algorithm->getDriftError() == Approx(0.0).epsilon(0.001));\n REQUIRE(algorithm->getOffset().count() == Approx(MiniSync::us_t{0}.count()).epsilon(0.001));\n REQUIRE(algorithm->getOffsetError().count() == Approx(MiniSync::us_t{0}.count()).epsilon(0.001));\n\n algorithm->addDataPoint(To, Tbt, Tr);\n // now algorithm should recalculate\n REQUIRE(algorithm->getDrift() == Approx(init_drift).epsilon(0.001));\n REQUIRE(algorithm->getDriftError() == Approx(init_drift_error).epsilon(0.001));\n REQUIRE(algorithm->getOffset().count() == Approx(init_offset.count()).epsilon(0.001));\n REQUIRE(algorithm->getOffsetError().count() == Approx(init_offset_error.count()).epsilon(0.001));\n}\n\nTEST_CASE(\"Side by side tests\", \"[timing]\")\n{\n auto tiny = MiniSync::API::Factory::createTinySync();\n auto mini = MiniSync::API::Factory::createMiniSync();\n\n auto T0 = std::chrono::steady_clock::now();\n using clock = std::chrono::steady_clock;\n\n // we'll use some random delays, that way we get some variability in the inputs to the algorithms\n std::default_random_engine gen;\n std::uniform_int_distribution<uint32_t> dist(0, 10);\n\n // run algorithms in a loop. MiniSync should always give an equal OR better result compared to TinySync\n for (int i = 0; i < 50; ++i)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds{dist(gen)});\n \n auto To = clock::now() - T0;\n std::this_thread::sleep_for(std::chrono::milliseconds{dist(gen)});\n auto Tb = clock::now() - T0;\n std::this_thread::sleep_for(std::chrono::milliseconds{dist(gen)});\n auto Tr = clock::now() - T0;\n\n tiny->addDataPoint(To, Tb, Tr);\n mini->addDataPoint(To, Tb, Tr);\n\n REQUIRE(mini->getOffsetError() <= tiny->getOffsetError());\n REQUIRE(mini->getDriftError() <= tiny->getDriftError());\n }\n}\n" }, { "alpha_fraction": 0.5317394733428955, "alphanum_fraction": 0.5490519404411316, "avg_line_length": 22.326923370361328, "blob_id": "f03eba09aa1d53956dcb0cc8b012ab288a42c38a", "content_id": "baad6b2ed399783611de054d085d7a476a70d9e1", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1214, "license_type": "permissive", "max_line_length": 102, "num_lines": 52, "path": "/src/demo/stats.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n* \n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef MINISYNCPP_STATS_H\n#define MINISYNCPP_STATS_H\n\n#include <cinttypes>\n#include <vector>\n#include <string>\n\nnamespace MiniSync\n{\n namespace Stats\n {\n typedef struct Sample\n {\n long double current_timestamp = 0;\n long double offset = 0;\n long double offset_error = 0;\n long double drift = 0;\n long double drift_error = 0;\n } Sample;\n\n class SyncStats\n {\n private:\n static const uint32_t INIT_VEC_SIZE = 100000;\n std::vector<Sample> samples;\n\n public:\n explicit SyncStats(uint32_t init_capacity = INIT_VEC_SIZE) : samples{init_capacity}\n {};\n\n ~SyncStats() = default;\n\n void add_sample(long double offset,\n long double offset_error,\n long double drift,\n long double drift_error);\n\n uint32_t write_csv(const std::string& path);\n\n\n };\n }\n}\n\n#endif //MINISYNCPP_STATS_H\n" }, { "alpha_fraction": 0.6559560894966125, "alphanum_fraction": 0.6617032289505005, "avg_line_length": 25.58333396911621, "blob_id": "5c1921dc6524bb821d1108fa6fd3a73c0fb758a9", "content_id": "409f015edc4b231d30e4028d554edd52129af7c4", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3829, "license_type": "permissive", "max_line_length": 102, "num_lines": 144, "path": "/src/python_bindings/pyminisyncpp_gen.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef LIBMINISYNCPP_PYMINISYNCPP_GEN_CPP\n#define LIBMINISYNCPP_PYMINISYNCPP_GEN_CPP\n\n#include <pybind11/pybind11.h>\n#include <minisync_api.h>\n\nclass Algorithm\n{\nprotected:\n std::shared_ptr<MiniSync::API::Algorithm> algo;\n\npublic:\n virtual ~Algorithm() = default;\n\n virtual void addDataPoint(long double To, long double Tb, long double Tr)\n {\n algo->addDataPoint(\n MiniSync::us_t{To},\n MiniSync::us_t{Tb},\n MiniSync::us_t{Tr});\n }\n\n virtual long double getDrift()\n {\n return algo->getDrift();\n }\n\n virtual long double getDriftError()\n {\n return algo->getDriftError();\n }\n\n virtual long double getOffset()\n {\n return algo->getOffset().count();\n }\n\n virtual long double getOffsetError()\n {\n return algo->getOffsetError().count();\n }\n};\n\nclass MiniSyncAlgorithm : public Algorithm\n{\npublic:\n MiniSyncAlgorithm() : Algorithm()\n {\n this->algo = std::move(MiniSync::API::Factory::createMiniSync());\n }\n\n ~MiniSyncAlgorithm() override = default;\n};\n\nclass TinySyncAlgorithm : public Algorithm\n{\npublic:\n TinySyncAlgorithm() : Algorithm()\n {\n this->algo = std::move(MiniSync::API::Factory::createTinySync());\n }\n\n ~TinySyncAlgorithm() override = default;\n};\n\n// Trampoline class template\ntemplate<class AlgorithmBase = Algorithm>\nclass PyAlgorithm : public AlgorithmBase\n{\npublic:\n using AlgorithmBase::AlgorithmBase; //inherit constructors\n void addDataPoint(long double To, long double Tb, long double Tr) override\n {\n PYBIND11_OVERLOAD(void, AlgorithmBase, addDataPoint, To, Tb, Tr);\n }\n\n long double getDrift() override\n {\n PYBIND11_OVERLOAD(long double, AlgorithmBase, getDrift,);\n }\n\n long double getDriftError() override\n {\n PYBIND11_OVERLOAD(long double, AlgorithmBase, getDriftError,);\n }\n\n long double getOffset() override\n {\n PYBIND11_OVERLOAD(long double, AlgorithmBase, getOffset,);\n }\n\n long double getOffsetError() override\n {\n PYBIND11_OVERLOAD(long double, AlgorithmBase, getOffsetError,);\n }\n\n};\n\n// Python bindings:\nnamespace py = pybind11;\nPYBIND11_MODULE(pyminisyncpp, m)\n{\n // documentation\n m.doc() = \"PyMiniSynCPP: Python bindings for the libminisyncpp C++ library.\\n\";\n\n py::class_<Algorithm, PyAlgorithm<>> pyAlgo(m, \"Algorithm\");\n py::class_<TinySyncAlgorithm, PyAlgorithm<TinySyncAlgorithm>> pyTiny(m, \"TinySyncAlgorithm\");\n py::class_<MiniSyncAlgorithm, PyAlgorithm<MiniSyncAlgorithm>> pyMini(m, \"MiniSyncAlgorithm\");\n\n // method definitions\n pyAlgo\n .def(py::init())\n .def(\"addDataPoint\", &Algorithm::addDataPoint)\n .def(\"getOffset\", &Algorithm::getOffset)\n .def(\"getOffsetError\", &Algorithm::getOffsetError)\n .def(\"getDrift\", &Algorithm::getDrift)\n .def(\"getDriftError\", &Algorithm::getDriftError);\n\n pyTiny\n .def(py::init())\n .def(\"addDataPoint\", &TinySyncAlgorithm::addDataPoint)\n .def(\"getOffset\", &TinySyncAlgorithm::getOffset)\n .def(\"getOffsetError\", &TinySyncAlgorithm::getOffsetError)\n .def(\"getDrift\", &TinySyncAlgorithm::getDrift)\n .def(\"getDriftError\", &TinySyncAlgorithm::getDriftError);\n\n pyMini\n .def(py::init())\n .def(\"addDataPoint\", &MiniSyncAlgorithm::addDataPoint)\n .def(\"getOffset\", &MiniSyncAlgorithm::getOffset)\n .def(\"getOffsetError\", &MiniSyncAlgorithm::getOffsetError)\n .def(\"getDrift\", &MiniSyncAlgorithm::getDrift)\n .def(\"getDriftError\", &MiniSyncAlgorithm::getDriftError);\n}\n\n\n#endif //LIBMINISYNCPP_PYMINISYNCPP_GEN_CPP\n" }, { "alpha_fraction": 0.5447824001312256, "alphanum_fraction": 0.5476693511009216, "avg_line_length": 31.350797653198242, "blob_id": "d2bff4ae694e69ac801f29023170b6f71b2ce0ec", "content_id": "d4f4c802a0be5ed237f904d760904de676e0ce2e", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14203, "license_type": "permissive", "max_line_length": 119, "num_lines": 439, "path": "/src/libminisyncpp/minisync.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include <cstdlib>\n#include <algorithm>\n\n#ifdef LIBMINISYNCPP_LOGURU_ENABLE\n\n#include <loguru.hpp>\n\n#endif\n\n#include \"minisync.h\"\n\n/*\n * Get the current relative drift of the clock.\n */\nlong double MiniSync::Algorithms::Base::getDrift()\n{\n return this->currentDrift.value;\n}\n\n/*\n * Get the current (one-sided) error of the relative clock drift.\n */\nlong double MiniSync::Algorithms::Base::getDriftError()\n{\n return this->currentDrift.error;\n}\n\n/*\n * Get the current relative offset of the clock.\n */\nMiniSync::us_t MiniSync::Algorithms::Base::getOffset()\n{\n return this->currentOffset.value;\n}\n\n/*\n * Get the current (one-sided) error of the relative clock offset.\n */\nMiniSync::us_t MiniSync::Algorithms::Base::getOffsetError()\n{\n return this->currentOffset.error;\n}\n\n/*\n * Get the current time as a std::chrono::time_point, adjusted using the current relative offset and drift.\n */\nstd::chrono::time_point<std::chrono::system_clock, MiniSync::us_t> MiniSync::Algorithms::Base::getCurrentAdjustedTime()\n{\n auto t_now = std::chrono::system_clock::now().time_since_epoch();\n return std::chrono::time_point<std::chrono::system_clock, us_t>{\n this->currentDrift.value * t_now +\n this->currentOffset.value\n };\n}\n\n/*\n * Adds a data point to the algorithm and recalculates the drift and offset estimates.\n */\nvoid MiniSync::Algorithms::Base::addDataPoint(us_t To, us_t Tb, us_t Tr)\n{\n // add points to internal storage\n //this->low_points.insert(std::make_shared<LowPoint>(Tb, To));\n // this->high_points.insert(std::make_shared<HighPoint>(Tb, Tr));\n\n this->addLowPoint(Tb, To);\n this->addHighPoint(Tb, Tr);\n ++this->processed_timestamps;\n\n if (processed_timestamps > 1)\n {\n // n_th sample, n >= 1\n // pass it on to the specific algorithm\n // TODO: extract this call from this method?\n this->__recalculateEstimates();\n }\n}\n\nMiniSync::Algorithms::Base::Base() :\n processed_timestamps(0),\n diff_factor(std::numeric_limits<long double>::max())\n{\n}\n\n/*\n * Update estimate based on the constraints we have stored.\n *\n * Considering\n *\n * constraint1 = {tol, tbl, trl}\n * constraint2 = {tor, tbr, trr}\n *\n * We have four points to build two linear equations:\n * {tbl, tol} -> {tbr, trr}: (A_upper, B_lower)\n * {tbl, trl} -> {tbr, tor}: (A_lower, B_upper)\n *\n * Where\n * A_upper = (trr - tol)/(tbr - tbl)\n * A_lower = (tor - trl)/(tbr - tbl)\n * B_upper = trl - A_lower * tbl\n * B_lower = tol - A_upper * tbl\n *\n * Using these bounds, we can estimate the Drift and Offset as\n *\n * Drift = (A_upper + A_lower)/2\n * Offset = (B_upper + B_lower)/2\n * Drift_Error = (A_upper - A_lower)/2\n * Offset_Error = (B_upper - B_lower)/2\n */\nvoid MiniSync::Algorithms::Base::__recalculateEstimates()\n{\n // assume timestamps come in time order\n //\n // find the tightest bound\n // only need to compare the lines\n // l1 -> h2 (already have)\n // l2 -> h1 (already have)\n // l1 -> n_h\n // l2 -> n_h\n // n_l -> h1\n // n_l -> h2\n //\n // find minimum (a_upper - a_lower)(b_upper - b_lower)\n\n // lower lines (a_upper * x + b_lower)\n\n us_t tmp_diff;\n for (const auto& iter_low: this->low_constraints)\n {\n for (const auto& iter_high: this->high_constraints)\n {\n ConstraintPtr tmp_low = iter_low.second;\n ConstraintPtr tmp_high = iter_high.second;\n\n tmp_diff = (tmp_low->getA() - tmp_high->getA()) * (tmp_high->getB() - tmp_low->getB());\n if (tmp_diff < this->diff_factor)\n {\n this->diff_factor = tmp_diff;\n\n this->current_low = tmp_low;\n this->low_constraint_pts = iter_low.first;\n\n this->current_high = tmp_high;\n this->high_constraint_pts = iter_high.first;\n }\n }\n }\n\n this->cleanup();\n\n#ifdef LIBMINISYNCPP_LOGURU_ENABLE\n CHECK_NE_F(current_low.get(), nullptr, \"current_low is null!\");\n CHECK_NE_F(current_high.get(), nullptr, \"current_high is null!\");\n#else\n if (current_low.get() == nullptr)\n throw std::runtime_error(\"current_low is null!\");\n if (current_high.get() == nullptr)\n throw std::runtime_error(\"current_high is null!\");\n#endif\n\n this->currentDrift.value = (current_low->getA() + current_high->getA()) / 2;\n this->currentOffset.value = (current_low->getB() + current_high->getB()) / 2;\n this->currentDrift.error = (current_low->getA() - current_high->getA()) / 2;\n this->currentOffset.error = (current_high->getB() - current_low->getB()) / 2;\n\n#ifdef LIBMINISYNCPP_LOGURU_ENABLE\n CHECK_GE_F(this->currentDrift.value,\n 0,\n \"Drift must be >=0 for monotonically increasing clocks... (actual value: %Lf)\",\n this->currentDrift.value);\n#else\n if (this->currentDrift.value <= 0)\n throw std::runtime_error(\"Drift must be >=0 for monotonically increasing clocks...\");\n#endif\n}\n\nMiniSync::LPointPtr MiniSync::Algorithms::MiniSync::addLowPoint(us_t Tb, us_t To)\n{\n auto lp = Base::addLowPoint(Tb, To);\n // calculate the slopes for the minisync algo\n std::pair<LPointPtr, LPointPtr> pair;\n long double M;\n for (LPointPtr olp: this->low_points)\n {\n if (lp->getX() == olp->getX()) continue; //avoid division by 0...\n\n // hp is always the newest pointer, put it as the second element of the pair always\n pair = std::make_pair(olp, lp);\n M = (lp->getY() - olp->getY()) / (lp->getX() - olp->getX());\n low_slopes.emplace(pair, M);\n }\n\n return lp;\n}\n\nMiniSync::HPointPtr MiniSync::Algorithms::MiniSync::addHighPoint(us_t Tb, us_t Tr)\n{\n auto hp = Base::addHighPoint(Tb, Tr);\n // calculate the slopes for the minisync algo\n std::pair<HPointPtr, HPointPtr> pair;\n long double M;\n for (HPointPtr ohp: this->high_points)\n {\n if (hp->getX() == ohp->getX()) continue; //avoid division by 0...\n\n // hp is always the newest pointer, put it as the second element of the pair always\n pair = std::make_pair(ohp, hp);\n M = (hp->getY() - ohp->getY()) / (hp->getX() - ohp->getX());\n high_slopes.emplace(pair, M);\n }\n\n return hp;\n}\n\nMiniSync::LPointPtr MiniSync::Algorithms::Base::addLowPoint(us_t Tb, us_t To)\n{\n auto lp = std::make_shared<LowPoint>(Tb, To);\n std::pair<LPointPtr, HPointPtr> pair;\n\n // calculate new constraints\n for (HPointPtr hp: this->high_points)\n {\n this->addConstraint(lp, hp);\n }\n\n this->low_points.insert(lp);\n return lp; // return a copy of the created pointer.\n}\n\nMiniSync::HPointPtr MiniSync::Algorithms::Base::addHighPoint(us_t Tb, us_t Tr)\n{\n auto hp = std::make_shared<HighPoint>(Tb, Tr);\n\n // calculate new constraints\n for (LPointPtr lp: this->low_points)\n {\n this->addConstraint(lp, hp);\n }\n\n this->high_points.insert(hp);\n return hp; // return a copy of the created pointer.\n}\n\n/*\n * Helper instance method to add a constraint linear equation given a lower-bound and an upper-bound point.\n */\nbool MiniSync::Algorithms::Base::addConstraint(LPointPtr lp, HPointPtr hp)\n{\n auto pair = std::make_pair(lp, hp);\n\n if (lp->getX() == hp->getX()) return false;\n else if (lp->getX() < hp->getX() && this->low_constraints.count(pair) == 0)\n {\n this->low_constraints.emplace(pair, std::make_shared<ConstraintLine>(*lp, *hp));\n return true;\n }\n else if (lp->getX() > hp->getX() && this->high_constraints.count(pair) == 0)\n {\n this->high_constraints.emplace(pair, std::make_shared<ConstraintLine>(*lp, *hp));\n return true;\n }\n\n return false;\n}\n\n/*\n * Removes un-used data points from the algorithm internal storage.\n */\nvoid MiniSync::Algorithms::TinySync::cleanup()\n{\n // cleanup\n for (auto iter = low_points.begin(); iter != low_points.end();)\n {\n if (low_constraint_pts.first != *iter && high_constraint_pts.first != *iter)\n iter = low_points.erase(iter);\n else\n ++iter;\n }\n\n for (auto iter = high_points.begin(); iter != high_points.end();)\n {\n if (low_constraint_pts.second != *iter && high_constraint_pts.second != *iter)\n iter = high_points.erase(iter);\n else\n ++iter;\n }\n\n auto tmp_low_cons = std::move(this->low_constraints);\n auto tmp_high_cons = std::move(this->high_constraints);\n for (auto h_point: high_points)\n {\n for (auto l_point: low_points)\n {\n auto pair = std::make_pair(l_point, h_point);\n if (tmp_low_cons.count(pair) > 0)\n this->low_constraints[pair] = tmp_low_cons.at(pair);\n else if (tmp_high_cons.count(pair) > 0)\n this->high_constraints[pair] = tmp_high_cons.at(pair);\n }\n }\n}\n\n/*\n * Removes un-used data points from the algorithm internal storage.\n */\nvoid MiniSync::Algorithms::MiniSync::cleanup()\n{\n // cleanup\n for (auto iter_j = low_points.begin(); iter_j != low_points.end();)\n {\n if (low_constraint_pts.first != *iter_j && high_constraint_pts.first != *iter_j)\n {\n // low point is not one of the current constraint low points\n // now we compare the slopes with each other point to see if we store it for future use or not\n // if current point is Aj, compare each M(Ai, Aj) with M(Aj, Ak)\n // store point Aj only iff there exists\n // M(Ai, Aj) > M(Aj, Ak) for 0 <= i < j < k <= total number of points.\n bool store = false;\n for (auto iter_i = low_points.begin(); iter_i != iter_j; ++iter_i)\n {\n for (auto iter_k = std::next(iter_j, 1); iter_k != low_points.end(); ++iter_k)\n {\n if (low_slopes.at(std::make_pair(*iter_i, *iter_j))\n > low_slopes.at(std::make_pair(*iter_j, *iter_k)))\n {\n store = true;\n break;\n }\n }\n\n if (store) break;\n }\n\n if (!store)\n {\n // delete all associated slopes then delete the point\n for (auto iter_slope = low_slopes.begin(); iter_slope != low_slopes.end();)\n {\n if (iter_slope->first.first == *iter_j || iter_slope->first.second == *iter_j)\n iter_slope = low_slopes.erase(iter_slope);\n else ++iter_slope;\n }\n iter_j = low_points.erase(iter_j);\n }\n else\n ++iter_j;\n }\n else\n ++iter_j;\n }\n\n // done same thing for high points\n for (auto iter_j = high_points.begin(); iter_j != high_points.end();)\n {\n if (low_constraint_pts.second != *iter_j && high_constraint_pts.second != *iter_j)\n {\n // high point is not one of the current constraint high points\n // now we compare the slopes with each other point to see if we store it for future use or not\n // if current point is Aj, compare each M(Ai, Aj) with M(Aj, Ak)\n // store point Aj only iff there exists\n // M(Ai, Aj) < M(Aj, Ak) for 0 <= i < j < k <= total number of points. This is the inverse condition as\n // the low points.\n bool store = false;\n for (auto iter_i = high_points.begin(); iter_i != iter_j; ++iter_i)\n {\n for (auto iter_k = std::next(iter_j, 1); iter_k != high_points.end(); ++iter_k)\n {\n try\n {\n if (high_slopes.at(std::make_pair(*iter_i, *iter_j))\n < high_slopes.at(std::make_pair(*iter_j, *iter_k)))\n {\n store = true;\n break;\n }\n }\n catch (std::out_of_range& e)\n {\n#ifdef LOGURU_ENABLE\n DLOG_F(WARNING, \"iter_i: (%Lf, %Lf)\",\n iter_i->get()->getX().count(),\n iter_i->get()->getY().count());\n DLOG_F(WARNING, \"iter_j: (%Lf, %Lf)\",\n iter_j->get()->getX().count(),\n iter_j->get()->getY().count());\n DLOG_F(WARNING, \"iter_k: (%Lf, %Lf)\",\n iter_k->get()->getX().count(),\n iter_k->get()->getY().count());\n#endif\n throw;\n }\n }\n\n if (store) break;\n }\n\n if (!store)\n {\n // delete all associated slopes then delete the point\n for (auto iter_slope = high_slopes.begin(); iter_slope != high_slopes.end();)\n {\n if (iter_slope->first.first == *iter_j || iter_slope->first.second == *iter_j)\n iter_slope = high_slopes.erase(iter_slope);\n else ++iter_slope;\n }\n iter_j = high_points.erase(iter_j);\n }\n else\n ++iter_j;\n }\n else\n ++iter_j;\n }\n\n auto tmp_low_cons = std::move(this->low_constraints);\n auto tmp_high_cons = std::move(this->high_constraints);\n for (auto h_point: high_points)\n {\n for (auto l_point: low_points)\n {\n auto pair = std::make_pair(l_point, h_point);\n if (tmp_low_cons.count(pair) > 0)\n this->low_constraints.emplace(pair, tmp_low_cons.at(pair));\n else if (tmp_high_cons.count(pair) > 0)\n this->high_constraints.emplace(pair, tmp_high_cons.at(pair));\n }\n }\n}\n\nsize_t std::hash<MiniSync::Point>::operator()(const MiniSync::Point& point) const\n{\n return std::hash<long double>()(point.getX().count() + point.getY().count());\n}\n" }, { "alpha_fraction": 0.5791352391242981, "alphanum_fraction": 0.5946053266525269, "avg_line_length": 24.98969078063965, "blob_id": "b1d61a300913f64369adeb03ac7dc9f65f2eb7d6", "content_id": "9c7f0f034c8af11c464562cca3cbbba521f46a46", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2522, "license_type": "permissive", "max_line_length": 102, "num_lines": 97, "path": "/src/demo/node.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef MINISYNCPP_NODE_H\n#define MINISYNCPP_NODE_H\n\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <string>\n#include <minisync_api.h>\n#include <protocol.pb.h>\n#include <cinttypes>\n#include \"stats.h\"\n//#include \"algorithms/constraints.h\"\n\nnamespace MiniSync\n{\n typedef struct sockaddr_in SOCKADDR;\n\n // Maximum message length corresponds to the maximum UDP datagram size.\n static const size_t MAX_MSG_LEN = 65507;\n\n class Node\n {\n protected:\n std::chrono::steady_clock::time_point start; // TODO: timestamp\n\n int sock_fd;\n uint16_t bind_port;\n SOCKADDR local_addr;\n const MiniSync::Protocol::NodeMode mode;\n std::atomic_bool running;\n\n struct\n {\n us_t beacon{0};\n us_t beacon_reply{0};\n } minimum_delays;\n\n Node(uint16_t bind_port, MiniSync::Protocol::NodeMode mode);\n\n us_t send_message(MiniSync::Protocol::MiniSyncMsg& msg, const sockaddr* dest);\n us_t recv_message(MiniSync::Protocol::MiniSyncMsg& msg, struct sockaddr* reply_to);\n public:\n virtual void run() = 0;\n virtual void shut_down();\n virtual ~Node();\n };\n\n class ReferenceNode : public Node\n {\n public:\n explicit ReferenceNode(uint16_t bind_port);\n ~ReferenceNode() override = default;\n\n void run() final;\n\n private:\n void serve();\n void wait_for_handshake();\n };\n\n class SyncNode : public Node\n {\n private:\n const std::string& peer;\n const uint16_t peer_port;\n SOCKADDR peer_addr;\n const std::string stat_file_path;\n std::shared_ptr<MiniSync::API::Algorithm> algo;\n MiniSync::Stats::SyncStats stats;\n void handshake();\n void sync();\n double bw_bytes_per_usecond;\n us_t min_ping_oneway_us;\n\n public:\n static const uint32_t RD_TIMEOUT_USEC = 100000; // 100 ms\n\n SyncNode(uint16_t bind_port,\n std::string& peer,\n uint16_t peer_port,\n std::shared_ptr<MiniSync::API::Algorithm>&& sync_algo,\n std::string stat_file_path = \"\",\n double bandwidth_mbps = -1.0,\n double min_ping_rtt_ms = -1.0);\n ~SyncNode() override; // = default;\n\n void run() final;\n };\n}\n\n#endif //MINISYNCPP_NODE_H\n" }, { "alpha_fraction": 0.6830812692642212, "alphanum_fraction": 0.7003165483474731, "avg_line_length": 33.67073059082031, "blob_id": "e03bf517651fb014c8eee71794bbfaf5957dabb3", "content_id": "507ec1db3d462dc67c57ff526a102075e92bd7b0", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2843, "license_type": "permissive", "max_line_length": 85, "num_lines": 82, "path": "/docker_build.sh", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nprintf \"Building libminisyncpp in a Docker container...\\n\"\n\nDOCKER_IMG=\"minisync_build:v2.5.5\"\n\nprintf \"Checking if build image exists in registry: \"\nif [[ \"$(docker images -q ${DOCKER_IMG} 2> /dev/null)\" == \"\" ]]; then\n # check if image exists. If it doesn't, build it.\n printf \"not found.\\n\"\n printf \"Building required Docker image:\\n\"\n docker build --tag=${DOCKER_IMG} . -f-<<EOF\nFROM ubuntu:18.10\nLABEL maintainer=\"Manuel Olguín <[email protected]>\"\n\n# install requirements\nCOPY ./sources.list /etc/apt/sources.list\nRUN apt-get update\nRUN apt-get upgrade -y\nRUN apt-get install -y wget git curl tar\n\n# first get the Raspberry Pi cross-compilers\n# done in this order because it speeds up future image builds\nCOPY ./install_raspi_xcompiler.sh /tmp/\nRUN /tmp/install_raspi_xcompiler.sh\n\n# install build deps\nRUN apt-get install -y build-essential cmake gcc g++ clang \\\n python3-all python3-all-dev libpython3-all-dev python3-setuptools\nRUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1\nRUN update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2\nRUN update-alternatives --set python /usr/bin/python3.7\nEOF\n\nelse\n printf \"found.\\n\"\nfi\n\nLINUX_BUILD_DIR=\"build_x86_64\";\nRASPI_BUILD_DIR=\"build_ARMv7\";\nRASPI_ENV_PATH=\"/opt/raspi_gcc.env\";\nRASPI_GCC_EXEC=\"\\$RASPI_GCC_PATH/bin/arm-linux-gnueabihf-gcc\";\nRASPI_GXX_EXEC=\"\\$RASPI_GCC_PATH/bin/arm-linux-gnueabihf-g++\";\nRASPI_LD_LIB_PATH=\"\\$RASPI_GCC_PATH/lib:\\$LD_LIBRARY_PATH\";\nCOMMON_CMAKE_FLAGS=\"-DCMAKE_BUILD_TYPE=Release \\\n-UCMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES \\\n-UCMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES \\\n-DLIBMINISYNCPP_BUILD_DEMO=TRUE \\\n-DLIBMINISYNCPP_BUILD_TESTS=TRUE \\\n-DLIBMINISYNCPP_ENABLE_LOGURU=TRUE \\\n\"\n\n# use the docker image to build both for Linux and for Raspberry Pi\nprintf \"Building MiniSynCPP x86_64...\\n\";\ndocker run --name=build_x86_64 --rm -v ${PWD}:/mnt/build ${DOCKER_IMG} /bin/bash -c \\\n\"\\\ncd /mnt/build;\\\nmkdir -p ${LINUX_BUILD_DIR};\\\ncd ${LINUX_BUILD_DIR};\\\ncmake ${COMMON_CMAKE_FLAGS} -DLIBMINISYNCPP_WITH_PYTHON=TRUE .. &&\\\ncmake --build . --target clean -- -j 4;\\\ncmake --build . --target all -- -j 4;\\\n./tests/minisyncpp;\\\ncd ..; chmod 0777 ${LINUX_BUILD_DIR};\\\n\";\n\nprintf \"Building MiniSynCPP ARMv7...\\n\";\ndocker run --name=build_ARMv7 --rm -v ${PWD}:/mnt/build ${DOCKER_IMG} /bin/bash -c \\\n\"\\\nsource ${RASPI_ENV_PATH};\\\ncd /mnt/build;\\\nmkdir -p ${RASPI_BUILD_DIR};\\\ncd ${RASPI_BUILD_DIR};\\\nLD_LIBRARY_PATH='${RASPI_LD_LIB_PATH}' cmake -DCMAKE_C_COMPILER=${RASPI_GCC_EXEC} \\\n-DCMAKE_CXX_COMPILER=${RASPI_GXX_EXEC} \\\n-DCMAKE_CXX_FLAGS='-march=armv7-a -mfloat-abi=hard -mfpu=neon-vfpv4' \\\n${COMMON_CMAKE_FLAGS} .. &&\\\ncmake --build . --target clean -- -j 4;\\\nLD_LIBRARY_PATH='${RASPI_LD_LIB_PATH}' cmake --build . --target all -- -j 4;\\\ncd ..; chmod 0777 ${RASPI_BUILD_DIR};\\\n\";\nprintf \"Done.\\n\";\n" }, { "alpha_fraction": 0.568656325340271, "alphanum_fraction": 0.5718496441841125, "avg_line_length": 29.380596160888672, "blob_id": "abfc2fb1fa4187fb43974830931ab857679e23fa", "content_id": "7d8aeaa1a36ee548bcfa60c84194f95fae3bee4d", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4073, "license_type": "permissive", "max_line_length": 108, "num_lines": 134, "path": "/src/libminisyncpp/minisync.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#ifndef TINYSYNC___MINISYNC_H\n#define TINYSYNC___MINISYNC_H\n\n#include <tuple>\n#include <exception>\n#include <unordered_map>\n#include <set>\n#include <memory>\n#include \"constraints.h\"\n#include \"minisync_api.h\"\n\nnamespace MiniSync\n{\n using LPointPtr = std::shared_ptr<LowPoint>;\n using HPointPtr = std::shared_ptr<HighPoint>;\n using ConstraintPtr = std::shared_ptr<ConstraintLine>;\n\n // some hash specializations we'll need\n struct ppair_hash\n {\n std::size_t operator()(const std::pair<std::shared_ptr<Point>, std::shared_ptr<Point>>& pair) const\n {\n return std::hash<MiniSync::Point>()(*pair.first) ^ std::hash<MiniSync::Point>()(*pair.second);\n }\n };\n\n // some comparison operations for sets of pointers to Points\n struct lppoint_compare\n {\n bool operator()(const LPointPtr& lhs, const LPointPtr& rhs)\n {\n return *lhs < *rhs;\n }\n };\n\n struct hppoint_compare\n {\n bool operator()(const HPointPtr& lhs, const HPointPtr& rhs)\n {\n return *lhs < *rhs;\n }\n };\n\n namespace Algorithms\n {\n class Base : public MiniSync::API::Algorithm\n {\n protected:\n // constraints\n std::unordered_map<std::pair<LPointPtr, HPointPtr>, ConstraintPtr, ppair_hash> low_constraints;\n std::unordered_map<std::pair<LPointPtr, HPointPtr>, ConstraintPtr, ppair_hash> high_constraints;\n std::set<LPointPtr, lppoint_compare> low_points;\n std::set<HPointPtr, hppoint_compare> high_points;\n\n ConstraintPtr current_high;\n ConstraintPtr current_low;\n std::pair<LPointPtr, HPointPtr> high_constraint_pts;\n std::pair<LPointPtr, HPointPtr> low_constraint_pts;\n\n struct\n {\n long double value = 1.0;\n long double error = 0.0;\n } currentDrift; // relative drift of the clock\n\n struct\n {\n us_t value{0};\n us_t error{0};\n } currentOffset; // current offset in µseconds\n\n us_t diff_factor; // difference between current lines\n uint32_t processed_timestamps;\n\n Base();\n\n void __recalculateEstimates();\n\n /*\n * Subclasses need to override this function with their own cleanup method.\n */\n\n virtual void cleanup() = 0;\n\n /*\n * Helper instance method to add a lower-bound point to the algorithm.\n */\n virtual LPointPtr addLowPoint(us_t Tb, us_t To);\n\n /*\n * Helper instance method to add a higher-bound point to the algorithm.\n */\n virtual HPointPtr addHighPoint(us_t Tb, us_t Tr);\n virtual bool addConstraint(LPointPtr lp, HPointPtr hp);\n public:\n void addDataPoint(us_t To, us_t Tb, us_t Tr) final;\n long double getDrift() final;\n long double getDriftError() final;\n us_t getOffset() final;\n us_t getOffsetError() final;\n std::chrono::time_point<std::chrono::system_clock, us_t> getCurrentAdjustedTime() final;\n };\n\n class TinySync : public Base\n {\n public:\n TinySync() = default;\n private:\n void cleanup() final;\n };\n\n class MiniSync : public Base\n {\n public:\n MiniSync() = default;\n private:\n std::unordered_map<std::pair<LPointPtr, LPointPtr>, long double, ppair_hash> low_slopes;\n std::unordered_map<std::pair<HPointPtr, HPointPtr>, long double, ppair_hash> high_slopes;\n void cleanup() final;\n LPointPtr addLowPoint(us_t Tb, us_t To) final;\n HPointPtr addHighPoint(us_t Tb, us_t Tr) final;\n };\n }\n}\n\n\n#endif //TINYSYNC___MINISYNC_H\n" }, { "alpha_fraction": 0.6420361399650574, "alphanum_fraction": 0.6559934616088867, "avg_line_length": 27.325580596923828, "blob_id": "1140eda90f4e323e649c025e25a6746ae1adb7b3", "content_id": "f95b13a8423ae1611c10a77cb0e3459e42f6670c", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1219, "license_type": "permissive", "max_line_length": 111, "num_lines": 43, "path": "/src/libminisyncpp/constraints.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include <algorithm>\n#include <cstdlib>\n\n#ifdef LIBMINISYNCPP_LOGURU_ENABLE\n\n#include <loguru.hpp>\n#endif\n\n#include \"constraints.h\"\n#include \"minisync.h\"\n\nbool MiniSync::Point::operator==(const Point& o) const\n{\n return this->x == o.x && this->y == o.y;\n}\n\nMiniSync::ConstraintLine::ConstraintLine(const LowPoint& p1, const HighPoint& p2) : B({})\n{\n#ifdef LIBMINISYNCPP_LOGURU_ENABLE\n CHECK_NE_F(p1.getX(), p2.getX(), \"Points in a constraint line cannot have the same REF timestamp!\");\n#else\n if (p1.getX() == p2.getX())\n throw std::runtime_error(\"Points in a constraint line cannot have the same REF timestamp!\");\n#endif\n\n this->A = (p2.getY() - p1.getY()).count() / (p2.getX() - p1.getX()).count();\n\n // slope can't be negative\n // CHECK_GT_F(this->A, 0, \"Slope can't be negative!\"); // it actually can, at least for the constrain lines\n this->B = us_t{p1.getY() - (this->A * p1.getX())};\n}\n\nbool MiniSync::ConstraintLine::operator==(const ConstraintLine& o) const\n{\n return this->A == o.getA() && this->B == o.getB();\n}\n" }, { "alpha_fraction": 0.7197452187538147, "alphanum_fraction": 0.7388535141944885, "avg_line_length": 27.454545974731445, "blob_id": "f05c53e5c7e7a395a799b6c396f86a8f906b4cab", "content_id": "856d2b309047dd32435de7519f9d91c54003d00a", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 315, "license_type": "permissive", "max_line_length": 102, "num_lines": 11, "path": "/src/tests/tests_main.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n// Only include the following lines in this file, to avoid recompiling Catch2 at every build.\n#define CATCH_CONFIG_MAIN\n\n#include <catch2/catch.hpp>\n\n" }, { "alpha_fraction": 0.5980176329612732, "alphanum_fraction": 0.6049008965492249, "avg_line_length": 34.59803771972656, "blob_id": "576fdaa86d9df13c56a30570a238f602c2b180e7", "content_id": "97c058ff903a645804875709354beeb412855116", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3633, "license_type": "permissive", "max_line_length": 115, "num_lines": 102, "path": "/src/demo/main.cpp", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n\n#include <iostream>\n#include <memory>\n#include <demo_config.h>\n#include <loguru.hpp>\n#include <CLI/CLI.hpp>\n#include \"node.h\"\n#include \"exception.h\"\n\nMiniSync::Node* node = nullptr;\n\nvoid sig_handler(int)\n{\n if (node != nullptr)\n node->shut_down();\n else exit(0);\n}\n\nint main(int argc, char* argv[])\n{\n loguru::g_stderr_verbosity = loguru::Verbosity_ERROR; // set default verbosity to ERROR or FATAL\n loguru::init(argc, argv); // parse -v flags\n\n signal(SIGINT, sig_handler); // override logurus signal handlers\n\n std::string peer;\n uint16_t port;\n uint16_t bind_port;\n std::string output_file;\n double bandwidth = -1.0;\n double min_ping = -1.0;\n\n std::ostringstream app_description{};\n app_description\n << \"MiniSynCPP v\" << APP_VERSION_MAJOR << \".\" << APP_VERSION_MINOR << \". \"\n << \"Standalone demo implementation of the Tiny/MiniSync time synchronization algorithms.\";\n\n CLI::App app{app_description.str()};\n\n auto* ref_mode = app.add_subcommand(\"REF_MODE\", \"Start node in reference mode; \"\n \"i.e. other peers synchronize to this node's clock.\");\n ref_mode->add_option<uint16_t>(\"BIND_PORT\", bind_port, \"Local UDP port to bind to.\")->required(true);\n ref_mode->add_option(\"-v\", loguru::g_stderr_verbosity, \"Set verbosity level.\", true);\n\n auto* sync_mode = app.add_subcommand(\"SYNC_MODE\", \"Start node in synchronization mode.\");\n\n sync_mode->add_option<uint16_t>(\"BIND_PORT\", bind_port, \"Local UDP port to bind to.\")->required(true);\n sync_mode->add_option<std::string>(\"ADDRESS\", peer, \"Address of peer to synchronize with.\")->required(true);\n sync_mode->add_option<uint16_t>(\"PORT\", port, \"Target UDP Port on peer.\")->required(true);\n sync_mode->add_option(\"-v\", loguru::g_stderr_verbosity, \"Set verbosity level.\", true);\n sync_mode->add_option(\"-o,--output\", output_file, \"Output stats to file.\", false);\n sync_mode->add_option(\"-b,--bandwidth\", bandwidth, // sync node is the only one that adjusts based on bandwidth\n \"Nominal bandwidth in Mbps, for minimum delay estimation.\",\n false);\n sync_mode->add_option(\"-p,--ping\", min_ping,\n \"Nominal minimum ICMP ping RTT in milliseconds for better minimum delay estimation.\",\n false);\n\n app.fallthrough(true);\n app.require_subcommand(1, 1);\n\n CLI11_PARSE(app, argc, argv)\n\n auto modes = app.get_subcommands();\n CHECK_EQ_F(modes.size(), 1, \"Wrong number of subcommands - THIS SHOULD NEVER HAPPEN?\");\n\n if (modes.front()->get_name() == \"REF_MODE\")\n {\n // LOG_F(INFO, \"Started node in REFERENCE mode.\");\n // MiniSync::ReferenceNode node{bind_port};\n node = new MiniSync::ReferenceNode{bind_port};\n }\n else if (modes.front()->get_name() == \"SYNC_MODE\")\n {\n // LOG_F(INFO, \"Started node in SYNCHRONIZATION mode.\");\n\n node = new MiniSync::SyncNode(bind_port, peer, port,\n MiniSync::API::Factory::createMiniSync(),\n output_file, bandwidth, min_ping);\n }\n else\n ABORT_F(\"Invalid mode specified for application - THIS SHOULD NEVER HAPPEN?\");\n\n try\n {\n node->run();\n }\n catch (std::exception& e)\n {\n LOG_F(ERROR, \"%s\", e.what());\n node->shut_down();\n }\n\n delete (node);\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5596963167190552, "alphanum_fraction": 0.5665976405143738, "avg_line_length": 26.339622497558594, "blob_id": "cb9636976cd7dd0b3a3421d634f06c6eb2ba10f1", "content_id": "7d4c36fd459499a005248370a163228b4655a679", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1450, "license_type": "permissive", "max_line_length": 106, "num_lines": 53, "path": "/src/libminisyncpp/minisync_api.h", "repo_name": "molguin92/MiniSynCPP", "src_encoding": "UTF-8", "text": "/*\n* Author: Manuel Olguín Muñoz <[email protected]>\n*\n* Copyright© 2019 Manuel Olguín Muñoz\n* See LICENSE file included in the root directory of this project for licensing and copyright details.\n*/\n#ifndef MINISYNCPP_MINISYNC_API_H\n#define MINISYNCPP_MINISYNC_API_H\n\n#include <chrono>\n#include <memory>\n\nnamespace MiniSync\n{\n typedef std::chrono::duration<long double, std::chrono::microseconds::period> us_t;\n\n namespace API\n {\n class Algorithm\n {\n public:\n /*\n * Add a new DataPoint and recalculate offset and drift.\n */\n virtual void addDataPoint(us_t To, us_t Tb, us_t Tr) = 0;\n\n /*\n * Get the current estimated relative clock drift.\n */\n virtual long double getDrift() = 0;\n virtual long double getDriftError() = 0;\n\n /*\n * Get the current estimated relative clock offset in nanoseconds.\n */\n virtual us_t getOffset() = 0;\n virtual us_t getOffsetError() = 0;\n\n /*\n * Get the current adjusted time\n */\n virtual std::chrono::time_point<std::chrono::system_clock, us_t> getCurrentAdjustedTime() = 0;\n };\n\n namespace Factory\n {\n std::shared_ptr<MiniSync::API::Algorithm> createTinySync();\n std::shared_ptr<MiniSync::API::Algorithm> createMiniSync();\n }\n }\n}\n\n#endif //MINISYNCPP_MINISYNC_API_H\n" } ]
22
LucyLiu-UCSB/Learn-Computer-Vision
https://github.com/LucyLiu-UCSB/Learn-Computer-Vision
051e3e449ca0e534b52ea2ee2d975672615d5509
841abf219bccc465ffea7e276405ddee5a4f489b
cd86f02c23971aaaf05a1b6cf40bb05fff0744c9
refs/heads/master
2021-05-18T23:37:38.985309
2020-07-12T23:23:15
2020-07-12T23:23:15
251,480,273
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6602409482002258, "alphanum_fraction": 0.6955823302268982, "avg_line_length": 22.49056625366211, "blob_id": "6b0e7bf14badcd2d259b8b531873650f8418f9d2", "content_id": "1129612b4f099b4fabf7bcc8707834706df9d099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 117, "num_lines": 53, "path": "/MasterOpenCV4/Chapter2_ImageBasic.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n## read image\nimg = cv2.imread('/Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface.png')\n\n## get dimension of the image\ndimensions = img.shape # height x width x channels\ntotal_number_of_elements = img.size\nimage_dtype = img.dtype\n\n## show image\ncv2.imshow('original image', img)\ncv2.waitKey(1)\nplt.imshow(img[:, :, ::-1])\nplt.xticks([]), plt.yticks([])\nplt.show()\n\n## get a pixel value\n(b, g, r) = img[6, 40]\n## get a region of the image\ntop_left_corner = img[0:50, 0:50]\nplt.imshow(top_left_corner[:, :, [2, 1, 0]])\nplt.show()\n\n## set a pixel value to red\nimg[6, 40] = (0, 0, 255)\n\n## read image in grey scale\ngray_img = cv2.imread('/Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface.png', cv2.IMREAD_GRAYSCALE)\ni = gray_img[6, 40]\nplt.imshow(gray_img, cmap='gray', vmin=0, vmax=255)\nplt.show()\n\n## split and merge channels\nb, g, r = cv2.split(img)\nimg_rgb = cv2.merge([r, g, b])\nplt.imshow(img_rgb)\n\n## show b g r and r g b image\nplt.subplot(121)\nplt.imshow(img)\n\nplt.subplot(122)\nplt.imshow(img_rgb)\nplt.show()\n\n## concatenate two picture horizontally\nimg_concats = np.concatenate((img, img_rgb), axis=1)\nplt.imshow(img_concats)\nplt.show()" }, { "alpha_fraction": 0.7417961955070496, "alphanum_fraction": 0.7426597476005554, "avg_line_length": 40.39285659790039, "blob_id": "ba51bef77f2bcf4450d5c5ea5c0e626371da5143", "content_id": "7fdae12ee3c34537dd9400de87ccdfffc9013aa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 111, "num_lines": 28, "path": "/MasterOpenCV4/Chapter3_argparse.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "import argparse\n\nparser = argparse.ArgumentParser()\n\n## add a positional argument using add_argument() including a help\nparser.add_argument('first_number', help='this is the string text in connection with fisrt_argument', type=int)\n# We add 'second_number' argument using add_argument() including a help The type of this argument is int\n# note that the default is str\nparser.add_argument(\"second_number\", help=\"second number to be added\", type=int)\n\n## ArgumentParser parses arguments through the parse_args() method:\nargs = parser.parse_args()\nprint(\"args: '{}'\".format(args))\nprint(\"the sum is: '{}'\".format(args.first_number + args.second_number))\n\n## Additionally, the arguments can be stored in a dictionary calling vars() function:\nargs_dict = vars(parser.parse_args())\n# We print this dictionary:\nprint(\"args_dict dictionary: '{}'\".format(args_dict))\n\n## get and print the first argument of the script\nprint(\"first raw argument is '{}'\".format(args.first_number))\n# For example, to get the first argument using this dictionary:\nprint(\"first argument from the dictionary: '{}'\".format(args_dict[\"first_number\"]))\n\n\n\n# run python Chapter3_argparse.py -h" }, { "alpha_fraction": 0.5545454621315002, "alphanum_fraction": 0.6466666460037231, "avg_line_length": 37.83529281616211, "blob_id": "c56cf5ce267c9239e631a1d8bbd8a6409c25afd8", "content_id": "82eb1811d859da2a2b630367c860f8f76e16f50b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3300, "license_type": "no_license", "max_line_length": 112, "num_lines": 85, "path": "/MasterOpenCV4/Chapter4_construct_basic_shape.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n## build a color dictionary\ncolors = {'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), 'yellow': (0, 255, 255),\n 'magenta': (255, 0, 255), 'cyan': (255, 255, 0), 'white': (255, 255, 255), 'black': (0, 0, 0),\n 'gray': (125, 125, 125), 'rand': np.random.randint(0, high=256, size=(3,)).tolist(),\n 'dark_gray': (50, 50, 50), 'light_gray': (220, 220, 220)}\n\n## matplotlib plot\ndef show_with_matplotlib(img, title):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n # Convert BGR image to RGB:\n img_RGB = img[:, :, ::-1]\n\n # Show the image using matplotlib:\n plt.imshow(img_RGB)\n plt.title(title)\n plt.show()\n\n## show color map\n# We set background to black using np.zeros():\nimage = np.zeros((500, 500, 3), dtype=\"uint8\")\n\n# If you want another background color you can do the following:\nimage[:] = colors['light_gray']\n\n# We draw all the colors to test the dictionary\n# We draw some lines each one in one color. To get the color use 'colors[key]'\nseparation = 40\nfor key in colors:\n # Draw a line using the function cv2.line():\n cv2.line(image, (0, separation), (500, separation), colors[key], 10)\n separation += 40\n\n# Show image:\nshow_with_matplotlib(image, 'Dictionary with some predefined colors')\n\n## Draw basic shapes\n\n# We create the canvas to draw: 400 x 400 pixels, 3 channels, uint8 (8-bit unsigned integers)\n# We set the background to black using np.zeros()\n\nimage = np.zeros((400, 400, 3), dtype=\"uint8\")\n# If you want another background color, you can do the following:\nimage[:] = colors['light_gray']\n\n## drawing lines\ncv2.line(image, pt1 = (0, 0), pt2 = (400, 400), color = colors['green'], thickness = 3)\ncv2.line(image, (0, 400), (400, 0), colors['blue'], thickness=10)\ncv2.line(image, (200, 0), (200, 400), colors['red'], 3)\ncv2.line(image, (0, 200), (400, 200), colors['yellow'], 10)\nshow_with_matplotlib(image, 'cv2.line()')\n\n## Drawing rectangles\ncv2.rectangle(image, pt1 = (10, 50), pt2 = (60, 300), color = colors['green'], thickness = 3)\n# thickness -1 to fill the rectangles\ncv2.rectangle(image, (80, 50), (130, 300), colors['blue'], -1)\ncv2.rectangle(image, (150, 50), (350, 100), colors['red'], -1)\ncv2.rectangle(image, (150, 150), (350, 300), colors['cyan'], 10)\nshow_with_matplotlib(image, 'cv2.rectangle()')\n\n## drawing circles\ncv2.circle(image, center = (50, 50), radius = 20, color = colors['green'], thickness = 3)\ncv2.circle(image, (100, 100), 30, colors['blue'], -1)\ncv2.circle(image, (200, 200), 40, colors['magenta'], 10)\ncv2.circle(image, (300, 300), 40, colors['cyan'], -1)\nshow_with_matplotlib(image, 'cv2.circle()')\n\n## write text\n\n## other font choices, textbox and underline -- page 198\nimage.fill(255)\n# img = cv.putText( img, text, org, fontFace, fontScale, color, thickness=1, lineType)\ncv2.putText(image, 'Mastering OpenCV4 with Python', (10, 30), 6, 0.5, colors['red'], 2,\n cv2.LINE_4)\ncv2.putText(image, 'Mastering OpenCV4 with Python', (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.9, colors['green'], 1,\n cv2.LINE_8)\ncv2.putText(image, 'Mastering OpenCV4 with Python', (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 0.9, colors['blue'], 3,\n cv2.LINE_AA)\n\nshow_with_matplotlib(image, 'cv2.putText()')" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7962962985038757, "avg_line_length": 26, "blob_id": "d4dd9e151b41f2587677eb736117bcd709669756", "content_id": "18a0dabb38ac796f5d68530e5237e7de88927be0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 54, "license_type": "no_license", "max_line_length": 29, "num_lines": 2, "path": "/README.md", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "# Learn Computer Vision\nstage 1. learn OpenCV package\n" }, { "alpha_fraction": 0.6351311802864075, "alphanum_fraction": 0.6936830878257751, "avg_line_length": 40.721309661865234, "blob_id": "4c4b0ce162d9f4af83b3b37e27e0780c0da0f391", "content_id": "7ed591001b974b2baf0d9b37510100ddbdd0a42c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10179, "license_type": "no_license", "max_line_length": 134, "num_lines": 244, "path": "/MasterOpenCV4/Chapter5_image_processing_techniques.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "import cv2\nimport matplotlib.pyplot as plt\n\n########################## split and merge channels ##########################\nimage = cv2.imread('/Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface.png')\nb, g, r = cv2.split(image)\n# note that split function is slower than\nb = image[:, :, 0]\n\n## merge image\nimage_copy = cv2.merge((b, g, r))\n\ndef show_with_matplotlib(color_img, title, pos):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n # Convert BGR image to RGB\n img_RGB = color_img[:, :, ::-1]\n\n ax = plt.subplot(3, 6, pos)\n plt.imshow(img_RGB)\n plt.title(title)\n plt.axis('off')\n\n\n# create a figure() object with appropriate size and title:\nplt.figure(figsize=(13, 5))\nplt.suptitle(\"Splitting and merging channels in OpenCV\", fontsize=14, fontweight='bold')\n\n# Show the BGR image:\nshow_with_matplotlib(image, \"BGR - image\", 1)\n\n# Show all the channels from the BGR image:\nshow_with_matplotlib(cv2.cvtColor(b, cv2.COLOR_GRAY2BGR), \"BGR - (B)\", 2)\nshow_with_matplotlib(cv2.cvtColor(g, cv2.COLOR_GRAY2BGR), \"BGR - (G)\", 2 + 6)\nshow_with_matplotlib(cv2.cvtColor(r, cv2.COLOR_GRAY2BGR), \"BGR - (R)\", 2 + 6 * 2)\n\n# Show the BGR image:\nshow_with_matplotlib(image_copy, \"BGR - image (copy)\", 1 + 6)\n\n\n# We make a copy of the loaded image:\nimage_without_blue = image.copy()\n\n# From the BGR image, we \"eliminate\" (set to 0) the blue component (channel 0):\nimage_without_blue[:, :, 0] = 0\n\n# From the BGR image, we \"eliminate\" (set to 0) the green component (channel 1):\nimage_without_green = image.copy()\nimage_without_green[:, :, 1] = 0\n\n# From the BGR image, we \"eliminate\" (set to 0) the red component (channel 2):\nimage_without_red = image.copy()\nimage_without_red[:, :, 2] = 0\n\n# Show all the channels from the BGR image:\nshow_with_matplotlib(image_without_blue, \"BGR without B\", 3)\nshow_with_matplotlib(image_without_green, \"BGR without G\", 3 + 6)\nshow_with_matplotlib(image_without_red, \"BGR without R\", 3 + 6 * 2)\n\n# Split the 'image_without_blue' image into its three components (blue, green and red):\n(b, g, r) = cv2.split(image_without_blue)\n\n# Show all the channels from the BGR image without the blue information:\nshow_with_matplotlib(cv2.cvtColor(b, cv2.COLOR_GRAY2BGR), \"BGR without B (B)\", 4)\nshow_with_matplotlib(cv2.cvtColor(g, cv2.COLOR_GRAY2BGR), \"BGR without B (G)\", 4 + 6)\nshow_with_matplotlib(cv2.cvtColor(r, cv2.COLOR_GRAY2BGR), \"BGR without B (R)\", 4 + 6 * 2)\n\n# Split the 'image_without_green' image into its three components (blue, green and red):\n(b, g, r) = cv2.split(image_without_green)\n\n# Show all the channels from the BGR image without the green information:\nshow_with_matplotlib(cv2.cvtColor(b, cv2.COLOR_GRAY2BGR), \"BGR without G (B)\", 5)\nshow_with_matplotlib(cv2.cvtColor(g, cv2.COLOR_GRAY2BGR), \"BGR without G (G)\", 5 + 6)\nshow_with_matplotlib(cv2.cvtColor(r, cv2.COLOR_GRAY2BGR), \"BGR without G (R)\", 5 + 6 * 2)\n\n# Split the 'image_without_red' image into its three components (blue, green and red):\n(b, g, r) = cv2.split(image_without_red)\n\n# Show all the channels from the BGR image without the red information:\nshow_with_matplotlib(cv2.cvtColor(b, cv2.COLOR_GRAY2BGR), \"BGR without R (B)\", 6)\nshow_with_matplotlib(cv2.cvtColor(g, cv2.COLOR_GRAY2BGR), \"BGR without R (G)\", 6 + 6)\nshow_with_matplotlib(cv2.cvtColor(r, cv2.COLOR_GRAY2BGR), \"BGR without R (R)\", 6 + 6 * 2)\n\n# Show the created image:\nplt.show()\n\n########################## Geometric transformation of images ##########################\n\ndef show_with_matplotlib(img, title):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n # Convert BGR image to RGB\n img_RGB = img[:, :, ::-1]\n\n # Show the image using matplotlib:\n plt.imshow(img_RGB)\n plt.title(title)\n plt.show()\n\n## affine transformation, the transformation is on the position\n# | m11, m12 | |x| |m13|\n# | |*| | + | |\n# | m21, m22 | |y| |m23|\n\n# 1. Scaling or resizing\n# Resize the input image using cv2.resize()\n# Resize using the scaling factor for each dimension of the image\n# In this case the scaling factor is 0.5 in every dimension\ndst_image = cv2.resize(image, dsize = None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)\n\n# Get the height and width of the image:\nheight, width = image.shape[:2]\n\n# You can resize also the image specifying the new size:\ndst_image_2 = cv2.resize(image, (width * 2, height * 2), interpolation=cv2.INTER_LINEAR)\n\n# We see the two resized images:\nshow_with_matplotlib(dst_image, 'Resized image')\nshow_with_matplotlib(dst_image_2, 'Resized image 2')\n\n# 2. Translation\n# You need to create the 2x3 transformation matrix making use of numpy array with float values (float32)\n# Translation in the x direction: 200 pixels, and a translation in the y direction: 30 pixels:\nM = np.float32([[1, 0, 200], [0, 1, 30]])\n# Once this transformation Matrix is created, we can pass it to the function cv2.warpAffine():\ndst_image = cv2.warpAffine(image, M, dsize = (width, height))\n# Show the translated image:\n# the image move to right by 200 and down by 30\nshow_with_matplotlib(dst_image, 'Translated image (positive values)')\n\nM = np.float32([[1, 0, -200], [0, 1, -30]]) # move left and up\ndst_image = cv2.warpAffine(image, M, (width, height))\nshow_with_matplotlib(dst_image, 'Translated image (negative values)')\n\naa = np.sqrt(2)*0.5\nM_rotation = np.float32([[aa, aa, 0], [-aa, aa, 0]]) # rotate the photo\ndst_image = cv2.warpAffine(image, M_rotation, (width, height))\nshow_with_matplotlib(dst_image, 'rotate image')\n\n# note that\nleft_bottom = np.dot(M_rotation[:, [0, 1]], np.array([0, 600]).reshape((2, 1)))\n\n# 3. Rotation\n# To rotate the image we make use of the function cv.getRotationMatrix2D() to build the 2x3 rotation matrix:\n# In this case, we are going to rotate the image 180 degrees (upside down):\nM = cv2.getRotationMatrix2D((width / 2.0, height / 2.0), 180, 1)\ndst_image = cv2.warpAffine(image, M, (width, height))\n\n\n# Show the center of rotation and the rotated image:\ncv2.circle(dst_image, (round(width / 2.0), round(height / 2.0)), 5, (255, 0, 0), -1)\nshow_with_matplotlib(dst_image, 'Image rotated 180 degrees')\n\n# Now, we are going to rotate the image 30 degrees changing the center of rotation\nM = cv2.getRotationMatrix2D((width / 1.5, height / 1.5), 30, 1)\ndst_image = cv2.warpAffine(image, M, (width, height))\n\n# Show the center of rotation and the rotated image:\ncv2.circle(dst_image, (round(width / 1.5), round(height / 1.5)), 5, (255, 0, 0), -1)\nshow_with_matplotlib(dst_image, 'Image rotated 30 degrees')\n\n\n# 4. Affine Transformation\n# In an affine transformation we first make use of the function cv2.getAffineTransform()\n# to build the 2x3 transformation matrix, which is obtained from the relation between three points\n# from the input image and their corresponding coordinates in the transformed image.\n\n# the transformation is determined by move the first three points to the second three points. six equations solve six parameters in M.\n\n# A copy of the image is created to show the points that will be used for the affine transformation:\nimage_points = image.copy()\ncv2.circle(image_points, (135, 45), 5, (255, 0, 255), -1)\ncv2.circle(image_points, (385, 45), 5, (255, 0, 255), -1)\ncv2.circle(image_points, (135, 230), 5, (255, 0, 255), -1)\n\n# Show the image with the three created points:\nshow_with_matplotlib(image_points, 'before affine transformation')\n\n# We create the arrays with the aforementioned three points and the desired positions in the output image:\npts_1 = np.float32([[135, 45], [400, 45], [135, 230]])\npts_2 = np.float32([[135, 45], [400, 45], [150, 230]])\n\n# We get the 2x3 tranformation matrix based on pts_1 and pts_2 and apply cv2.warpAffine():\nM = cv2.getAffineTransform(pts_1, pts_2)\ndst_image = cv2.warpAffine(image_points, M, (width, height))\n\n# Show the image:\nshow_with_matplotlib(dst_image, 'Affine transformation')\n\n\n\n# 5. Perspective transformation\n# A copy of the image is created to show the points that will be used for the perspective transformation:\nimage_points = image.copy()\ncv2.circle(image_points, (450, 65), 5, (255, 0, 255), -1)\ncv2.circle(image_points, (517, 65), 5, (255, 0, 255), -1)\ncv2.circle(image_points, (431, 164), 5, (255, 0, 255), -1)\ncv2.circle(image_points, (552, 164), 5, (255, 0, 255), -1)\n\n# Show the image:\nshow_with_matplotlib(image_points, 'before perspective transformation')\n\n# cv2.getPerspectiveTransform() needs four pairs of points\n# (coordinates of a quadrangle in both the source and output image)\n# We create the arrays for these four pairs of points:\npts_1 = np.float32([[450, 65], [517, 65], [431, 164], [552, 164]])\npts_2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])\n\n# stretch the first four points to form the perspective of second four points\n\n# To correct the perspective (also known as perspective transformation) you need to create the transformation matrix\n# making use of the function cv2.getPerspectiveTransform(), where a 3x3 matrix is constructed:\nM = cv2.getPerspectiveTransform(pts_1, pts_2)\n\n# Then, apply cv2.warpPerspective(), where the source image is transformed applying\n# the specified matrix and with a specified size:\ndst_image = cv2.warpPerspective(image, M, (300, 300))\n\n# Show the image:\nshow_with_matplotlib(dst_image, 'perspective transformation')\n\n\n# 6. Cropping\n# A copy of the image is created to show the points that will be used for the cropping example:\nimage_points = image.copy()\n\n# Show the points and lines connecting the points:\ncv2.circle(image_points, (230, 80), 5, (0, 0, 255), -1)\ncv2.circle(image_points, (330, 80), 5, (0, 0, 255), -1)\ncv2.circle(image_points, (230, 200), 5, (0, 0, 255), -1)\ncv2.circle(image_points, (330, 200), 5, (0, 0, 255), -1)\ncv2.line(image_points, (230, 80), (330, 80), (0, 0, 255))\ncv2.line(image_points, (230, 200), (330, 200), (0, 0, 255))\ncv2.line(image_points, (230, 80), (230, 200), (0, 0, 255))\ncv2.line(image_points, (330, 200), (330, 80), (0, 0, 255))\n\n# Show the image with the points and lines:\nshow_with_matplotlib(image_points, 'Before cropping')\n\n# For cropping, we make use of numpy slicing:\ndst_image = image[80:200, 230:330]\n\n# Show the image:\nshow_with_matplotlib(dst_image, 'Cropping image')" }, { "alpha_fraction": 0.6037021279335022, "alphanum_fraction": 0.6546066403388977, "avg_line_length": 35.86046600341797, "blob_id": "d1e8d88f9234cf18814c897816c56b120cf51853", "content_id": "382ab393b93cd8ca38c36e144ca7f62ee0c42d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4754, "license_type": "no_license", "max_line_length": 108, "num_lines": 129, "path": "/MasterOpenCV4/Chapter5_image_filtering.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "# Import required packages:\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef show_with_matplotlib(color_img, title, pos):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n # Convert BGR image to RGB\n img_RGB = color_img[:, :, ::-1]\n\n ax = plt.subplot(3, 3, pos)\n plt.imshow(img_RGB)\n plt.title(title)\n plt.axis('off')\n\n## read image\nimage = cv2.imread('/Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface.png')\n\n# Create a figure() object with appropriate size and title\nplt.figure(figsize=(12, 6))\nplt.suptitle(\"Smoothing techniques\", fontsize=14, fontweight='bold')\n\n## create the average kernel\nkernel_averaging_5_5 = np.ones((5, 5), np.float32)/25\nkernel_averaging_10_10 = np.ones((10, 10), np.float32) / 100\n\nprint(\"kernel: {}\".format(kernel_averaging_5_5))\n# The function cv2.filter2D() applies an arbitrary linear filter to the provided image:\nsmooth_image_f2D_5_5 = cv2.filter2D(image, -1, kernel_averaging_5_5)\nsmooth_image_f2D_10_10 = cv2.filter2D(image, -1, kernel_averaging_10_10)\n\nsmooth_image_b = cv2.blur(image, (10, 10))\n\n# When the parameter normalize (by default True) of cv2.boxFilter() is equals to True,\n# cv2.filter2D() and cv2.boxFilter() perform the same operation:\nsmooth_image_bfi = cv2.boxFilter(image, -1, (10, 10), normalize=True)\n\n# The function cv2.GaussianBlur() convolves the source image with the specified Gaussian kernel\n# This kernel can be controlled using the parameters ksize (kernel size),\n# sigmaX(standard deviation in the x direction of the gaussian kernel) and\n# sigmaY (standard deviation in the y direction of the gaussian kernel)\nsmooth_image_gb = cv2.GaussianBlur(image, (9, 9), 0)\n\n# The function cv2.medianBlur(), which blurs the image with a median kernel:\nsmooth_image_mb = cv2.medianBlur(image, 9)\n\n# The function cv2.bilateralFilter() can be applied to the input image in order to apply a bilateral filter:\nsmooth_image_bf = cv2.bilateralFilter(image, 5, 10, 10)\nsmooth_image_bf_2 = cv2.bilateralFilter(image, 9, 200, 200)\n\n# Plot the images:\nshow_with_matplotlib(image, \"original\", 1)\nshow_with_matplotlib(smooth_image_f2D_5_5, \"cv2.filter2D() (5,5) kernel\", 2)\nshow_with_matplotlib(smooth_image_f2D_10_10, \"cv2.filter2D() (10,10) kernel\", 3)\nshow_with_matplotlib(smooth_image_b, \"cv2.blur()\", 4)\nshow_with_matplotlib(smooth_image_bfi, \"cv2.boxFilter()\", 5)\nshow_with_matplotlib(smooth_image_gb, \"cv2.GaussianBlur()\", 6)\nshow_with_matplotlib(smooth_image_mb, \"cv2.medianBlur()\", 7)\nshow_with_matplotlib(smooth_image_bf, \"cv2.bilateralFilter() - small values\", 8)\nshow_with_matplotlib(smooth_image_bf_2, \"cv2.bilateralFilter() - big values\", 9)\n\n# Show the created image:\nplt.show()\n\n\n#### sharpen filters\ndef show_with_matplotlib(color_img, title, pos):\n \"\"\"Shows an image using matplotlib capabilities\"\"\"\n\n # Convert BGR image to RGB\n img_RGB = color_img[:, :, ::-1]\n\n ax = plt.subplot(2, 3, pos)\n plt.imshow(img_RGB)\n plt.title(title)\n plt.axis('off')\n\n\ndef unsharped_filter(img):\n \"\"\"The unsharp filter enhances edges subtracting the smoothed image from the original image\"\"\"\n\n smoothed = cv2.GaussianBlur(img, (9, 9), 10)\n return cv2.addWeighted(img, 1.5, smoothed, -0.5, 0)\n\n\n# Create the dimensions of the figure and set title:\nplt.figure(figsize=(12, 6))\nplt.suptitle(\"Sharpening images\", fontsize=14, fontweight='bold')\n\n# We create the kernel for sharpening images\nkernel_sharpen_1 = np.array([[0, -1, 0],\n [-1, 5, -1],\n [0, -1, 0]])\n\nkernel_sharpen_2 = np.array([[-1, -1, -1],\n [-1, 9, -1],\n [-1, -1, -1]])\n\nkernel_sharpen_3 = np.array([[1, 1, 1],\n [1, -7, 1],\n [1, 1, 1]])\n\nkernel_sharpen_4 = np.array([[-1, -1, -1, -1, -1],\n [-1, 2, 2, 2, -1],\n [-1, 2, 8, 2, -1],\n [-1, 2, 2, 2, -1],\n [-1, -1, -1, -1, -1]]) / 8.0\n\n# Apply all the kernels we have created:\nsharp_image_1 = cv2.filter2D(image, -1, kernel_sharpen_1)\nsharp_image_2 = cv2.filter2D(image, -1, kernel_sharpen_2)\nsharp_image_3 = cv2.filter2D(image, -1, kernel_sharpen_3)\nsharp_image_4 = cv2.filter2D(image, -1, kernel_sharpen_4)\n\n# Try the unsharped filter:\nsharp_image_5 = unsharped_filter(image)\n\n# Display all the resulting images:\nshow_with_matplotlib(image, \"original\", 1)\nshow_with_matplotlib(sharp_image_1, \"sharp 1\", 2)\nshow_with_matplotlib(sharp_image_2, \"sharp 2\", 3)\nshow_with_matplotlib(sharp_image_3, \"sharp 3\", 4)\nshow_with_matplotlib(sharp_image_4, \"sharp 4\", 5)\nshow_with_matplotlib(sharp_image_5, \"sharp 5\", 6)\n\n# Show the Figure:\nplt.show()" }, { "alpha_fraction": 0.7394043803215027, "alphanum_fraction": 0.7525773048400879, "avg_line_length": 32.596153259277344, "blob_id": "8c273fa6fd6a75a886879f86ef65dc12026fa291", "content_id": "d5b7f7f6c0c402fe1de8698cb8f5109fc563b447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 188, "num_lines": 52, "path": "/MasterOpenCV4/Chapter3_argparse_load_save_image.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "import argparse\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n## create the argumentparser object, it can parse the command-line arguments into data types\nparser = argparse.ArgumentParser()\n\n## add 'path_image' argument using add_argment() including a help\nparser.add_argument('path_image', help=\"path to input image to be displayed\")\n# Add 'path_image_output' argument using add_argument() including a help. The type is string\nparser.add_argument(\"path_image_output\", help=\"path of the processed image to be saved\")\n\n## the imformation is stored in 'parser'. use information when the parser calls parse_args() method\nargs = parser.parse_args()\n\n## we can load the input from disk using the path in args\nimage = cv2.imread(args.path_image)\n\n## parse the argument and store it in a dictionary\nargs = vars(parser.parse_args())\n\n## load the input image from disk using args element in a dictionary\nimage2 = cv2.imread(args['path_image'])\n\n\nimg_concats = np.concatenate((image, image2), axis=1)\nplt.imshow(img_concats[:, :, ::-1])\nplt.show()\n\n# Process the input image (convert it to grayscale):\ngray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nplt.imshow(gray_image, cmap='gray', vmin=0, vmax=255)\nplt.show()\n\n\n# Save the processed image to disk:\ncv2.imwrite(args[\"path_image_output\"], gray_image)\n\n#### test function by run in terminal\n# python Chapter3_argparse_load_image.py /Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface.png /Users/lucyliu/Documents/GitHub/LearnComputerVision/image/lucyface_gray.png\n\n'''\n# Show the loaded image:\ncv2.imshow(\"loaded image\", image)\ncv2.imshow(\"loaded image2\", image2\n\n# Wait until a key is pressed:\ncv2.waitKey(0)\n# Destroy all windows: \ncv2.destroyAllWindows()\n'''" }, { "alpha_fraction": 0.7382671236991882, "alphanum_fraction": 0.7454873919487, "avg_line_length": 33.5625, "blob_id": "7149df16aa670d7dafcbc106aa1790fffb1eea42", "content_id": "32c63de35ac1d3e64f54135b1a8b5651025154f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 77, "num_lines": 16, "path": "/MasterOpenCV4/Chapter3_handle_files_images.py", "repo_name": "LucyLiu-UCSB/Learn-Computer-Vision", "src_encoding": "UTF-8", "text": "import cv2\nimport sys\nimport argparse\nfrom matplotlib import pyplot as plt\n\n## using sys to pass arguments\nprint(\"The name of the script being processed is: '{}'\".format(sys.argv[0]))\nprint(\"The number of arguments of the script is: '{}'\".format(len(sys.argv)))\nprint(\"The arguments of the script are: '{}'\".format(str(sys.argv)))\n\n# run in Terminal to test: python Chapter3_handle_files_images.py\n# run in Terminal to test: python Chapter3_handle_files_images.py OpenCV\n\n## using argparse library\nparser = argparse.ArgumentParser()\nparser.parse_args()\n\n" } ]
8
lilkyze/bachelor2021
https://github.com/lilkyze/bachelor2021
7ddce3c71c0f7e58df2e6647f484c3513d322e88
9c7082f833597febe999de395ed5da68b6a15e90
9ed44e8da5ea8f3120e1cb010039f031fe98aa09
refs/heads/main
2023-03-14T03:57:02.015154
2021-03-05T02:49:31
2021-03-05T02:49:31
339,831,928
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6358470916748047, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 36.7599983215332, "blob_id": "259d3918f11c533c8147bd37ff3ff126d5ed00c6", "content_id": "768639d5a73fa3e865c973c9fbd68af98ac58806", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1936, "license_type": "no_license", "max_line_length": 103, "num_lines": 50, "path": "/scraping-bachelor-twitter-followers.py", "repo_name": "lilkyze/bachelor2021", "src_encoding": "UTF-8", "text": "import twitter\r\nimport pandas as pd\r\n\r\n# initialize the twitter api module with your keys\r\napi = twitter.Api(consumer_key='consumer-key-here',\r\n consumer_secret='consumer-secret-here',\r\n access_token_key='access-token-key-here',\r\n access_token_secret='access-token-secret-here',\r\n sleep_on_rate_limit=True\r\n )\r\n\r\n# read in the contestant data set\r\ndf = pd.read_csv('bachelor_data.csv')\r\n\r\n# only grab non-null twitter handles to grab followers\r\nhandles = [handle for handle in df['twitter_handle'].values if not pd.isnull(handle) and handle != '-']\r\n\r\n# create a connections dict - key: handle; value: list of following (friends)\r\nconnections_dict = {}\r\n\r\n# iterate through all the twitter handles - wrap in try/catch in case user is private\r\nfor handle in handles:\r\n try:\r\n # get the friends via twitter api & save to connections dict\r\n friends = api.GetFriends(screen_name=handle)\r\n connections_dict[handle] = friends\r\n print('success: ' + handle)\r\n except:\r\n print('error: ' + handle)\r\n continue\r\n\r\n# create the output dataframe. each row will be a follower output\r\nrelationship_df = pd.DataFrame(columns = [\"who\", \"following\"])\r\n\r\n# for each handle in connections, dict - add each individual to the row\r\nfor key, value in connections_dict.items():\r\n \r\n # if they are following someone!\r\n if len(value) > 0:\r\n # create a temp df w this handle's info\r\n temp = pd.DataFrame(value)\r\n temp['who'] = key\r\n temp.columns = [\"following\", \"who\"]\r\n temp[\"following\"] = temp[\"following\"].apply(lambda x: x.screen_name)\r\n \r\n # append this to the relationship (output) df\r\n relationship_df = pd.concat([relationship_df, temp])\r\n\r\n# save file to csv\r\nrelationship_df[['who', 'following']].to_csv('MASTER-DATA-TWITTER-RELATIONSHIP.csv', index = False)" }, { "alpha_fraction": 0.7329300045967102, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 31.13888931274414, "blob_id": "eef6a08fdd78b2a698b0fd2731769731a6f22b49", "content_id": "3e764cad5c00a87108bda69c4ce59dab05e1645e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1157, "license_type": "no_license", "max_line_length": 114, "num_lines": 36, "path": "/README.md", "repo_name": "lilkyze/bachelor2021", "src_encoding": "UTF-8", "text": "# bachelor2021\n\n# Neo4j Set up \n\n1. Download Neo4j 4.\n - Neo4j Desktop is where you can maintain your databases, change config files, and start/stop/restart database. \n - Neo4j Browser is where you can query and view the database.\n - Neo4j bolt is the port which you can reach your database through API or in our case a python driver.\n\n2. Download Neo4j python driver.\n - pip install neo4j\n\n3. Configure database so that you can import csv quickly.\n - Uncomment the line containing:\n dbms.security.allow_csv_import_from_file_urls=true\n - Comment this line below:\n #dbms.directories.import=import\n Doucementation for this step can be found ger\n https://neo4j.com/docs/cypher-manual/current/clauses/load-csv/\n\n4. Create Constraints on the Database and upload the database.\n - Run the queries from UploadData.cypher file.\n \n5. Run Cypher queries to explore the data.\n\n# Gephi set up \n1. Download Gephi.\n\n2. Install plugins.\n - Install Graph Streaming: This plugin will connect the streeam \n - Install Image Preview: This plugin will place a .png on a node.\n\n3. Start streaming on Gephi UI.\n\n4. Send graph from Neo4j.\n - See streamtogephi.cypher\n" } ]
2
tusha28/Resume-Builder-master
https://github.com/tusha28/Resume-Builder-master
74e96814fb42a728a3e0f5e781b465b6e4e646f9
edcd297a70b80c381e0cb6609d12036baeb0f445
2159323e663733983d045216e2279eded9b12798
refs/heads/master
2023-08-17T00:56:11.772608
2021-09-25T05:16:28
2021-09-25T05:16:28
409,972,282
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.695341169834137, "alphanum_fraction": 0.7345834374427795, "avg_line_length": 54.846153259277344, "blob_id": "6297d2b85670e529d2722244d05530d8e6e758c7", "content_id": "68524466d4adf82623709a35f8adb1eb72689b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5173, "license_type": "no_license", "max_line_length": 76, "num_lines": 91, "path": "/resumeBuilder/models.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "from django.db import models\r\nfrom django.contrib.auth.models import User\r\n\r\n# Create your models here.\r\n\r\nclass Profile(models.Model):\r\n userid = models.CharField(max_length=50)\r\n name = models.CharField(max_length=100)\r\n objective = models.TextField()\r\n address = models.CharField(max_length=200)\r\n phoneno = models.CharField(max_length=12)\r\n email = models.EmailField(max_length=100)\r\n github = models.URLField(blank=True)\r\n linkedin = models.URLField(blank=True)\r\n university1 = models.CharField(max_length=100, blank=True)\r\n degree1 = models.CharField(max_length=50, blank=True)\r\n stream1 = models.CharField(max_length=100, blank=True)\r\n currentYear1 = models.CharField(max_length=50, blank=True)\r\n univStartingYear1 = models.CharField(max_length=20, blank=True)\r\n univPassingYear1 = models.CharField(max_length=20, blank=True)\r\n univResult1 = models.CharField(max_length=20, blank=True)\r\n university2 = models.CharField(max_length=100, blank=True)\r\n degree2 = models.CharField(max_length=50, blank=True)\r\n stream2 = models.CharField(max_length=100, blank=True)\r\n currentYear2 = models.CharField(max_length=50, blank=True)\r\n univStartingYear2 = models.CharField(max_length=20, blank=True)\r\n univPassingYear2 = models.CharField(max_length=20, blank=True)\r\n univResult2 = models.CharField(max_length=20, blank=True)\r\n intermediateSchool = models.CharField(max_length=100, blank=True)\r\n intermediateSubjects = models.CharField(max_length=100, blank=True)\r\n intermediateStartingYear = models.CharField(max_length=20, blank=True)\r\n intermediatePassingYear = models.CharField(max_length=20, blank=True)\r\n intermediateMarks = models.CharField(max_length=15, blank=True)\r\n highSchool = models.CharField(max_length=100, blank=True)\r\n highSchoolSubjects = models.CharField(max_length=100, blank=True)\r\n highSchoolStartingYear = models.CharField(max_length=20, blank=True)\r\n highSchoolPassingYear = models.CharField(max_length=20, blank=True)\r\n highSchoolMarks = models.CharField(max_length=20, blank=True)\r\n jobTitle1 = models.CharField(max_length=100, blank=True)\r\n jobStartDate1 = models.CharField(max_length=20, blank=True)\r\n jobEndDate1 = models.CharField(max_length=20, blank=True)\r\n jobDescription1 = models.TextField(blank=True, null=True)\r\n jobTitle2 = models.CharField(max_length=100, blank=True)\r\n jobStartDate2 = models.CharField(max_length=20, blank=True)\r\n jobEndDate2 = models.CharField(max_length=20, blank=True)\r\n jobDescription2 = models.TextField(blank=True, null=True)\r\n jobTitle3 = models.CharField(max_length=100, blank=True)\r\n jobStartDate3 = models.CharField(max_length=20, blank=True)\r\n jobEndDate3 = models.CharField(max_length=20, blank=True)\r\n jobDescription3 = models.TextField(blank=True, null=True)\r\n jobTitle4 = models.CharField(max_length=100, blank=True)\r\n jobStartDate4 = models.CharField(max_length=20, blank=True)\r\n jobEndDate4 = models.CharField(max_length=20, blank=True)\r\n jobDescription4 = models.TextField(blank=True, null=True)\r\n jobTitle5 = models.CharField(max_length=100, blank=True)\r\n jobStartDate5 = models.CharField(max_length=20, blank=True)\r\n jobEndDate5 = models.CharField(max_length=20, blank=True)\r\n jobDescription5 = models.TextField(blank=True, null=True)\r\n projectTitle1 = models.CharField(max_length=100, blank=True)\r\n projectStartDate1 = models.CharField(max_length=20, blank=True)\r\n projectEndDate1 = models.CharField(max_length=20, blank=True)\r\n projectDescription1 = models.TextField(blank=True, null=True)\r\n projectTitle2 = models.CharField(max_length=100, blank=True)\r\n projectStartDate2 = models.CharField(max_length=20, blank=True)\r\n projectEndDate2 = models.CharField(max_length=20, blank=True)\r\n projectDescription2 = models.TextField(blank=True, null=True)\r\n projectTitle3 = models.CharField(max_length=100, blank=True)\r\n projectStartDate3 = models.CharField(max_length=20, blank=True)\r\n projectEndDate3 = models.CharField(max_length=20, blank=True)\r\n projectDescription3 = models.TextField(blank=True, null=True)\r\n projectTitle4 = models.CharField(max_length=100, blank=True)\r\n projectStartDate4 = models.CharField(max_length=20, blank=True)\r\n projectEndDate4 = models.CharField(max_length=20, blank=True)\r\n projectDescription4 = models.TextField(blank=True, null=True)\r\n projectTitle5 = models.CharField(max_length=100, blank=True)\r\n projectStartDate5 = models.CharField(max_length=20, blank=True)\r\n projectEndDate5 = models.CharField(max_length=20, blank=True)\r\n projectDescription5 = models.TextField(blank=True, null=True)\r\n skillDetail = models.TextField()\r\n languageDetail = models.TextField() \r\n areaOfInterest = models.CharField(max_length=200, blank=True)\r\n extracurricularDetail = models.CharField(max_length=200, blank=True) \r\n\r\nclass Contact(models.Model):\r\n name = models.CharField(max_length=60)\r\n email = models.EmailField()\r\n phoneno = models.CharField(max_length=12)\r\n msg = models.TextField()\r\n\r\n def __str__(self):\r\n return self.name\r\n" }, { "alpha_fraction": 0.49582308530807495, "alphanum_fraction": 0.5056511163711548, "avg_line_length": 28.863636016845703, "blob_id": "bb022e6cfa898c9c57be03f8bcc53ec9e0ea9ee6", "content_id": "75eaa6f0caa769c7e62da4f0db163db914389fa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2035, "license_type": "no_license", "max_line_length": 101, "num_lines": 66, "path": "/templates/listResume.html", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\r\n\r\n<!-- changing title of page -->\r\n\r\n{% block title %}\r\nList Resume\r\n{% endblock title %}\r\n\r\n{% block body %}\r\n\r\n{% load static %}\r\n<div class=\"card-deck\">\r\n\r\n {% for profile in profile %}\r\n\r\n <!-- if resume is created display info of that resume and option to view that resume -->\r\n\r\n <div class=\"container-fluid pt-5 pb-3\">\r\n <div class=\"row\">\r\n <div class=\"col-sm-3\"> </div>\r\n <div class=\"col-sm-6 d-flex justify-content-center\">\r\n <div class=\"card\" style=\"width: 20rem;\">\r\n <div class=\"card\">\r\n <img class=\"card-img-top\" src=\"{% static '/images/resume-5.jpg' %}\" alt=\"Card image cap\">\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\">{{profile.name}}</h5>\r\n <p class=\"card-text\">{{profile.objective}}</p>\r\n </div>\r\n <div class=\"card-footer text-center\">\r\n <a href=\"/{{profile.id}}\" class=\"btn btn-success\"> View Resume </a>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"col-sm-3\"> </div>\r\n </div>\r\n </div>\r\n\r\n <!-- if no resume created, display this -->\r\n\r\n {% empty %}\r\n\r\n <div class=\"container-fluid pt-5 pb-3\">\r\n <div class=\"row\">\r\n <div class=\"col-sm-3\"> </div>\r\n <div class=\"col-sm-6 d-flex justify-content-center\">\r\n <div class=\"card\" style=\"width: 20rem;\">\r\n <div class=\"card\">\r\n <img class=\"card-img-top\" src=\"{% static '/images/resume-5.jpg' %}\" alt=\"Card image cap\">\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\"> You haven't created resume yet! </h5>\r\n <p class=\"card-text\">Lets get started! Create your first resume now!</p>\r\n </div>\r\n <div class=\"card-footer text-center\">\r\n <a href=\"/addResume\" class=\"btn btn-success\"> CREATE RESUME </a>\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"col-sm-3\"> </div>\r\n </div>\r\n </div>\r\n\r\n {% endfor %}\r\n\r\n {% endblock body %}" }, { "alpha_fraction": 0.5228531956672668, "alphanum_fraction": 0.5588642954826355, "avg_line_length": 29.08333396911621, "blob_id": "867af68c1fc81f5d63a9bd4e88e762508cb4003b", "content_id": "007e9fe5e791c76e79d9805f98bafe74ddc1858a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1444, "license_type": "no_license", "max_line_length": 63, "num_lines": 48, "path": "/resumeBuilder/migrations/0009_auto_20210411_1623.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-11 10:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0008_auto_20210411_1620'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='areaOfInterest',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='extracurricularDetail',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobDescription',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='languageDetail',\n field=models.CharField(max_length=200),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectDescription',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='skillDetail',\n field=models.CharField(max_length=200),\n ),\n migrations.AlterField(\n model_name='profile',\n name='university',\n field=models.CharField(blank=True, max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.5483125448226929, "alphanum_fraction": 0.5598705410957336, "avg_line_length": 35.04999923706055, "blob_id": "3001757a55e9319fead47cae6d5968fa0d4f8416", "content_id": "0f08152ab2c7c76877c1090b6dfbbe5427fe68b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2163, "license_type": "no_license", "max_line_length": 205, "num_lines": 60, "path": "/resumeBuilder/migrations/0002_auto_20210409_1838.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-09 13:08\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='ProjectorJob',\n new_name='Experience',\n ),\n migrations.RenameField(\n model_name='areaofinterest',\n old_name='area_of_interest_detail',\n new_name='areaofinterest_detail',\n ),\n migrations.RenameField(\n model_name='person',\n old_name='age',\n new_name='phoneno',\n ),\n migrations.RemoveField(\n model_name='person',\n name='gender',\n ),\n migrations.AddField(\n model_name='education',\n name='starting_year',\n field=models.DateField(default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='education',\n name='degree',\n field=models.CharField(choices=[('Phd', 'Male'), ('Mtech/MA/MSc/MCom/MBA', 'Masters'), ('BE/Btech/BA/BSc/BCom', 'Bachelors'), ('12th', 'Intermediate'), ('10th', 'High School')], max_length=50),\n ),\n migrations.CreateModel(\n name='Languages',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('language_detail', models.TextField()),\n ('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='resumeBuilder.person')),\n ],\n ),\n migrations.CreateModel(\n name='ExtraCurricular',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('extracurricular_detail', models.TextField()),\n ('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='resumeBuilder.person')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.503443717956543, "alphanum_fraction": 0.5210596323013306, "avg_line_length": 30.83478355407715, "blob_id": "bf588aa875e9a3175e2e36168d95696499ff05ca", "content_id": "b4fd33b5b03e901027650099b2f45c15e6c943f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 7550, "license_type": "no_license", "max_line_length": 295, "num_lines": 230, "path": "/templates/viewResume.html", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\r\n\r\n<!-- changing title of page -->\r\n\r\n{% block title %}\r\nView Resume\r\n{% endblock title %}\r\n\r\n{% block body %}\r\n{% load static %}\r\n\r\n<!-- creating template for displaying Resume -->\r\n\r\n<div class=\" pt-4 pl-5 pr-5 ml-5 mr-5 pb-4\">\r\n <div class=\"row\">\r\n <div class=\"col-md-2\">\r\n </div>\r\n <div class=\"col-md-8 border border-dark px-5 \">\r\n <div class=\"row\">\r\n <h2 class=\" h1 text-center py-3\"> {{user_profile.name}}</h2>\r\n <div class=\"col\">\r\n </div>\r\n <div class=\"col\">\r\n </div>\r\n\r\n <div class=\"col align-self-end pb-2\">\r\n <a href={{user_profile.github}}> {{user_profile.github}}</a> <br>\r\n <a href={{user_profile.linkedin}}> {{user_profile.linkedin}}</a>\r\n </div>\r\n <hr class=\"hl\">\r\n\r\n <div class=\"col-sm-4\">\r\n <h4 class=\"py-3 vl px-2\">CONTACT</h4>\r\n <p>{{user_profile.address}}</p>\r\n <p>{{user_profile.phoneno}}</p>\r\n <p>{{user_profile.email}}</p>\r\n </div>\r\n\r\n <div class=\"col-sm-8\">\r\n <h4 class=\"py-3 vl px-2\">OBJECTIVE</h4>\r\n <p>{{user_profile.objective}}</p>\r\n <br>\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-sm-4\">\r\n <hr class=\"hl invisible\">\r\n <h4 class=\"py-3 vl px-2\">SKILLS</h4>\r\n <p>{{user_profile.skillDetail}}</p>\r\n </div>\r\n <div class=\"col-sm-8\">\r\n\r\n {% if user_profile.university1 or user_profile.university2 or user_profile.intermediateSchool or user_profile.highSchool %}\r\n <hr class=\"hl\">\r\n\r\n <h4 class=\"py-3 vl px-2\">EDUCATION</h4>\r\n\r\n {% if user_profile.university1 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.degree1}} in {{user_profile.stream1}} --- (\r\n {{user_profile.univStartingYear1}} - {{user_profile.univPassingYear1}} ) </p>\r\n <p>{{user_profile.university1}} </p>\r\n <p>{{user_profile.univResult1}} </p>\r\n\r\n {%endif%}\r\n\r\n {% if user_profile.university2 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.degree2}} in {{user_profile.stream2}} --- (\r\n {{user_profile.univStartingYear2}} - {{user_profile.univPassingYear2}} ) </p>\r\n <p>{{user_profile.university2}} </p>\r\n <p>{{user_profile.univResult2}} </p>\r\n\r\n {%endif%}\r\n\r\n {% if user_profile.intermediateSchool %}\r\n\r\n <p class=\"font-weight-bold\"> Intermediate --- ( {{user_profile.intermediateStartingYear}} -\r\n {{user_profile.intermediatePassingYear}} )</p>\r\n <p> {{user_profile.intermediateSchool}} </p>\r\n <p> {{user_profile.intermediateMarks}} in {{user_profile.intermediateSubjects}} </p>\r\n\r\n {%endif%}\r\n\r\n {% if user_profile.highSchool %}\r\n\r\n <p class=\"font-weight-bold\"> High School --- ( {{user_profile.highSchoolStartingYear}} -\r\n {{user_profile.highSchoolPassingYear}} )</p>\r\n <p> {{user_profile.highSchool}} </p>\r\n <p> {{user_profile.highSchoolMarks}} in {{user_profile.highSchoolSubjects}} </p>\r\n\r\n {%endif%}\r\n\r\n {%endif%}\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-sm-4\">\r\n <hr class=\"hl invisible\">\r\n <h4 class=\"py-3 vl px-2\">LANGUAGES</h4>\r\n <p>{{user_profile.languageDetail}}</p>\r\n </div>\r\n <div class=\"col-sm-8\">\r\n\r\n {% if user_profile.jobTitle1 or user_profile.jobTitle2 or user_profile.jobTitle3 or user_profile.jobTitle4 or user_profile.jobTitle5 or user_profile.projectTitle1 or user_profile.projectTitle2 or user_profile.projectTitle3 or user_profile.projectTitle4 or user_profile.projectTitle5 %}\r\n\r\n <hr class=\"hl\">\r\n\r\n <h4 class=\"py-3 vl px-2\">EXPERIENCE</h4>\r\n\r\n {% if user_profile.jobTitle1 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.jobTitle1}} --- ( {{user_profile.jobStartDate1}} -\r\n {{user_profile.jobEndDate1}} ) </p>\r\n <p>{{user_profile.jobDescription1}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.jobTitle2 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.jobTitle2}} --- ( {{user_profile.jobStartDate2}} -\r\n {{user_profile.jobEndDate2}} ) </p>\r\n <p>{{user_profile.jobDescription2}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.jobTitle3 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.jobTitle3}} --- ( {{user_profile.jobStartDate3}} -\r\n {{user_profile.jobEndDate3}} ) </p>\r\n <p>{{user_profile.jobDescription3}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.jobTitle4 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.jobTitle4}} --- ( {{user_profile.jobStartDate4}} -\r\n {{user_profile.jobEndDate4}} ) </p>\r\n <p>{{user_profile.jobDescription4}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.jobTitle5 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.jobTitle5}} --- ( {{user_profile.jobStartDate5}} -\r\n {{user_profile.jobEndDate5}} ) </p>\r\n <p>{{user_profile.jobDescription5}} </p>\r\n\r\n {%endif%}\r\n\r\n {% if user_profile.projectTitle1 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.projectTitle1}} --- ( {{user_profile.projectStartDate1}} -\r\n {{user_profile.projectEndDate1}} ) </p>\r\n <p>{{user_profile.projectDescription1}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.projectTitle2 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.projectTitle2}} --- ( {{user_profile.projectStartDate2}} -\r\n {{user_profile.projectEndDate2}} ) </p>\r\n <p>{{user_profile.projectDescription2}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.projectTitle3 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.projectTitle3}} --- ( {{user_profile.projectStartDate3}} -\r\n {{user_profile.projectEndDate3}} ) </p>\r\n <p>{{user_profile.projectDescription3}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.projectTitle4 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.projectTitle4}} --- ( {{user_profile.projectStartDate4}} -\r\n {{user_profile.projectEndDate4}} ) </p>\r\n <p>{{user_profile.projectDescription4}} </p>\r\n\r\n {%endif%}\r\n {% if user_profile.projectTitle5 %}\r\n\r\n <p class=\"font-weight-bold\">{{user_profile.projectTitle5}} --- ( {{user_profile.projectStartDate5}} -\r\n {{user_profile.projectEndDate5}} ) </p>\r\n <p>{{user_profile.projectDescription5}} </p>\r\n\r\n {%endif%}\r\n\r\n {%endif%}\r\n\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-sm-4\">\r\n </div>\r\n <div class=\"col-sm-8\">\r\n\r\n {% if user_profile.areaOfInterest %}\r\n\r\n <hr class=\"hl\">\r\n <h4 class=\"py-3 vl px-2\">AREAS OF INTEREST</h4>\r\n <p>{{user_profile.areaOfInterest}} </p>\r\n\r\n {%endif%}\r\n\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-sm-4\">\r\n <p> </p>\r\n </div>\r\n\r\n <div class=\"col-sm-8\">\r\n\r\n {% if user_profile.extracurricularDetail %}\r\n\r\n <hr class=\"hl\">\r\n <h4 class=\"py-3 vl px-2\">EXTRA CURRICULAR ACTIVITIES</h4>\r\n <p>{{user_profile.extracurricularDetail}} </p>\r\n\r\n {%endif%}\r\n\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"col-md-2\">\r\n </div>\r\n </div>\r\n</div>\r\n\r\n{% endblock body %}" }, { "alpha_fraction": 0.5096510648727417, "alphanum_fraction": 0.5290482044219971, "avg_line_length": 31.56037139892578, "blob_id": "283ecb3cd08362be6562db7f0a9be442e357e2ed", "content_id": "37f4a2083e85b756c923fdb8d8553a41128ec285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10517, "license_type": "no_license", "max_line_length": 63, "num_lines": 323, "path": "/resumeBuilder/migrations/0011_auto_20210412_2001.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-12 14:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0010_auto_20210412_1845'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='profile',\n old_name='currentYear',\n new_name='currentYear1',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='degree',\n new_name='currentYear2',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='jobDescription',\n new_name='jobDescription1',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='jobTitle',\n new_name='jobDescription2',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='projectTitle',\n new_name='university2',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='jobEndDate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='jobStartDate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='projectDescription',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='projectEndDate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='projectStartDate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='stream',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='univPassingYear',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='univResult',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='univStartingYear',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='university',\n ),\n migrations.AddField(\n model_name='profile',\n name='degree1',\n field=models.CharField(blank=True, max_length=50),\n ),\n migrations.AddField(\n model_name='profile',\n name='degree2',\n field=models.CharField(blank=True, max_length=50),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobDescription3',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobDescription4',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobDescription5',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobEndDate1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobEndDate2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobEndDate3',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobEndDate4',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobEndDate5',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobStartDate1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobStartDate2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobStartDate3',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobStartDate4',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobStartDate5',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobTitle1',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobTitle2',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobTitle3',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobTitle4',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='jobTitle5',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription1',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription2',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription3',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription4',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription5',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate3',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate4',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate5',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate3',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate4',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate5',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectTitle1',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectTitle2',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectTitle3',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectTitle4',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectTitle5',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='stream1',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='stream2',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='univPassingYear1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='univPassingYear2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='univResult1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='univResult2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='univStartingYear1',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='univStartingYear2',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AddField(\n model_name='profile',\n name='university1',\n field=models.CharField(blank=True, max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.5357853174209595, "alphanum_fraction": 0.5611332058906555, "avg_line_length": 30.936508178710938, "blob_id": "c282da8e8736d9efb6c2a92bb5fe09fa4406ec71", "content_id": "cbecdbcb30b601b648b2f6f1e748b9b0d493e62e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2012, "license_type": "no_license", "max_line_length": 62, "num_lines": 63, "path": "/resumeBuilder/migrations/0008_auto_20210411_1620.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-11 10:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0007_auto_20210411_1616'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='highSchoolPassingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='highSchoolStartingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='intermediatePassingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='intermediateStartingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobEndDate',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobStartDate',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectEndDate',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectStartDate',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='univPassingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n migrations.AlterField(\n model_name='profile',\n name='univStartingYear',\n field=models.CharField(blank=True, max_length=20),\n ),\n ]\n" }, { "alpha_fraction": 0.5500338077545166, "alphanum_fraction": 0.5618661046028137, "avg_line_length": 31.866666793823242, "blob_id": "f59c445e7728347cf25b08efc050837a65ee1391", "content_id": "65b70e2b41926cf30f2ef53a9694d900a3287337", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2958, "license_type": "no_license", "max_line_length": 82, "num_lines": 90, "path": "/resumeBuilder/migrations/0005_auto_20210411_1252.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-11 07:22\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0004_auto_20210411_1030'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='profile',\n old_name='areaofinterest',\n new_name='areaOfInterest',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='extracurricular_detail',\n new_name='extracurricularDetail',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='passing_year',\n new_name='highSchoolPassingYear',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='starting_year',\n new_name='highSchoolStartingYear',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='language_detail',\n new_name='languageDetail',\n ),\n migrations.RenameField(\n model_name='profile',\n old_name='skill_detail',\n new_name='skillDetail',\n ),\n migrations.AddField(\n model_name='profile',\n name='currentYear',\n field=models.CharField(blank=True, max_length=5),\n ),\n migrations.AddField(\n model_name='profile',\n name='intermediatePassingYear',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='profile',\n name='intermediateStartingYear',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='profile',\n name='projectDescription',\n field=models.TextField(blank=True, max_length=100),\n ),\n migrations.AddField(\n model_name='profile',\n name='projectEndDate',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='profile',\n name='projectStartDate',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='profile',\n name='univPassingYear',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='profile',\n name='univStartingYear',\n field=models.DateField(blank=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5331388115882874, "alphanum_fraction": 0.5498124361038208, "avg_line_length": 29.756410598754883, "blob_id": "f4a9488ba5b5be654e02c5b08e141fd7adada7ca", "content_id": "3a06824f0f60e0f027f6200d504c2e989d6c1db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2399, "license_type": "no_license", "max_line_length": 63, "num_lines": 78, "path": "/resumeBuilder/migrations/0007_auto_20210411_1616.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-11 10:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0006_auto_20210411_1541'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='email',\n field=models.EmailField(max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='highSchoolPassingYear',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='highSchoolStartingYear',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='intermediatePassingYear',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='intermediateStartingYear',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobEndDate',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobStartDate',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='jobTitle',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectEndDate',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectStartDate',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='projectTitle',\n field=models.CharField(blank=True, max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='univPassingYear',\n field=models.DateTimeField(blank=True),\n ),\n migrations.AlterField(\n model_name='profile',\n name='univStartingYear',\n field=models.DateTimeField(blank=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6805845499038696, "alphanum_fraction": 0.6805845499038696, "avg_line_length": 38.08333206176758, "blob_id": "356ca50ce2f6bd9b1da5214d8e63d9664b60a574", "content_id": "5444997d4aedb682a9f80252b5adfc13151956a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 479, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/resumeBuilder/urls.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "from django.urls import path\r\nfrom resumeBuilder import views\r\n\r\nurlpatterns = [\r\n path('', views.index, name='index'),\r\n path('signup', views.signupPage, name='signupPage'),\r\n path('login', views.loginPage, name='loginPage'),\r\n path('logout', views.logoutPage, name='logoutPage'),\r\n path('viewResume', views.viewResume, name='viewResume'),\r\n path('addResume', views.addResume, name='addResume'),\r\n path('listResume', views.listResume, name='listResume'),\r\n]" }, { "alpha_fraction": 0.5233243703842163, "alphanum_fraction": 0.5445040464401245, "avg_line_length": 38.26315689086914, "blob_id": "18cc01a88083f1e6b637cd701e5f60a1447071ca", "content_id": "9116903490ede89227f5b5af0127cfce44878905", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3730, "license_type": "no_license", "max_line_length": 114, "num_lines": 95, "path": "/resumeBuilder/migrations/0004_auto_20210411_1030.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-11 05:00\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0003_contact'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('objective', models.CharField(blank=True, max_length=200)),\n ('address', models.CharField(max_length=200)),\n ('phoneno', models.CharField(max_length=12)),\n ('email', models.EmailField(max_length=254)),\n ('github', models.URLField(blank=True)),\n ('linkedin', models.URLField(blank=True)),\n ('university', models.URLField(blank=True, max_length=100)),\n ('degree', models.CharField(blank=True, max_length=50)),\n ('stream', models.CharField(blank=True, max_length=100)),\n ('starting_year', models.DateField(blank=True)),\n ('passing_year', models.DateField(blank=True)),\n ('univResult', models.CharField(blank=True, max_length=5)),\n ('intermediateSchool', models.CharField(blank=True, max_length=100)),\n ('intermediateSubjects', models.CharField(blank=True, max_length=100)),\n ('intermediateMarks', models.CharField(blank=True, max_length=15)),\n ('highSchool', models.CharField(blank=True, max_length=100)),\n ('highSchoolSubjects', models.CharField(blank=True, max_length=100)),\n ('highSchoolMarks', models.CharField(blank=True, max_length=15)),\n ('jobTitle', models.CharField(max_length=100)),\n ('projectTitle', models.CharField(max_length=100)),\n ('jobStartDate', models.DateField(blank=True)),\n ('jobEndDate', models.DateField(blank=True)),\n ('description', models.TextField(blank=True, max_length=100)),\n ('skill_detail', models.TextField(max_length=200)),\n ('language_detail', models.TextField(max_length=200)),\n ('areaofinterest', models.TextField(blank=True, max_length=100)),\n ('extracurricular_detail', models.TextField(blank=True, max_length=100)),\n ],\n ),\n migrations.RemoveField(\n model_name='areaofinterest',\n name='person',\n ),\n migrations.RemoveField(\n model_name='education',\n name='person',\n ),\n migrations.RemoveField(\n model_name='experience',\n name='person',\n ),\n migrations.RemoveField(\n model_name='extracurricular',\n name='person',\n ),\n migrations.RemoveField(\n model_name='languages',\n name='person',\n ),\n migrations.RemoveField(\n model_name='professionalskills',\n name='person',\n ),\n migrations.DeleteModel(\n name='Academics',\n ),\n migrations.DeleteModel(\n name='AreaOfInterest',\n ),\n migrations.DeleteModel(\n name='Education',\n ),\n migrations.DeleteModel(\n name='Experience',\n ),\n migrations.DeleteModel(\n name='ExtraCurricular',\n ),\n migrations.DeleteModel(\n name='Languages',\n ),\n migrations.DeleteModel(\n name='Person',\n ),\n migrations.DeleteModel(\n name='ProfessionalSkills',\n ),\n ]\n" }, { "alpha_fraction": 0.5206896662712097, "alphanum_fraction": 0.5810344815254211, "avg_line_length": 24.217391967773438, "blob_id": "c916cf528fd822b3c5bdc31f5183d3cbce773017", "content_id": "9bd5995763381cfddf56177d4acce8d411bce01e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 580, "license_type": "no_license", "max_line_length": 62, "num_lines": 23, "path": "/resumeBuilder/migrations/0010_auto_20210412_1845.py", "repo_name": "tusha28/Resume-Builder-master", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-12 13:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('resumeBuilder', '0009_auto_20210411_1623'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='currentYear',\n field=models.CharField(blank=True, max_length=50),\n ),\n migrations.AlterField(\n model_name='profile',\n name='univResult',\n field=models.CharField(blank=True, max_length=20),\n ),\n ]\n" } ]
12
gaosui/Biazza
https://github.com/gaosui/Biazza
3616643253fe68d65f2adac6c9468b06e800e4f6
465201dd1fb0ad1d86b08d9366468bb854fa3d72
11a93cbb194b7270f8b97cbda8c00d8c199eaef0
refs/heads/master
2020-04-01T05:19:42.982336
2020-03-26T22:33:15
2020-03-26T22:33:15
152,898,802
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7633135914802551, "alphanum_fraction": 0.7751479148864746, "avg_line_length": 32.900001525878906, "blob_id": "ddebe276d2ca3b22e33e13f0fd179157fac00882", "content_id": "209dffd9f197a87400d1dd99c7b944dd772ea565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 94, "num_lines": 10, "path": "/backend/save_model.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "from gensim.test.utils import get_tmpfile\nfrom gensim.models import KeyedVectors\n\nmodel = KeyedVectors.load_word2vec_format(\"./GoogleNews-vectors-negative300.bin\", binary=True)\nprint(\"finish loading start saving\")\nfname = \"vectors.kv\"\nmodel.save(fname)\nprint(\"reload\")\nword_vectors = KeyedVectors.load(\"vectors.kv\", mmap='r')\nprint(\"end\")" }, { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 54, "blob_id": "e09e30d4ecced057ea1a726790696b9e80bddbef", "content_id": "0b06649c010a2f547b92ce42d99ac57c473ba9d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 165, "license_type": "no_license", "max_line_length": 73, "num_lines": 3, "path": "/README.md", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "# Biazza - Better Piazza\nA chrome extension that augments the searching functionality of Piazza. \nGet better search results to avoid posting duplicated quaesitons.\n" }, { "alpha_fraction": 0.686985194683075, "alphanum_fraction": 0.7084019780158997, "avg_line_length": 22.346153259277344, "blob_id": "c6619bbc89b7d0050fed3a7c43f60da61754e070", "content_id": "1b42fc1792705361e7201df62ac9e0f5058dcfc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 95, "num_lines": 26, "path": "/backend/test.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "import json\nimport sys\nimport search\nfrom gensim.models import KeyedVectors\n\n#model = KeyedVectors.load_word2vec_format(\"./GoogleNews-vectors-negative300.bin\", binary=True)\nmodel = KeyedVectors.load(\"vectors.kv\", mmap='r')\n\nf = open('cache.json')\ncache = json.load(f)\nf.close()\n\n#for i in range()\ncids = list(cache['jml6wogpji0o3'].keys())\nposts = []\n\nfor i in cids:\n posts.append(cache['jml6wogpji0o3'][str(i)]['content'])\n\nsearch.setup()\nresults = search.predict(posts, cids, \"software\", model)\n\nprint(results)\n#for result in results:\n #print(cache['jml6wogpji0o3'][result]['content'])\n #print()\n" }, { "alpha_fraction": 0.5493975877761841, "alphanum_fraction": 0.5518072247505188, "avg_line_length": 23.899999618530273, "blob_id": "5d09231bce2fd4bc1fb643545530d09696799bf8", "content_id": "e7a9754498d22f7d20964e5b12e86322de415545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 62, "num_lines": 50, "path": "/backend/build_cache.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "from piazza_api import Piazza\nfrom html.parser import HTMLParser\nimport json\n\n\nclass MyParser(HTMLParser):\n def __init__(self):\n super().__init__(convert_charrefs=True)\n self.data = []\n\n def handle_data(self, d):\n self.data.append(d)\n\n def feed(self, d):\n super().feed(d + '<div>&nbsp;</div>')\n\n def get_data(self):\n return ''.join(self.data)\n\n\nf = open('settings.json')\nsettings = json.load(f)\nf.close()\n\np = Piazza()\np.user_login(settings['email'], settings['pwd'])\ncache = {}\n\nfor cl in settings['classes']:\n print(cl)\n net = p.network(cl)\n ls = {}\n for post in net.iter_all_posts():\n parser = MyParser()\n parser.feed(post['history'][0]['subject'])\n parser.feed(post['history'][0]['content'])\n for child in post['children']:\n if 'subject' in child:\n parser.feed(child['subject'])\n for cchild in child['children']:\n parser.feed(cchild['subject'])\n else:\n parser.feed(child['history'][0]['content'])\n post['content'] = parser.get_data().replace('\\n', ' ')\n ls[post['nr']] = post\n cache[cl] = ls\n\nf = open('cache.json', 'w')\njson.dump(cache, f)\nf.close()\n" }, { "alpha_fraction": 0.5580645203590393, "alphanum_fraction": 0.5659824013710022, "avg_line_length": 27.906780242919922, "blob_id": "36539031337adbdc7015f2c42e4299b905878362", "content_id": "116ce2d5650f93df15f5fd639cdccd947dd6bbeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3410, "license_type": "no_license", "max_line_length": 121, "num_lines": 118, "path": "/backend/search.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "import nltk\nfrom nltk.corpus import stopwords\nimport re\nimport numpy as np\nimport string\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom scipy.spatial.distance import cosine\nfrom gensim.models import KeyedVectors\nfrom gensim.test.utils import datapath\n\n\ndef setup():\n nltk.download('stopwords')\n nltk.download('punkt')\n\ndef tokenize_a_sentence(sentence):\n stop_words = set(stopwords.words('english'))\n \n sentence = sentence.strip()\n \n line_tokens = re.split(' |_|\\n',sentence) \n line_tokens = list(filter(lambda a: a != '', line_tokens))\n \n filtered= []\n for i in range(len(line_tokens)):\n token = line_tokens[i]\n \n if(token not in stop_words):\n \n for j in reversed(range(len(token))):\n if(token[j].isalpha() ):\n token = token[:j+1]\n break\n filtered.append(token)\n return filtered\n \n\ndef tokenize(docs):\n\n all_doc_tokens = []\n index = 0\n for doc in docs:\n tokens = []\n sentences = doc.lower().split(\". |, |; |\\n\")\n tokens = []\n for i in range(len(sentences)):\n tokens += tokenize_a_sentence(sentences[i])\n \n all_doc_tokens.append([index,tokens])\n index+=1\n\n\n return all_doc_tokens\n\ndef prepare_search(query):\n token_list = tokenize_a_sentence(query)\n return token_list\n \n\ndef predict(piazza_data, ids, query, model):\n list_of_lines = tokenize(piazza_data)\n corpus = []\n for text in list_of_lines:\n corpus.append(' '.join([l.rstrip().lower().translate(str.maketrans('','',string.punctuation)) for l in text[1]]))\n \n tfidf = TfidfVectorizer(tokenizer=nltk.word_tokenize, stop_words='english', min_df=1, max_df=0.8)\n tfs = tfidf.fit_transform(corpus)\n \n similarity = lambda u, v: 1-cosine(u, v)\n \n token_list = prepare_search(query)\n\n similar_keys = {}\n substring_keys = {}\n vocab = tfidf.vocabulary_\n\n for k in vocab.keys():\n for t in token_list:\n if(t in k and t != k):\n if(k not in substring_keys):\n substring_keys[k] = 1\n #token_list.append(k)\n if(k in model and k not in substring_keys and k not in token_list):\n if (t in model and similarity(model[k],model[t]) > 0.6 ):\n similar_keys[k] = 1\n \n similar_list = list(similar_keys.keys())\n search = ' '.join(token_list+similar_list)\n\n print(search)\n search_tf = tfidf.transform([search])\n\n\n cids = []\n sims = []\n\n for i, sim in enumerate(cosine_similarity(tfs, search_tf)):\n if(sim[0] > 0.1):\n cids.append(ids[i])\n sims.append(sim[0])\n\n if(len(cids) < 2):\n for i, sim in enumerate(cosine_similarity(tfs, search_tf)):\n if(sim[0] > 0.05):\n cids.append(ids[i])\n sims.append(sim[0])\n for sub in substring_keys.keys():\n sub_tf = tfidf.transform([sub])\n for i, sim in enumerate(cosine_similarity(tfs, sub_tf)):\n if(sim[0] > 0.05 and ids[i] not in cids):\n cids.append(ids[i])\n sims.append(sim[0])\n \n cids = np.asarray(cids)\n sims = np.asarray(sims)\n\n return reversed(cids[np.argsort(sims)])" }, { "alpha_fraction": 0.6633517742156982, "alphanum_fraction": 0.6677716374397278, "avg_line_length": 29.51685333251953, "blob_id": "5904afa1b29f9c42e620c2421e9edcfc0e111a3c", "content_id": "0579e5e791d65638cecf18846ab4557c0f78aec6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2715, "license_type": "no_license", "max_line_length": 119, "num_lines": 89, "path": "/extension/contentScript.js", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "console.log('hohohohohohohhoohoo')\nlet root = document.createElement('div')\nroot.classList.add('biazza')\ndocument.querySelector('#views').appendChild(root)\n\nlet bar = document.createElement('div')\nbar.classList.add('dashboard_toolbar', 'biazza_bbar')\nbar.textContent = 'Biazza'\nroot.appendChild(bar)\n\nlet ul = document.createElement('ul')\nroot.appendChild(ul)\n\n\nlet page_center = document.querySelector('#page_center')\nlet searchBox = document.querySelector('#search-box')\nlet keywordQueue = []\n// root.classList.add('active')\n// page_center.classList.add('active')\nsearchBox.addEventListener('input', e => {\n if (e.target.value) {\n keywordQueue.push(e.target.value)\n root.classList.add('active')\n page_center.classList.add('active')\n }\n else {\n root.classList.remove('active')\n page_center.classList.remove('active')\n }\n})\ndocument.querySelector('#my_classes').addEventListener('click', () => {\n root.classList.remove('active')\n page_center.classList.remove('active')\n})\ndocument.querySelector('#clear-search-button').addEventListener('click', () => {\n root.classList.remove('active')\n page_center.classList.remove('active')\n})\n\nfunction search() {\n if (!keywordQueue.length) return\n keyword = keywordQueue.pop()\n keywordQueue = []\n\n httpRequest = new XMLHttpRequest()\n httpRequest.onreadystatechange = () => {\n if (httpRequest.readyState === XMLHttpRequest.DONE) {\n if (httpRequest.status === 200) {\n while (ul.hasChildNodes()) {\n ul.removeChild(ul.firstChild)\n }\n for (node of JSON.parse(httpRequest.responseText)) {\n let li = document.createElement('li')\n li.classList.add('biazza_li')\n if (node.red) li.classList.add('red')\n li.dataset.nr = node.nr\n li.onclick = showPost\n let title = document.createElement('div')\n title.classList.add('title', 'ellipses')\n title.textContent = node.sub\n li.appendChild(title)\n let short = document.createElement('div')\n short.classList.add('short')\n short.textContent = node.short\n li.appendChild(short)\n ul.appendChild(li)\n }\n }\n }\n }\n httpRequest.open('GET', `http://localhost:3000/search?key=${keyword}&cid=${window.location.pathname.slice(7)}`, true)\n httpRequest.send()\n console.log(keyword)\n}\nsetInterval(search, 1000)\n\nfunction showPost(e) {\n event = document.createEvent('HTMLEvents')\n event.initEvent('keyup', true, true)\n let old = searchBox.value\n searchBox.value = '@' + this.dataset.nr\n searchBox.dispatchEvent(event)\n searchBox.value = old\n\n for (let li of ul.childNodes) {\n li.classList.remove('active')\n }\n this.classList.add('active')\n}" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 19, "blob_id": "7baefbbaa6db364b7cff4426d03b6d483f424856", "content_id": "f7da139be9168e06dcc7d503c8bfe250ff86cb68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60, "license_type": "no_license", "max_line_length": 36, "num_lines": 3, "path": "/backend/piazza_api/__init__.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "from piazza_api.piazza import Piazza\n\n__version__ = \"0.8.0\"\n" }, { "alpha_fraction": 0.5549890995025635, "alphanum_fraction": 0.5659140348434448, "avg_line_length": 24.90566062927246, "blob_id": "535707911e8190aa2c2d20ada1031012669f9486", "content_id": "b71342b004f253a9e0b81bfd6d187a88278ae848", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 60, "num_lines": 53, "path": "/backend/main.py", "repo_name": "gaosui/Biazza", "src_encoding": "UTF-8", "text": "from http.server import BaseHTTPRequestHandler, HTTPServer\nimport json\nimport sys\nimport urllib.parse as up\nfrom search import predict\nfrom gensim.models import KeyedVectors\n\nmodel = KeyedVectors.load(\"vectors.kv\", mmap='r')\nprint('model loaded')\n\nf = open('cache.json')\ncache = json.load(f)\nf.close()\nprint('cache loaded')\n\n\ndef buildDict(cid):\n nrs = []\n posts = []\n for k, v in cache[cid].items():\n nrs.append(k)\n posts.append(v['content'])\n return posts, nrs\n\n\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n args = up.parse_qs(self.path.split('?')[1])\n cid = args['cid'][0]\n\n posts, nrs = buildDict(cid)\n res = predict(posts, nrs, args['key'][0], model)\n objs = []\n for r in res:\n sub = cache[cid][r]['history'][0]['subject']\n short = cache[cid][r]['content'].lstrip(sub)\n short = short.lstrip(' ')\n objs.append({\n 'nr': r,\n 'sub': sub,\n 'short': short[0:120],\n 'red': 'unanswered' in cache[cid][r]['tags']\n })\n\n self.send_response(200)\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n self.wfile.write(json.dumps(objs).encode())\n return\n\n\nprint('start server')\nHTTPServer(('', 3000), Handler).serve_forever()\n" } ]
8
javirosa/particlecamp
https://github.com/javirosa/particlecamp
162de41597382919772ae04d09caf48534df3a3a
ce8a2ac9c56f4f633892818f26e3a165a59bd5d2
80388ac48efe88c3b28305e2f1d3a6f0663e06cd
refs/heads/master
2020-11-30T23:32:49.693490
2013-08-22T07:11:12
2013-08-22T07:11:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4765799343585968, "alphanum_fraction": 0.49814125895500183, "avg_line_length": 23.454545974731445, "blob_id": "6eeca099f45c1e0884d309e174d62d2bb6e50476", "content_id": "4454df24f84abff3c5d8e5ad624063a6f519c2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "no_license", "max_line_length": 113, "num_lines": 55, "path": "/PythonScripts/DAQ/DB/ReadUCPC_DB.py", "repo_name": "javirosa/particlecamp", "src_encoding": "UTF-8", "text": "import serial\nimport time\nimport psycopg2\n\nconn = psycopg2.connect(database='mydb', user='melissa', password='postgres')\ncur = conn.cursor()\nInsert = \"INSERT INTO ucpc (cpctime,Record,Mode,Flags,CN,ST,LT,CNT,PM,RP) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n\nser = serial.Serial('COM11', 115200, timeout=None);\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n \nwhile 1:\n Line = \"\"\n while ser.inWaiting() > 0:\n Line += ser.read();\n Line = Line.strip();\n\n if not Line:\n continue\n\n LineArray = Line.split(\",\")\n if len(LineArray) < 9:\n continue\n elif LineArray[0] != 'D':\n continue\n \n Count = 0\n for Item in LineArray:\n if Count == 0:\n Count += 1\n \n if is_number(Item):\n Count += 1\n \n if LineArray[0] == 'D' and Count == 9:\n Line = time.strftime(\"%Y-%m-%d %H:%M:%S\") + \",\" + \",\".join(LineArray)\n print \"CPC: \" + Line\n cur.execute(Insert, (time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n str(LineArray[0]),\n LineArray[1],\n LineArray[2],\n LineArray[3],\n LineArray[4],\n LineArray[5],\n LineArray[6],\n LineArray[7],\n LineArray[8])\n )\n conn.commit()\n" }, { "alpha_fraction": 0.6046379804611206, "alphanum_fraction": 0.6295248866081238, "avg_line_length": 31.127273559570312, "blob_id": "21c599077e7f90861335722bb422e1bdd1e61db5", "content_id": "291a1b83d88a21123be2e08c69c3709f1e01f45d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1768, "license_type": "no_license", "max_line_length": 99, "num_lines": 55, "path": "/PythonScripts/DAQ/ReadNeph.py", "repo_name": "javirosa/particlecamp", "src_encoding": "UTF-8", "text": "import serial\nimport time\nimport math\nimport os\n# Initially based on ReadAlicat\n# Neph output string: 4.460e-06 5.828e-04 1003 296 99 00\n# Column idenity: bscat (m-1), calibrator coef (,-1), pressure (mb), temp (K), RH (%), relay status\nDATADIR = os.path.join(os.path.curdir,\"Collected\")\nINSTR = 'Neph'\nser = serial.Serial('COM12', 9600, timeout=None);\n\nif not os.path.exists(DATADIR):\n os.makedirs(DATADIR)\nprint \"Data stored in:\\'%s\\'\"%(os.path.abspath(DATADIR))\nOutputName = time.strftime(\"Neph%Y%m%d_%H%M.csv\");\nOutputFile = open(os.path.join(DATADIR,OutputName), \"w\")\nOutputFile.write(\"Instr,Time\\n\")\n\ntoAvg = [] \nwhile 1:\n Line = ser.readline()\n LineArray = Line.split()\n values = (float(LineArray[0]),float(LineArray[1]))\n toAvg.append(values)\n if len(LineArray)<5:\n print \"Error an invalid number of lines was sent.\"\n elif math.floor(time.time())%60 == 0:\n avgVal = (sum(zip(*toAvg)[0])/len(toAvg),sum(zip(*toAvg)[1])/len(toAvg))\n timeStr = time.strftime(\"%Y-%m-%d %H:%M:%S\") \n toFile = \", \".join([INSTR,timeStr]+LineArray)\n display = \", \".join([INSTR,timeStr]+list(map(str,values)))\n print display\n #print zip(xrange(0,len(Line.split())),Line.split())\n OutputFile.write(toFile + \"\\n\")\n OutputFile.flush()\n toAvg=[]\n time.sleep(1)\nser.close()\nOutputFile.close()\n\n#Attempt at modularizing the code, don't worry about this for now\nclass Neph(object):\n def __init__(self, port):\n #Verify instrument on port\n pass\n def configureNeph(self,frequencyS=60):\n pass\n def readNeph(self):\n pass\n def registerListener(self,handler):\n pass\n def startPolling(self):\n pass\n def stopPolling(self):\n pass\n\n" }, { "alpha_fraction": 0.5650485157966614, "alphanum_fraction": 0.5873786211013794, "avg_line_length": 22.953489303588867, "blob_id": "80c51bca82c88632a19b48b9f1be6f110360028b", "content_id": "198a8a86dd329dc45a0e751fe789a46d0db914f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 104, "num_lines": 43, "path": "/PythonScripts/DAQ/DB/ReadAPI200A_DB.py", "repo_name": "javirosa/particlecamp", "src_encoding": "UTF-8", "text": "import serial\nimport time\nimport psycopg2\n\n\"\"\"\nThe database has 4 columns:\napitime\nno\nno2\nnox\n\nStore data from each read into the database so that we can query it\nlater.\n\"\"\"\nconn = psycopg2.connect(database='mydb', user='melissa', password='postgres')\ncur = conn.cursor()\nInsert = \"INSERT INTO api (apitime,no,no2,nox) VALUES (%s,%s,%s,%s)\"\n\nser = serial.Serial('COM3', 9600, timeout=None);\n\nCompounds = ['NO', 'NO2', 'NOX']\nResults = []\nwhile 1:\n ser.write(\"\\x03\\n\")\n \n for Compound in Compounds:\n ser.write(\"T {}\\n\".format(Compound))\n Line = ser.readline()\n LineArray = Line.split()\n LineArray = LineArray[3].split('=')\n Results.append(LineArray[1])\n \n \n print \"API:{},{},{},{}\".format(time.strftime(\"%Y-%m-%d %H:%M:%S\"),Results[0],Results[1], Results[2])\n cur.execute(Insert, (\n time.strftime(\"%Y-%m-%d %H:%M:%S\"), \n float(Results[0]), float(Results[1]), \n float(Results[2]))\n )\n conn.commit()\n\n Results = []\n time.sleep(1)\n" }, { "alpha_fraction": 0.8024691343307495, "alphanum_fraction": 0.8024691343307495, "avg_line_length": 39.5, "blob_id": "f7df835e84aed9f7595678f8115049ac4037b095", "content_id": "d1925398c5c790ca85a7d6ab0dfa782361f36f91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 81, "license_type": "no_license", "max_line_length": 50, "num_lines": 2, "path": "/backend/TODO.txt", "repo_name": "javirosa/particlecamp", "src_encoding": "UTF-8", "text": "Add reset routine if the thing keeps on timing out\nAdd live view of reading rows\n" }, { "alpha_fraction": 0.5893254280090332, "alphanum_fraction": 0.610822856426239, "avg_line_length": 29.659090042114258, "blob_id": "d6c7cb0f20cdb4a6e678bca60cc1abcb706ac905", "content_id": "3607c070a91884a07437152e27a45abdbd91c987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license_type": "no_license", "max_line_length": 123, "num_lines": 44, "path": "/PythonScripts/DAQ/.svn/text-base/ReadMetOne_DB.py.svn-base", "repo_name": "javirosa/particlecamp", "src_encoding": "UTF-8", "text": "import serial\nimport psycopg2\nimport time\n\nser = serial.Serial('COM9', 9600, timeout=None)\nconn = psycopg2.connect(database='mydb', user='melissa', password='postgres')\ncur = conn.cursor()\n\nInsert = \"INSERT INTO metone (metonetime,metone03,metone05,metone07,metone1,metone2,metone5) VALUES (%s,%s,%s,%s,%s,%s,%s)\"\n\nwhile 1:\n #Check to see if the instrument is logging data. Command to send\n #is OP\\r. If the instrument is not logging, it will return OP S.\n #If the instrument is running, it will return OP R #. I believe\n #the # is the number of seconds that the instrument has been running.\n ser.write(\"OP\\r\")\n \n line = ser.readline() #It sends out extra info we don't need so call twice.\n line = ser.readline() #This is the one we need.\n LineArray = line.split()\n \n #Check to see if the instrument is running\n if LineArray[1] == 'S':\n ser.write(\"S\\r\")\n time.sleep(1)\n continue\n \n line = ser.readline()\n\n LineArray = line.split(',')\n if len(LineArray) != 20:\n continue\n \n print \"MetOne:\" + line\n cur.execute(Insert, (time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n int(LineArray[2]),\n int(LineArray[4]),\n int(LineArray[6]),\n int(LineArray[8]),\n int(LineArray[10]),\n int(LineArray[12]))\n )\n \n conn.commit()\n" } ]
5
panshao521/ProcessThreadCoroutines
https://github.com/panshao521/ProcessThreadCoroutines
616040c6f8fd8bdea7ce458fc39411875eb7e3c2
6107a3cce84eb3b4b6c86f4a0fbc0ce6752bc588
9090634637c561eb0f12213a0e8f6d40b94331d1
refs/heads/master
2023-02-14T04:25:31.319614
2021-01-13T15:40:23
2021-01-13T15:40:23
329,353,485
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.494226336479187, "alphanum_fraction": 0.4996151030063629, "avg_line_length": 23.50943374633789, "blob_id": "f6a8c7c2b5cd8e0d87b558a40b073c576531e6b1", "content_id": "ede0c93fb7ad5cc328bd7dd2e4c03f72fa5ccdfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 64, "num_lines": 53, "path": "/thread_coroutines.py", "repo_name": "panshao521/ProcessThreadCoroutines", "src_encoding": "UTF-8", "text": "#--coding:utf-8--\nfrom gevent import monkey;\nimport gevent\nmonkey.patch_all()\nfrom threading import Thread\nimport queue\nimport requests\nimport time\n\ndef crawl(url,i):\n try:\n r = requests.get(url,timeout = 3)\n print(\"我是第%s个【线程+协程】\" %i,url,r.status_code)\n except Exception as e:\n print(e)\n\ndef task_gevent(queue,i):\n url_list = []\n while not queue.empty():\n url = queue.get()\n url_list.append(url)\n if len(url_list) == 250:\n tasks = []\n for url in url_list:\n tasks.append(gevent.spawn(crawl,url,i))\n gevent.joinall(tasks)\n return\n\nif __name__ == '__main__':\n queue = queue.Queue()\n urls = []\n with open(\"d:\\\\urls.txt\") as fp:\n for url in fp:\n urls.append(url.strip())\n print(\"一共%s个url\" % len(urls))\n for url in urls:\n queue.put(url)\n\n start = time.time()\n print(\"**********************开始计时**********************\")\n t_list = []\n for i in range(1,5):\n t = Thread(target=task_gevent, args=(queue,i)) #多进程 + 协程\n t.start()\n t_list.append(t)\n print(t)\n for p in t_list:\n p.join()\n print(p)\n\n end = time.time()\n print(\"**********************结束计时**********************\")\n print(\"总耗时:\",end - start)\n" }, { "alpha_fraction": 0.47233203053474426, "alphanum_fraction": 0.47628459334373474, "avg_line_length": 23.707317352294922, "blob_id": "675316b4dc5bce98fb4ccb7a9b9d13598b5c2a1b", "content_id": "14f84829f5e395443d234acc7ca78963dfc6414e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 61, "num_lines": 41, "path": "/thread_only.py", "repo_name": "panshao521/ProcessThreadCoroutines", "src_encoding": "UTF-8", "text": "#--coding:utf-8--\nfrom threading import Thread\nimport queue\nimport requests\nimport time\n\ndef crawl_process(queue,i):\n while not queue.empty():\n try:\n url = queue.get()\n r = requests.get(url,timeout = 3)\n print(\"我是第%s个【线程】\" %i,url,r.status_code)\n except Exception as e:\n print(e)\n return\n\n\nif __name__ == '__main__':\n queue = queue.Queue()\n urls = []\n with open(\"d:\\\\urls.txt\") as fp:\n for url in fp:\n urls.append(url.strip())\n print(\"一共%s个url\" %len(urls))\n for url in urls:\n queue.put(url)\n\n start = time.time()\n print(\"**********************开始计时**********************\")\n t_list = []\n for i in range(1,5):\n t = Thread(target=crawl_process, args=(queue,i)) #多进程\n t_list.append(t)\n t.start()\n print(t)\n for t in t_list:\n t.join()\n print(t)\n end = time.time()\n print(\"**********************结束计时**********************\")\n print(\"总耗时:\",end - start)" } ]
2
ahameden/Utils
https://github.com/ahameden/Utils
8826f0f91671ae6728e404d682aa166856b22514
82f725a4bfeae8e85d63e2bea7c02ff504a8a4ab
c22afcddec52872aa6e7930a0c37aae02abd3f51
refs/heads/master
2017-10-07T18:15:15.274807
2017-02-10T22:04:47
2017-02-10T22:04:47
81,403,521
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5472221970558167, "alphanum_fraction": 0.6138888597488403, "avg_line_length": 24.64285659790039, "blob_id": "22830ad1ad63407f7412f56b25a2682a5bbcf796", "content_id": "c9b45671d4eb6e1824e3ba79a182a04c994e7a40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 96, "num_lines": 14, "path": "/ipv6_subnet.py", "repo_name": "ahameden/Utils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#\n# Ahamed EN ([email protected])\n# ahameden/Utils\n# Convert subnet from 120 -> ffff.ffff.ffff.ffff.ffff.ffff.ffff.ff00\n#\n\nimport sys\nval = []\nmask = 128 if len(sys.argv) < 2 else int(sys.argv[1])\nfor i in range(0,8):\n val.append(format(((0xffffffff << (32-( 16 if mask>16 else mask)) >> 16 ) & 0xffff ) , 'x'))\n mask -= 16\nprint \":\".join(val)\n\n" }, { "alpha_fraction": 0.5205047130584717, "alphanum_fraction": 0.5962145328521729, "avg_line_length": 20.066667556762695, "blob_id": "8fed055a80ddb58d5375774ea11c85beb4631f56", "content_id": "c744da4e91da9d44e885a2f2287eda488f7930e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 317, "license_type": "no_license", "max_line_length": 52, "num_lines": 15, "path": "/ipv4_subnet.py", "repo_name": "ahameden/Utils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#\n# Ahamed EN ([email protected])\n# ahameden/Utils\n# Convert subnet from 24 -> 255.255.255.0\n#\n\nimport sys\nval = []\nmask = 32 if len(sys.argv) < 2 else int(sys.argv[1])\nfor i in range(0,4):\n shift = 8 if mask>8 else mask\n val.append(str((0xff << (8-shift) & 0xff)))\n mask -= 8\nprint \".\".join(val)\n\n" }, { "alpha_fraction": 0.7476635575294495, "alphanum_fraction": 0.7476635575294495, "avg_line_length": 25.5, "blob_id": "43d31e30b6f9ca830aa8682e5745b18bf138bfc2", "content_id": "51b78ee0ff98b1f33d2cac3348260d5e1de7539f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 107, "license_type": "no_license", "max_line_length": 52, "num_lines": 4, "path": "/README.md", "repo_name": "ahameden/Utils", "src_encoding": "UTF-8", "text": "# Utils\n\nUtililty programs which I use now and then.\nBefore I used to just code and forget it or lose it.\n\n" }, { "alpha_fraction": 0.5244755148887634, "alphanum_fraction": 0.5244755148887634, "avg_line_length": 10.583333015441895, "blob_id": "43db50ef08da5f0cb413ae2eb3b144f56fc46ca0", "content_id": "58f61b3f248a6257819fe3a8788d8e0c0d62eaea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 143, "license_type": "no_license", "max_line_length": 34, "num_lines": 12, "path": "/merge_sort/Makefile", "repo_name": "ahameden/Utils", "src_encoding": "UTF-8", "text": "\n\nMODULE=merge\n\nCC=gcc\nCFLAGS=-I.\n\nSRC=$(wildcard *.c)\n\n$(MODULE): $(SRC)\n\tgcc -o $@ $^ $(CFLAGS)\n\nclean:\n\trm -f $(PWD)/$(MODULE) $(PWD)/*.o \n\n" }, { "alpha_fraction": 0.43478259444236755, "alphanum_fraction": 0.4775595963001251, "avg_line_length": 11.837838172912598, "blob_id": "6a8c7c4b0f6f2f7841049aa45f7586634f6ccd5c", "content_id": "139362b1165bd4df308252748ea548641a82b77c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 58, "num_lines": 111, "path": "/merge_sort/merge.c", "repo_name": "ahameden/Utils", "src_encoding": "UTF-8", "text": "#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n#include \"time.h\"\n\ntypedef enum _return_type\n{\n ERROR,\n SUCCESS\n}return_type_t;\n\n#define NULL_CHECK(x) { if(!x) return ERROR; }\n\nstatic int merge(int *a1, int n1, int *a2, int n2, int *a)\n{\n\n int i=0, j=0, k=0;\n\n\n while(i<n1 && j<n2){\n if(a1[i] <= a2[j]){\n a[k] = a1[i];\n i++;\n }\n else{\n a[k] = a2[j];\n j++;\n }\n k++;\n }\n\n while(i<n1){\n a[k] = a1[i];\n i++;\n k++;\n }\n\n while(j<n2){\n a[k] = a2[j];\n j++;\n k++;\n }\n return SUCCESS;\n}\n\nstatic int merge_sort(int *a, int m)\n{\n int *a1, *a2;\n int n1, n2;\n\n if(m<2) return SUCCESS;\n\n n1 = m >> 1;\n n2 = m - n1;\n\n a1 = malloc(sizeof(int) * n1);\n NULL_CHECK(a1);\n a2 = malloc(sizeof(int) * n2);\n NULL_CHECK(a2);\n\n int i=0;\n for(i=0; i<n1; i++)\n a1[i] = a[i];\n\n for(i=0; i<n2; i++)\n a2[i] = a[i+n1];\n\n merge_sort(a1, n1);\n merge_sort(a2, n2);\n\n merge(a1, n1, a2, n2, a);\n free(a1);\n free(a2);\n\n return 0;\n\n}\n\nstatic void display(int *a, int n)\n{\n int i;\n for(i=0; i<n; i++){\n printf(\"%d \", a[i]);\n }\n printf(\"\\n\");\n return;\n}\n\nint main(int argc, char **argv)\n{\n int *a;\n int i,n,num;\n\n scanf(\"%d\", &n);\n a = malloc(sizeof(int) * n);\n NULL_CHECK(a);\n\n srand ( time(NULL) );\n\n for(i=0; i<n; i++){\n num = rand() %100000 + 1;\n a[i] = num;\n }\n\n display(a, n);\n merge_sort(a, n);\n display(a, n);\n\n free(a);\n return 0;\n}\n\n" } ]
5
Aastha-520609/python_learning
https://github.com/Aastha-520609/python_learning
cd5d31640568ff9c6b347bb943647982063dcf1e
d948dd1881b0a781aa5fde608060679a9faec00d
19499fb1a31748c5ad4794b6ea1741a6500c0654
refs/heads/master
2023-02-24T14:53:04.845158
2021-01-22T19:11:45
2021-01-22T19:11:45
332,039,168
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6788194179534912, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 27.25, "blob_id": "06b1dca2316277e19ade91653a391d8021633e96", "content_id": "012bdb976169fc68ccb4c68dc4e6028226073ac0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 79, "num_lines": 20, "path": "/dictionarie.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "dict={}#creating a dictionary\ndict['apple']= 150#assigning key to the dict and the value\ndict['banana']=60\ndict\nprint(dict)\n\n#another way to create a dictionary\nmail_adress={'aastha':'[email protected]','pasta':'[email protected]'}\nprint(mail_adress)\nprint(mail_adress.keys())#to print keys of dictionary\nprint(mail_adress.values())#to print values of dictionary\n\n\n#creating dict with the help of list\na=[1,2,3,4]\nb=['cat','dog','mouse','rat']\nmy_dict={}#empty dict\nfor i in range(len(a)):#here we can use any ones lenght because length is equal\n my_dict[a[i]]=b[i]\nprint(my_dict)\n\n \n\n\n\n\n\n" }, { "alpha_fraction": 0.6652977466583252, "alphanum_fraction": 0.6673511266708374, "avg_line_length": 21.952381134033203, "blob_id": "3824224c310f13b7111a425b7fad23adbadb58ee", "content_id": "f444d983be746bb88a6cfcdf69bacdf2e6b88499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 487, "license_type": "no_license", "max_line_length": 43, "num_lines": 21, "path": "/file handling.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\n\n\"\"\"textfile=open(\"text.txt\",'w')\ntextfile.write(\"Hello people\")\ntextfile.close()\"\"\"\n\n\"\"\"textfile=open(\"text.txt\",'a')\ntextfile.write(\" How are you?\")\ntextfile.write(\"\\n All good?\")\ntextfile.write(\"\\nWhat are you doing now?\")\ntextfile.close()\"\"\"\n\n\"\"\"textfile=open(\"text.txt\",'r')\nprint(textfile.read())\ntextfile.close()\"\"\"\n\n\"\"\"textfile=open(\"text.txt\",'r')\nprint(textfile.readline())\ntextfile.close()\"\"\"\n\ntextfile=open(\"text.txt\",'r')\nprint(textfile.readlines(-1))\ntextfile.close()\n\n\n\n" }, { "alpha_fraction": 0.54347825050354, "alphanum_fraction": 0.5797101259231567, "avg_line_length": 28.11111068725586, "blob_id": "d9c73335147da36211d5a89791793edc82647bab", "content_id": "bfc2e8b2644ce94e7c917491a15db4d8a437117e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 64, "num_lines": 9, "path": "/hello world.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\nlist=[10,20,3,4,32,45]\nkeyword=int(input(\"Enter the element which is to be searched:\"))\nfor i in range(len(list)):\n if list[i] == keyword:\n print(\"keyword is matched\")\n print(\"index:\",i)\n break\nelse:\n print(\"Element is not matched\")\n \n \n" }, { "alpha_fraction": 0.6933514475822449, "alphanum_fraction": 0.7069199681282043, "avg_line_length": 29.20833396911621, "blob_id": "641344021debd6f2c47dd842e287c0cf19619acc", "content_id": "f114f057caa5928cca722c94b090419736ab8edd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 737, "license_type": "no_license", "max_line_length": 77, "num_lines": 24, "path": "/basic_operationD.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "#Basic operations in dictionaries\nmy_dict={1:'apple',2:'ball',3:'cat'}\nprint(my_dict)\nnumbers=dict(my_dict)#copying to another dictionary\nprint(numbers)\nprint(len(numbers))#printing length of dict\ndel numbers[2]#deleting the dictionary element\nprint(numbers)\nprint(my_dict.keys())\nprint(my_dict.values())\nprint(my_dict[3])#in dictionary we can excess key using value but we cannot\n #excess values value using key.so for this we can do it with\n #get function\nprint(my_dict.get(1))\n#insert new value to dictionary\nmy_dict[4]=\"dog\"\nprint(my_dict)\n#updating the actual value\nmy_dict[2]='parrot'\nprint(my_dict)\n# concatination in dict\ndict={5:'orange',6:'pine'}\nmy_dict.update(dict)\nprint(my_dict)\n\n\n \n\n\n\n" }, { "alpha_fraction": 0.43718594312667847, "alphanum_fraction": 0.45728641748428345, "avg_line_length": 19.421052932739258, "blob_id": "6324ccfaf72cd7d0e41e2b0efaf6348dd3c99856", "content_id": "ad366d321e8fa74c9e75c82f7ed65f6b91dc3e09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 37, "num_lines": 19, "path": "/Bubble sort.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\nl=[]\nn=int(input(\"Enter the no of list:\"))\nnum=0\ntemp=0\nfor i in range(0,n):\n num=int(input())\n l.append(num)\nprint(\"unsorted list\",l)\nfor j in range (len(l)-1):\n for i in range(len(l)-1-j):\n if l[i]>l[i+1]:\n temp=l[i]\n l[i]=l[i+1]\n l[i+1]=temp\n print(l)\n else:\n print(l)\n print() \nprint(\"sorted list\",l)\n " }, { "alpha_fraction": 0.5028901696205139, "alphanum_fraction": 0.5173410177230835, "avg_line_length": 17.66666603088379, "blob_id": "2a17041ebd6a987446ca1b4cd066f125d4f0b9f2", "content_id": "1b66aa9eb71fe599a8b04e3846814adbca283290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 34, "num_lines": 18, "path": "/DNA sequence.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\nstring=input()\nset1=set(string)\nset2=set({'A','C','T','G'})\nif (len(string)>0 and set1==set2):\n a=string.count('A')\n t=string.count('T')\n g=string.count('G')\n c=string.count('C')\n print(\"A\")\n print(a)\n print(\"T\")\n print(t)\n print(\"C\")\n print(c)\n print(\"G\")\n print(g)\nelse:\n print(\"Invalid input\")\n \n " }, { "alpha_fraction": 0.3089887499809265, "alphanum_fraction": 0.4101123511791229, "avg_line_length": 17.88888931274414, "blob_id": "535d29c83e7f2d27faff66223c1c3cc74dc66dff", "content_id": "0239fa8b7b7ea8b496793b9bace6e4a8049e4a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/insertion sort.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "l=[1,5,32,67,34,58,98]\nfor i in range(1,len(l)):\n j=i\n while j>=0 and l[j-1]>l[j]:\n temp=l[j-1]\n l[j-1]=l[j]\n l[j]=temp\n j=j-1\nprint(l)\n " }, { "alpha_fraction": 0.5752577185630798, "alphanum_fraction": 0.6144329905509949, "avg_line_length": 23.578947067260742, "blob_id": "afd7ac9963badb786f376158de1aa8d16211839e", "content_id": "c961ce32f179fbf1e9de42e8b9bc7c2d7d61b7f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 61, "num_lines": 19, "path": "/Binary search.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\nlist=[10,20,5,9,43,56,23,45]\nlist.sort()\nkeyword=int(input(\"Enter the keyword which is to be found:\"))\nfirst=0\nlast=len(list)-1\nFound=False\nwhile first<=last and not Found:\n middle_value=(first+last)//2 \n if keyword==list[middle_value]:\n Found=True\n elif keyword>list[middle_value]:\n first=middle_value+1 \n else:\n last=middle_value-1\n \nif Found==True:\n print(\"keyword is found\")\nelse:\n print(\"keyword is not found\")\n \n " }, { "alpha_fraction": 0.5230125784873962, "alphanum_fraction": 0.5648535490036011, "avg_line_length": 15.785714149475098, "blob_id": "cf5af77be57f7b79540b01ff05cff7214aa155d7", "content_id": "30a0401d9ce3be5c03faaa1d930030cf4fb1554a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/untitled2.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\n\"\"\"n=int(input(\"Enter a binary number:\"))\nrem=1\ni=0\nd=0\nwhile n>0:\n rem=n%10\n d=d+rem*pow(2,i)\n n=int(n/10)\n i=i+1\nprint(\"The decimal number is\",d)\"\"\"\n\nn=int(input(\"Enter a binary numbeer:\")\nnum=dec(n) \nprint(num)\n\n\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 20.44444465637207, "blob_id": "1d71a16004177155783d007a397a805263a6a0aa", "content_id": "1ef0c95e43cb33275c0eb2f7c2bfb60819b8d252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/selection sort.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\nl=[34,65,3,67,98,32]\nprint(\"unsorted list\",l)\nfor i in range(len(l)):\n min_value=min(l[i:])\n min_ind=l.index(min_value)\n temp=l[i]\n l[i]=l[min_ind]\n l[min_ind]=temp\n print(l)\n " }, { "alpha_fraction": 0.5612813234329224, "alphanum_fraction": 0.5947075486183167, "avg_line_length": 24.535715103149414, "blob_id": "5ff5839c2d3a26c189cc9f9de0cce70e4accbecd", "content_id": "57c65f427a56c25d829c2516c7f66ce12e11dc0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 718, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/linear search.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "#if no duplicate value is present\n\"\"\"list=[10,20,3,4,32,45]\nkeyword=int(input(\"Enter the element which is to be searched:\"))\nfor i in range(len(list)):\n if list[i] == keyword:\n print(\"keyword is matched\")\n print(\"index:\",i)\n break\nelse:\n print(\"Element is not matched\")\"\"\"\n \n \n#if duplicate value is present\nlist=[10,20,3,4,32,45,3]\nlist1=[]\nflag=False\nkeyword=int(input(\"Enter the element which is to be searched:\"))\nfor i in range(len(list)):\n if list[i] == keyword:\n flag=True\n list1.append(i)\nif flag==True:\n print(\"Keywords are present at index:\") \n for i in list1:\n print(i) \n \nelse:\n print(\"Element is not matched\")\n " }, { "alpha_fraction": 0.47488585114479065, "alphanum_fraction": 0.5220699906349182, "avg_line_length": 16.735294342041016, "blob_id": "6bde090b1c75b96100d4fcdf9124488840686933", "content_id": "f5eff5739734db6bae13911dda645f7f5b48b2af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 46, "num_lines": 34, "path": "/list.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\"\"\"b=[]\na=list(map(int,input(\"Enter no:\").split(\" \")))\nb.extend(a)\nprint(b)\"\"\"\n#To add all the items in a list\n\"\"\"l=[1,2,3]\nsum=0\nfor i in l:\n sum=sum+i\nprint(sum)\"\"\"\n#To multiply all the items in a list\n\"\"\"l=[1,2,3]\nmul=1\nfor i in l:\n mul=mul*i\nprint(mul)\"\"\"\n#Largest and smallest number from a list\n\"\"\"l=[24,12,56]\nprint(l)\nl.sort()\nprint(l)\nprint(l[-1])\nprint(l[0])\"\"\"\n\"\"\"l=['abc','1221','abc','bab']\ncount=0\nfor i in l:\n if len(i)>1 and i[0]==i[-1]:\n count=count+1\nprint(count)\"\"\"\n#remove duplicates from the list\nl=[4,3,5,6,3]\nfor i in len(l):\n if l[i]=l[i+1]:\n print(i)\n \n \n \n \n \n\n\n\n \n \n\n\n" }, { "alpha_fraction": 0.4886363744735718, "alphanum_fraction": 0.5539772510528564, "avg_line_length": 12.037036895751953, "blob_id": "71664bbb34f73828abe5478c07895d1a5e71f2b4", "content_id": "649495eab3e6b1a6c5882df5a7ffb02ea4c954f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "no_license", "max_line_length": 35, "num_lines": 27, "path": "/swap float que.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 30 23:19:53 2020\n\n@author: Nageshwor\n\"\"\"\n\nn=float(input())\ntemp=1\nwhile(True):\n if(n//temp==0):\n break\n else:\n temp=temp*10\n\nnew_num=int(n)/temp\ntemp=10\n\nwhile(True):\n if((n*temp)%1==0):\n break\n else:\n temp=temp*10\n\nn=n-int(n)\nnew_num=new_num+temp*n\nprint(new_num)\n" }, { "alpha_fraction": 0.46722689270973206, "alphanum_fraction": 0.4848739504814148, "avg_line_length": 18.879310607910156, "blob_id": "df4ea192d42a8b5fa3fcce714feee8826af82887", "content_id": "4af6d4fd55ae210965b754dc8a173f900e64ce2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1190, "license_type": "no_license", "max_line_length": 49, "num_lines": 58, "path": "/matrix.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "\n\"\"\"R=int(input(\"Enter no of rows:\"))\nC=int(input(\"Enter no of coloumn:\"))\nmatrix1=[]\nfor i in range(R):\n a=[]\n for j in range(C):\n num=int(input())\n a.append(num)\n matrix1.append(a)\nfor i in range(R):\n for j in range(C):\n print(matrix1[i][j],end=\" \")\n print()\"\"\"\n \n \n \n \nR=int(input(\"Enter no of rows:\"))\nC=int(input(\"Enter no of coloumn:\"))\nprint(\"matrix1\") \nmatrix1=[]\nfor i in range(R):\n a=[]\n for j in range(C):\n num=int(input())\n a.append(num)\n matrix1.append(a)\nfor i in range(R):\n for j in range(C):\n print(matrix1[i][j],end=\" \")\n print()\n \nprint(\"matrix2\") \nmatrix2=[]\nfor i in range(R):\n a=[]\n for j in range(C):\n num=int(input())\n a.append(num)\n matrix2.append(a)\nfor i in range(R):\n for j in range(C):\n print(matrix2[i][j],end=\" \")\n print()\n \nprint(\"matrix3\") \nmatrix3=[[0,0],\n [0,0]]\n \n\nfor i in range(R):\n for j in range(C):\n matrix3[i][j]=matrix1[i][j]+matrix2[i][j]\n \nfor i in range(R):\n for j in range(C):\n print(matrix3[i][j],end=\" \")\n print()\n \n \n \n \n " }, { "alpha_fraction": 0.5916954874992371, "alphanum_fraction": 0.6539792418479919, "avg_line_length": 21, "blob_id": "614c0f112426401635c07b68d11db29b7208a19a", "content_id": "f8f1cdcd5e82053415cae2d16ada0d2aa350d064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 49, "num_lines": 13, "path": "/setspractice.py", "repo_name": "Aastha-520609/python_learning", "src_encoding": "UTF-8", "text": "#creating a set\nset={1,2,3,4}\nprint(set)\nset1={'apple','ball','cat'}\nprint(set1)\nset2={'apple','dog'}|set1#union(|) of set sign\nprint(set2)\nset2={'apple','dog'}&set1#intersection (&) of set\nprint(set2)\nset2=set1-{'apple'}#diff(-)\nprint(set2)\nset2=set1>{'apple'}#superset(>)\nprint(set2)\n\n\n\n" } ]
15
harrisonford/myPoCs
https://github.com/harrisonford/myPoCs
316456338b07fa20150d1aa969c39417beff2fb0
b584444be1418fd7153a54766f049211396bb870
adda07a0d759bd45efca6b49c584eae860011576
refs/heads/main
2023-04-17T00:24:10.388096
2021-04-29T15:07:04
2021-04-29T15:07:04
334,198,774
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6231182813644409, "alphanum_fraction": 0.6354838609695435, "avg_line_length": 34.09434127807617, "blob_id": "79bd587b0b64074bba37628d2a01aba5dac5e861", "content_id": "c4a39b61d237d8c00c8ca86f3047840df8e0074b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1860, "license_type": "permissive", "max_line_length": 90, "num_lines": 53, "path": "/AudioData/DataLoader.py", "repo_name": "harrisonford/myPoCs", "src_encoding": "UTF-8", "text": "from pytube import YouTube\nfrom pydub import AudioSegment\n\n\n# Import Youtube videos along with captions\ndef yt_import(url, filename=None, f_out='', captions=None, verbose=False):\n yt = YouTube(url)\n if not filename: # we put the title as filename\n filename = yt.title\n\n if verbose:\n print(f'yt_import: Downloading {url} as {filename}.mp4.')\n yt.streams\\\n .filter(progressive=True, file_extension='mp4')\\\n .order_by('resolution')\\\n .desc().first()\\\n .download(output_path=f_out, filename=filename)\n\n if captions: # download wanted captions\n for caption in captions:\n text = yt.captions[caption]\n if text:\n if verbose:\n print(f'yt_import: Found caption {caption}, saving file.')\n with open(f'{filename}_{caption}.txt', \"w\") as text_file:\n text_file.write(text.generate_srt_captions())\n return\n\n\ndef convert_audio(file, extension, bitrate, verbose=False):\n sample = AudioSegment.from_file('Caroe.mp4', format=extension)\n print(sample)\n return\n\n\n# Test Loader capabilities\nif __name__ == '__main__':\n\n # Enable debugging messages from functions\n debug = True\n\n # Test Youtube Importer we use this function to raise a Database from scratch\n print('Starting Loading Tests...')\n test_url = 'https://www.youtube.com/watch?v=eEOhx-u9Z2k' # url to load\n fname = 'Caroe' # base name of the output\n caption_list = ['a.es', 'es-419'] # we use autogenerated (a.es) and manually (es-419)\n yt_import(test_url, filename='Caroe', captions=['a.es', 'es-419'], verbose=debug)\n print('Loading done!')\n\n # Test Audio libraries: Transforming to 16kHz\n print('Starting Audio converter...')\n convert_audio('Caroe.mp4', 'mp4', 16000, verbose=debug)\n print('Converting done!')\n" }, { "alpha_fraction": 0.7758620977401733, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 28, "blob_id": "413c46cb04a0abbaf0019d31a856eaa54c209eea", "content_id": "45cfd1bebdb2733825c3f5011b5694d4a159ac5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "permissive", "max_line_length": 48, "num_lines": 2, "path": "/README.md", "repo_name": "harrisonford/myPoCs", "src_encoding": "UTF-8", "text": "# myPoCs\nInteresting ML Proof of Concepts I'm working on.\n" } ]
2
hanjie1992/python_machine_learning
https://github.com/hanjie1992/python_machine_learning
25635edabaace8c9dd4f2afbc7c5a76a64181425
4bd0fa46b0f0ca2441e3225683dc9412e7ffce6c
49e2d19d943ef5e1196ca37591536228fcc4a6fe
refs/heads/master
2023-04-03T02:33:36.687085
2021-12-20T02:20:41
2021-12-20T02:20:41
246,961,672
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6023067831993103, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 23.90804672241211, "blob_id": "2864d99f9e3250a003e2d15eb9dda6a672ca1efe", "content_id": "d69f6ffa3cc556daefeece0d2e8c526099a5fa09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5693, "license_type": "no_license", "max_line_length": 115, "num_lines": 174, "path": "/ss_08_聚类算法.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\n\ndef k_means():\n \"\"\"\n k-means聚类\n 数据集:iris鸢尾花数据集\n :return:\n \"\"\"\n #导包\n from sklearn.datasets import load_iris\n from sklearn.cluster import KMeans\n import matplotlib.pyplot as plt\n\n #加载数据\n data_iris = load_iris()\n #构建并训练K-Means模型\n kmeans_model = KMeans(n_clusters=3)\n kmeans_model.fit(data_iris[\"data\"])\n print(\"训练的模型为:\",kmeans_model)\n\n #画图展示\n #绘制iris原本的数据类别\n plt.scatter(data_iris.data[:,0],data_iris.data[:,1],c=data_iris.target)\n plt.show()\n #绘制kmeans聚类结果\n y_predict = kmeans_model.predict(data_iris.data)\n plt.scatter(data_iris.data[:,0],data_iris.data[:,1],c=y_predict)\n plt.show()\n return None\n\n\ndef hierarchical_clustering():\n \"\"\"\n 层次聚类--鸢尾花数据集\n :return:\n \"\"\"\n # 导包\n from sklearn import datasets\n from sklearn.cluster import AgglomerativeClustering\n import matplotlib.pyplot as plt\n # 加载数据\n data_iris = datasets.load_iris()\n x = data_iris.data\n y = data_iris.target\n clusting_ward = AgglomerativeClustering(n_clusters=3)\n clusting_ward.fit(x)\n print(\"簇类别标签为:\",clusting_ward.labels_)\n print(\"叶子节点数量:\",clusting_ward.n_leaves_)\n # 训练模型并预测每个样本的簇标记\n cw_ypre = AgglomerativeClustering(n_clusters=3).fit_predict(x)\n # 绘制散点图\n plt.scatter(x[:,0],x[:,1],c=cw_ypre)\n plt.title(\"ward linkage\",size=18)\n plt.show()\n\n\ndef dbscan_clustering():\n \"\"\"\n DBSCAN(密度聚类)\n :return:\n \"\"\"\n # 导包\n from sklearn import datasets\n from sklearn.cluster import DBSCAN\n import numpy as np\n import matplotlib.pyplot as plt\n from sklearn.cluster import KMeans\n # 生成两簇非凸数据\n \"\"\"\n make_blobs函数是为聚类产生数据集,产生一个数据集和相应的标签\n n_samples:表示数据样本点个数,默认值100\n n_features:表示数据的维度,默认值是2\n centers:产生数据的中心点,默认值3\n cluster_std:数据集的标准差,浮点数或者浮点数序列,默认值1.0\n center_box:中心确定之后的数据边界,默认值(-10.0, 10.0)\n shuffle :洗乱,默认值是True\n random_state:官网解释是随机生成器的种子\n \"\"\"\n x1,y2 = datasets.make_blobs(n_samples=1000,n_features=2,centers=[[1.2,1.2]],cluster_std=[[0.1]],random_state=9)\n # 一簇对比数据\n \"\"\"\n datasets.make_circles()专门用来生成圆圈形状的二维样本.\n factor表示里圈和外圈的距离之比.每圈共有n_samples/2个点,\n 里圈代表一个类,外圈也代表一个类.noise表示有0.05的点是异常点\n \"\"\"\n x2,y1 = datasets.make_circles(n_samples=5000,factor=0.6,noise=0.05)\n x = np.concatenate((x1,x2))\n plt.scatter(x[:,0],x[:,1],marker=\"o\")\n plt.show()\n\n dbs = DBSCAN().fit(x)\n print(\"DBSCAN模型的簇标签:\",dbs.labels_)\n print(\"核心样本的位置为:\",dbs.core_sample_indices_)\n #通过簇标签看出,默认参数的DBSCAN模型将所有样本归为一类,与实际不符,\n #调整eps参数和min_samples参数优化聚类效果\n\n ds_pre = DBSCAN(eps=0.1,min_samples=12).fit_predict(x)\n plt.scatter(x[:,0],x[:,1],c=ds_pre)\n plt.title(\"DBSCAN\",size=17)\n plt.show()\n\n #与k-means对比一下\n km_pre = KMeans(n_clusters=3,random_state=9).fit_predict(x)\n plt.scatter(x[:,0],x[:,1],c=km_pre)\n plt.title(\"K-means\",size=17)\n plt.show()\n\n\ndef gmm_clustering():\n \"\"\"\n 高斯混合模型(GMM)--iris数据集案例\n :return:\n \"\"\"\n # 导包\n from sklearn import datasets\n from sklearn.mixture import GaussianMixture\n import matplotlib.pyplot as plt\n from sklearn.cluster import KMeans\n\n # 加载数据\n iris = datasets.load_iris()\n x = iris.data\n y = iris.target\n #绘制样本数据\n plt.scatter(x[:,0],x[:,1],c=y)\n plt.title(\"iris\",size=18)\n plt.show()\n\n # 构建聚类为3的GMM模型\n gmm_model = GaussianMixture(n_components=3).fit(x)\n print(\"GMM模型的权重为:\",gmm_model.weights_)\n print(\"GMM模型的均值为:\",gmm_model.means_)\n #获取GMM模型聚类结果\n gmm_pre = gmm_model.predict(x)\n plt.scatter(x[:,0],x[:,1],c = gmm_pre)\n plt.title(\"GMM\",size=18)\n plt.show()\n #K-means聚类\n km_pre = KMeans(n_clusters=3).fit_predict(x)\n plt.scatter(x[:,0],x[:,1],c=km_pre)\n plt.title(\"K-means\",size=18)\n plt.show()\n return None\n\nif __name__ ==\"__main__\":\n \"\"\"\n 聚类算法:\n 是在没有给定划分类别的情况下,根据数据相似度进行样本分组的一种方法。\n 聚类的输入是一组未被标记的样本,聚类根据数据自身的距离或相似度将他们划分为若干组,\n 划分的原则是组内样本最小化组间距离最大化\n \n \"\"\"\n \"\"\"\n 聚类算法1:K-means:\n 步骤:\n 1.随机设置k个特征空间内的点作为初始的聚类中心\n 2.对于其他每个点计算到K个中心得距离,未知类的点选择距离最近的一个聚类中心点作为自己的属于的类\n 3.接着对标记的聚类中心之后,重新计算出每个聚类的新中心点\n 4.如果计算得出的新中心点与原中心点一样,那么结束,否则重新进行第二步过程\n \"\"\"\n k_means()\n\n \"\"\"\n 聚类算法2:层次聚类\n \"\"\"\n # hierarchical_clustering()\n\n \"\"\"\n DBSCAN(密度聚类)\n \"\"\"\n # dbscan_clustering()\n\n \"\"\"\n 高斯混合模型(GMM)\n \"\"\"\n # gmm_clustering()" }, { "alpha_fraction": 0.6153009533882141, "alphanum_fraction": 0.6488397121429443, "avg_line_length": 27.43556785583496, "blob_id": "d656471f59d800db1ace9f46edbcb3da98a05e5c", "content_id": "0defbc66a4c72e288882198a94380aa5bd754bae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12392, "license_type": "no_license", "max_line_length": 81, "num_lines": 388, "path": "/京东用户购买意向预测/JD_2_数据探索.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import pandas as pd\n\n\"\"\"\n(2)- 数据探索\n\"\"\"\n# 导入相关包\n\n# 绘图包\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n#定义文件名\nACTION_201602_FILE = \"./data/JData_Action_201602.csv\"\nACTION_201603_FILE = \"./data/JData_Action_201603.csv\"\nACTION_201604_FILE = \"./data/JData_Action_201604.csv\"\nCOMMENT_FILE = \"./data/JData_Comment.csv\"\nPRODUCT_FILE = \"./data/JData_Product.csv\"\nUSER_FILE = \"./data/JData_User.csv\"\nUSER_TABLE_FILE = \"./data/User_table.csv\"\nITEM_TABLE_FILE = \"./data/Item_table.csv\"\n\n\"\"\"\n周一到周日各天购买情况\n\"\"\"\n# 提取购买(type=4)的行为数据\ndef get_from_action_data(fname, chunk_size=50000):\n reader = pd.read_csv(fname, header=0, iterator=True)\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(chunk_size)[\n [\"user_id\", \"sku_id\", \"type\", \"time\"]]\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n\n df_ac = pd.concat(chunks, ignore_index=True)\n # type=4,为购买\n df_ac = df_ac[df_ac['type'] == 4]\n\n return df_ac[[\"user_id\", \"sku_id\", \"time\"]]\n\ndf_ac = []\ndf_ac.append(get_from_action_data(fname=ACTION_201602_FILE))\ndf_ac.append(get_from_action_data(fname=ACTION_201603_FILE))\ndf_ac.append(get_from_action_data(fname=ACTION_201604_FILE))\ndf_ac = pd.concat(df_ac, ignore_index=True)\n\nprint(df_ac.dtypes)\n\n# 将time字段转换为datetime类型\ndf_ac['time'] = pd.to_datetime(df_ac['time'])\n\n# 使用lambda匿名函数将时间time转换为星期(周一为1, 周日为7)\ndf_ac['time'] = df_ac['time'].apply(lambda x: x.weekday() + 1)\n\nprint(df_ac.head())\n\n# 周一到周日每天购买用户个数\ndf_user = df_ac.groupby('time')['user_id'].nunique()\ndf_user = df_user.to_frame().reset_index()\ndf_user.columns = ['weekday', 'user_num']\n\n# 周一到周日每天购买商品个数\ndf_item = df_ac.groupby('time')['sku_id'].nunique()\ndf_item = df_item.to_frame().reset_index()\ndf_item.columns = ['weekday', 'item_num']\n\n# 周一到周日每天购买记录个数\ndf_ui = df_ac.groupby('time', as_index=False).size()\ndf_ui = df_ui.to_frame().reset_index()\ndf_ui.columns = ['weekday', 'user_item_num']\n\n# 条形宽度\nbar_width = 0.2\n# 透明度\nopacity = 0.4\n\nplt.bar(df_user['weekday'], df_user['user_num'], bar_width,\n alpha=opacity, color='c', label='user')\nplt.bar(df_item['weekday']+bar_width, df_item['item_num'],\n bar_width, alpha=opacity, color='g', label='item')\nplt.bar(df_ui['weekday']+bar_width*2, df_ui['user_item_num'],\n bar_width, alpha=opacity, color='m', label='user_item')\n\nplt.xlabel('weekday')\nplt.ylabel('number')\nplt.title('A Week Purchase Table')\nplt.xticks(df_user['weekday'] + bar_width * 3 / 2., (1,2,3,4,5,6,7))\nplt.tight_layout()\nplt.legend(prop={'size':10})\nplt.show()\n# 分析:周六,周日购买量较少\n\n\"\"\"\n一个月中各天购买量\n\"\"\"\n# 2016年2月\ndf_ac = get_from_action_data(fname=ACTION_201602_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac['time'] = pd.to_datetime(df_ac['time']).apply(lambda x: x.day)\nprint(df_ac.head())\nprint(df_ac.tail())\n\ndf_user = df_ac.groupby('time')['user_id'].nunique()\ndf_user = df_user.to_frame().reset_index()\ndf_user.columns = ['day', 'user_num']\n\ndf_item = df_ac.groupby('time')['sku_id'].nunique()\ndf_item = df_item.to_frame().reset_index()\ndf_item.columns = ['day', 'item_num']\n\ndf_ui = df_ac.groupby('time', as_index=False).size()\ndf_ui = df_ui.to_frame().reset_index()\ndf_ui.columns = ['day', 'user_item_num']\n\n# 条形宽度\nbar_width = 0.2\n# 透明度\nopacity = 0.4\n# 天数\nday_range = range(1,len(df_user['day']) + 1, 1)\n# 设置图片大小\nplt.figure(figsize=(14,10))\n\nplt.bar(df_user['day'], df_user['user_num'], bar_width,\n alpha=opacity, color='c', label='user')\nplt.bar(df_item['day']+bar_width, df_item['item_num'],\n bar_width, alpha=opacity, color='g', label='item')\nplt.bar(df_ui['day']+bar_width*2, df_ui['user_item_num'],\n bar_width, alpha=opacity, color='m', label='user_item')\n\nplt.xlabel('day')\nplt.ylabel('number')\nplt.title('February Purchase Table')\nplt.xticks(df_user['day'] + bar_width * 3 / 2., day_range)\n# plt.ylim(0, 80)\nplt.tight_layout()\nplt.legend(prop={'size':9})\nplt.show()\n# 分析: 2月份5,6,7,8,9,10 这几天购买量非常少,原因可能是中国农历春节,快递不营业\n\n\"\"\"\n2016年3月\n\"\"\"\ndf_ac = get_from_action_data(fname=ACTION_201603_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac['time'] = pd.to_datetime(df_ac['time']).apply(lambda x: x.day)\n\ndf_user = df_ac.groupby('time')['user_id'].nunique()\ndf_user = df_user.to_frame().reset_index()\ndf_user.columns = ['day', 'user_num']\n\ndf_item = df_ac.groupby('time')['sku_id'].nunique()\ndf_item = df_item.to_frame().reset_index()\ndf_item.columns = ['day', 'item_num']\n\ndf_ui = df_ac.groupby('time', as_index=False).size()\ndf_ui = df_ui.to_frame().reset_index()\ndf_ui.columns = ['day', 'user_item_num']\n\n# 条形宽度\nbar_width = 0.2\n# 透明度\nopacity = 0.4\n# 天数\nday_range = range(1,len(df_user['day']) + 1, 1)\n# 设置图片大小\nplt.figure(figsize=(14,10))\n\nplt.bar(df_user['day'], df_user['user_num'], bar_width,\n alpha=opacity, color='c', label='user')\nplt.bar(df_item['day']+bar_width, df_item['item_num'],\n bar_width, alpha=opacity, color='g', label='item')\nplt.bar(df_ui['day']+bar_width*2, df_ui['user_item_num'],\n bar_width, alpha=opacity, color='m', label='user_item')\n\nplt.xlabel('day')\nplt.ylabel('number')\nplt.title('March Purchase Table')\nplt.xticks(df_user['day'] + bar_width * 3 / 2., day_range)\n# plt.ylim(0, 80)\nplt.tight_layout()\nplt.legend(prop={'size':9})\nplt.show()\n# 分析:3月份14,15,16不知名节日,造成购物大井喷,总体来看,购物记录多于2月份\n\n\"\"\"\n2016年4月\n\"\"\"\ndf_ac = get_from_action_data(fname=ACTION_201604_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac['time'] = pd.to_datetime(df_ac['time']).apply(lambda x: x.day)\n\ndf_user = df_ac.groupby('time')['user_id'].nunique()\ndf_user = df_user.to_frame().reset_index()\ndf_user.columns = ['day', 'user_num']\n\ndf_item = df_ac.groupby('time')['sku_id'].nunique()\ndf_item = df_item.to_frame().reset_index()\ndf_item.columns = ['day', 'item_num']\n\ndf_ui = df_ac.groupby('time', as_index=False).size()\ndf_ui = df_ui.to_frame().reset_index()\ndf_ui.columns = ['day', 'user_item_num']\n\n# 条形宽度\nbar_width = 0.2\n# 透明度\nopacity = 0.4\n# 天数\nday_range = range(1,len(df_user['day']) + 1, 1)\n# 设置图片大小\nplt.figure(figsize=(14,10))\n\nplt.bar(df_user['day'], df_user['user_num'], bar_width,\n alpha=opacity, color='c', label='user')\nplt.bar(df_item['day']+bar_width, df_item['item_num'],\n bar_width, alpha=opacity, color='g', label='item')\nplt.bar(df_ui['day']+bar_width*2, df_ui['user_item_num'],\n bar_width, alpha=opacity, color='m', label='user_item')\n\nplt.xlabel('day')\nplt.ylabel('number')\nplt.title('April Purchase Table')\nplt.xticks(df_user['day'] + bar_width * 3 / 2., day_range)\n# plt.ylim(0, 80)\nplt.tight_layout()\nplt.legend(prop={'size':9})\n# plt.show()\n# 分析:一脸懵逼中...可能又有啥节日? 还是说每个月中旬都有较强的购物欲望?\n\n\n\"\"\"\n商品类别销售统计\n\"\"\"\n\n\"\"\"\n周一到周日各商品类别销售情况\n\"\"\"\n# 从行为记录中提取商品类别数据\ndef get_from_action_data(fname, chunk_size=50000):\n reader = pd.read_csv(fname, header=0, iterator=True)\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(chunk_size)[\n [\"cate\", \"brand\", \"type\", \"time\"]]\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n\n df_ac = pd.concat(chunks, ignore_index=True)\n # type=4,为购买\n df_ac = df_ac[df_ac['type'] == 4]\n\n return df_ac[[\"cate\", \"brand\", \"type\", \"time\"]]\n\ndf_ac = []\ndf_ac.append(get_from_action_data(fname=ACTION_201602_FILE))\ndf_ac.append(get_from_action_data(fname=ACTION_201603_FILE))\ndf_ac.append(get_from_action_data(fname=ACTION_201604_FILE))\ndf_ac = pd.concat(df_ac, ignore_index=True)\n\n# 将time字段转换为datetime类型\ndf_ac['time'] = pd.to_datetime(df_ac['time'])\n\n# 使用lambda匿名函数将时间time转换为星期(周一为1, 周日为7)\ndf_ac['time'] = df_ac['time'].apply(lambda x: x.weekday() + 1)\n\nprint(df_ac.head())\nprint(# 观察有几个类别商品\ndf_ac.groupby(df_ac['cate']).count())\n\n# 周一到周日每天购买商品类别数量统计\ndf_product = df_ac['brand'].groupby([df_ac['time'],df_ac['cate']]).count()\ndf_product=df_product.unstack()\ndf_product.plot(kind='bar',title='Cate Purchase Table in a Week',figsize=(14,10))\nplt.show()\n\"\"\"\n分析:星期二买类别8的最多,星期天最少。\n\"\"\"\n\n\"\"\"\n每月各类商品销售情况(只关注商品8)\n\"\"\"\n\"\"\"\n2016年2,3,4月\n\"\"\"\ndf_ac2 = get_from_action_data(fname=ACTION_201602_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac2['time'] = pd.to_datetime(df_ac2['time']).apply(lambda x: x.day)\ndf_ac3 = get_from_action_data(fname=ACTION_201603_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac3['time'] = pd.to_datetime(df_ac3['time']).apply(lambda x: x.day)\ndf_ac4 = get_from_action_data(fname=ACTION_201604_FILE)\n\n# 将time字段转换为datetime类型并使用lambda匿名函数将时间time转换为天\ndf_ac4['time'] = pd.to_datetime(df_ac4['time']).apply(lambda x: x.day)\n\ndc_cate2 = df_ac2[df_ac2['cate']==8]\ndc_cate2 = dc_cate2['brand'].groupby(dc_cate2['time']).count()\ndc_cate2 = dc_cate2.to_frame().reset_index()\ndc_cate2.columns = ['day', 'product_num']\n\ndc_cate3 = df_ac3[df_ac3['cate']==8]\ndc_cate3 = dc_cate3['brand'].groupby(dc_cate3['time']).count()\ndc_cate3 = dc_cate3.to_frame().reset_index()\ndc_cate3.columns = ['day', 'product_num']\n\ndc_cate4 = df_ac4[df_ac4['cate']==8]\ndc_cate4 = dc_cate4['brand'].groupby(dc_cate4['time']).count()\ndc_cate4 = dc_cate4.to_frame().reset_index()\ndc_cate4.columns = ['day', 'product_num']\n\n# 条形宽度\nbar_width = 0.2\n# 透明度\nopacity = 0.4\n# 天数\nday_range = range(1,len(dc_cate3['day']) + 1, 1)\n# 设置图片大小\nplt.figure(figsize=(14,10))\n\nplt.bar(dc_cate2['day'], dc_cate2['product_num'], bar_width,\n alpha=opacity, color='c', label='February')\nplt.bar(dc_cate3['day']+bar_width, dc_cate3['product_num'],\n bar_width, alpha=opacity, color='g', label='March')\nplt.bar(dc_cate4['day']+bar_width*2, dc_cate4['product_num'],\n bar_width, alpha=opacity, color='m', label='April')\n\nplt.xlabel('day')\nplt.ylabel('number')\nplt.title('Cate-8 Purchase Table')\nplt.xticks(dc_cate3['day'] + bar_width * 3 / 2., day_range)\n# plt.ylim(0, 80)\nplt.tight_layout()\nplt.legend(prop={'size':9})\nplt.show()\n\"\"\"\n分析:2月份对类别8商品的购买普遍偏低,3,4月份普遍偏高,3月15日购买极其多!\n可以对比3月份的销售记录,发现类别8将近占了3月15日总销售的一半!同时发现,\n3,4月份类别8销售记录在前半个月特别相似,除了4月8号,9号和3月15号。\n\"\"\"\n\n\"\"\"\n查看特定用户对特定商品的的轨迹\n\"\"\"\ndef spec_ui_action_data(fname, user_id, item_id, chunk_size=100000):\n reader = pd.read_csv(fname, header=0, iterator=True)\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(chunk_size)[\n [\"user_id\", \"sku_id\", \"type\", \"time\"]]\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n\n df_ac = pd.concat(chunks, ignore_index=True)\n df_ac = df_ac[(df_ac['user_id'] == user_id) & (df_ac['sku_id'] == item_id)]\n\n return df_ac\n\ndef explore_user_item_via_time():\n user_id = 266079\n item_id = 138778\n df_ac = []\n df_ac.append(spec_ui_action_data(ACTION_201602_FILE, user_id, item_id))\n df_ac.append(spec_ui_action_data(ACTION_201603_FILE, user_id, item_id))\n df_ac.append(spec_ui_action_data(ACTION_201604_FILE, user_id, item_id))\n df_ac = pd.concat(df_ac, ignore_index=False)\n print(df_ac.sort_values(by='time'))\n\nexplore_user_item_via_time()" }, { "alpha_fraction": 0.6471260190010071, "alphanum_fraction": 0.6562619209289551, "avg_line_length": 32.68589782714844, "blob_id": "ea347826c651fd4c43e3e9b19bc612c15ad68c15", "content_id": "f4a4f95768a1d0511947e23eeec42e1b910bcf3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7248, "license_type": "no_license", "max_line_length": 104, "num_lines": 156, "path": "/泰迪杯2.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.externals import joblib\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport jieba\n\ndef message_classification():\n \"\"\"\n 第一问:群众留言分类\n\n 在处理网络问政平台的群众留言时,工作人员首先按照一定的划分体系(参考附件 1 提\n 供的内容分类三级标签体系)对留言进行分类,以便后续将群众留言分派至相应的职能部门\n 处理。目前,大部分电子政务系统还是依靠人工根据经验处理,存在工作量大、效率低,且\n 差错率高等问题。请根据附件 2 给出的数据,建立关于留言内容的一级标签分类模型。\n 通常使用 F-Score 对分类方法进行评价\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n data_message2 = pd.read_excel(\"../data/2test.xlsx\")\n data_message1 = pd.read_excel(\"../data/2.xlsx\")\n # 去除留言详情列空格,制表符\n data_message1[\"留言详情\"] = data_message1[\"留言详情\"].apply(lambda x: x.replace('\\n', '').replace('\\t', ''))\n data_message2[\"留言详情\"] = data_message2[\"留言详情\"].apply(lambda x: x.replace('\\n', '').replace('\\t', ''))\n # 特征值数据\n data = data_message1[\"留言详情\"]\n data2 = data_message2[\"留言详情\"]\n # 目标值数据\n target = data_message1[\"一级标签\"].values.tolist()\n # 拆分数据集\n x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.25)\n # 实例化CountVectorizer()。CountVectorizer会将文本中的词语转换为词频矩阵,\n # 它通过fit_transform函数计算各个词语出现的次数\n vectorizer = CountVectorizer()\n # 调用fit_transfrom输入并转换数据\n words = vectorizer.fit_transform(x_train)\n test_word = vectorizer.transform(data2)\n # 实例化多项式分布的朴素贝叶斯\n clf_model = MultinomialNB().fit(words, y_train)\n predicted = clf_model.predict(test_word)\n df = pd.DataFrame(predicted, columns=['一级标签'])\n df.to_excel(\"./a.xlsx\",index=False)\n print(\"===\",predicted)\n # for doc, category in zip(x_test, predicted):\n # print(doc, \":\", category)\n # print(\"每个类别的精确率和召回率:\\n\", classification_report(y_test, predicted))\n f1 = cross_val_score(clf_model, words, y_train, scoring=\"f1_weighted\", cv=5)\n print(\"F1 score: \" + str(round(100 * f1.mean(), 2)) + \"%\")\n # 模型保存\n # joblib.dump(clf_model, \"./clf_model.pkl\")\n #\n # # # 测试保存的模型\n # model = joblib.load(\"./clf_model.pkl\")\n # # predict_result = standard_y.inverse_transform(model.predict(x_test))\n # predict_result = model.predict(data)\n # print(predict_result)\n pass\n\ndef hot_mining():\n \"\"\"\n 2、热点问题挖掘\n 某一时段内群众集中反映的某一问题可称为热点问题,如“XXX 小区多位业主多次反映\n 入夏以来小区楼下烧烤店深夜经营导致噪音和油烟扰民”。及时发现热点问题,有助于相关\n 部门进行有针对性地处理,提升服务效率。请根据附件 3 将某一时段内反映特定地点或特定\n 人群问题的留言进行归类,定义合理的热度评价指标,并给出评价结果,按表 1 的格式给出\n 排名前 5 的热点问题,并保存为文件“热点问题表.xls”。按表 2 的格式给出相应热点问题\n 对应的留言信息,并保存为“热点问题留言明细表.xls”。\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n data_message = pd.read_excel(\"../data/3.xlsx\")\n # 特征值数据\n document = data_message[\"留言主题\"].values.tolist()\n # sent_words = [list(jieba.cut(sent)) for sent in data]\n # document = [\" \".join(sent) for sent in sent_words]\n # 对数据进行特征抽取,实例化TF-IDF\n tf = TfidfVectorizer(max_df=0.9)\n # 以训练集中的词的列表进行每篇文章重要性统计\n tfidf_model = tf.fit(document)\n sparse_result = tfidf_model.transform(document)\n # 词语与列的对应关系\n print(tfidf_model.vocabulary_)\n # 得到tf-idf矩阵,稀疏矩阵表示法\n print(sparse_result)\n # 转化为更直观的一般矩阵\n print(sparse_result.todense())\n pass\n\n\ndef hot_mining2():\n \"\"\"\n 2、热点问题挖掘\n 某一时段内群众集中反映的某一问题可称为热点问题,如“XXX 小区多位业主多次反映\n 入夏以来小区楼下烧烤店深夜经营导致噪音和油烟扰民”。及时发现热点问题,有助于相关\n 部门进行有针对性地处理,提升服务效率。请根据附件 3 将某一时段内反映特定地点或特定\n 人群问题的留言进行归类,定义合理的热度评价指标,并给出评价结果,按表 1 的格式给出\n 排名前 5 的热点问题,并保存为文件“热点问题表.xls”。按表 2 的格式给出相应热点问题\n 对应的留言信息,并保存为“热点问题留言明细表.xls”。\n :return:\n \"\"\"\n import matplotlib.pyplot as plt\n from wordcloud import WordCloud\n # 获取目标值数据、特征值数据文件\n data_message = pd.read_excel(\"../data/3.xlsx\")\n # 特征值数据\n document = data_message[\"留言主题\"].values.tolist()\n # sent_words = [list(jieba.cut(sent)) for sent in document]\n # document = []\n # for sent in sent_words:\n # for x in sent:\n # document.append(x)\n # document = [\" \".join(sent) for sent in sent_words]\n result = pd.DataFrame(document,columns=[\"留言主题\"])\n frequencies = result.groupby(by = ['留言主题'])[\"留言主题\"].count()\n frequencies = frequencies.sort_values(ascending=False)\n frequencies_dataframe = frequencies.to_frame()\n # data_message = frequencies_dataframe.index.droplevel()\n a = pd.merge(data_message,frequencies_dataframe,on=[\"留言主题\"])\n print(a)\n\n\n # backgroud_Image = plt.imread('../data/pl.jpg')\n # wordcloud = WordCloud(font_path=\"G:/workspace/font/STZHONGS.ttf\",\n # max_words=20,\n # background_color='white',\n # mask=backgroud_Image)\n # my_wordcloud = wordcloud.fit_words(frequencies)\n # plt.imshow(my_wordcloud)\n # plt.axis('off')\n # plt.show()\n pass\n\ndef evaluation_scheme():\n \"\"\"\n 3、答复意见的评价\n 针对附件 4 相关部门对留言的答复意见,从答复的相关性、完整性、可解释性等角度对\n 答复意见的质量给出一套评价方案,并尝试实现。\n\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n data_message = pd.read_excel(\"../data/4.xlsx\")\n # 特征值数据\n document = data_message[\"答复意见\"].values.tolist()\n print(document)\n pass\n\nif __name__==\"__main__\":\n message_classification()\n # hot_mining()\n # hot_mining2()\n # evaluation_scheme()\n pass" }, { "alpha_fraction": 0.6276891231536865, "alphanum_fraction": 0.6370576024055481, "avg_line_length": 30.659339904785156, "blob_id": "162e22f26499dcc9e9b09b2f2d7b3dae3b7e7957", "content_id": "3a9e6413519ce05d8a573e29f560d8a3bb8e6c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4192, "license_type": "no_license", "max_line_length": 94, "num_lines": 91, "path": "/ss_04_scikit_learn数据集与估计器.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\n\ndef iris():\n \"\"\"\n 加载鸢尾花数据集(分类数据集)\n :return:\n \"\"\"\n from sklearn.datasets import load_iris\n from sklearn.model_selection import train_test_split\n iris = load_iris()\n print(\"鸢尾花数据集的特征值为:\\n\",iris.data)\n print(\"鸢尾花数据集的目标值为:\\n\",iris.target)\n print(\"鸢尾花数据集概览信息:\\n\",iris.DESCR)\n\n #鸢尾花数据集划分为训练集和测试集\n #注意返回值顺序,固定的。\n #x_train训练集特征值,y_train训练集目标值;x_test测试集特征值,y_test测试集目标值\n x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size=0.25)\n print(\"训练集特征值和目标值:\",x_train,y_train)\n print(\"测试集特征值和目标值:\",x_test,y_test)\n\ndef news_groups():\n \"\"\"\n 20类新闻文章数据集(分类数据集)\n :return:\n \"\"\"\n #导入包\n from sklearn.datasets import fetch_20newsgroups\n from sklearn.model_selection import train_test_split\n #加载数据,subset=\"all\":选择所有数据(包括训练集和测试机)\n news = fetch_20newsgroups(subset=\"all\")\n print(\"获取特征值:\",news.data)\n print(\"获取目标值:\",news.target)\n #新闻文章数据集划分为训练集和测试机\n #注意数据返回顺序,固定\n #x_train训练集特征值,y_train训练集目标值;x_test测试机特征值,y_test测试机目标值\n x_train,x_test,y_train,y_test = train_test_split(news.data,news.target,test_size=0.25)\n print(\"训练集特征值和目标值:\",x_train,y_train)\n print(\"测试机特征值和目标值:\",x_test,y_test)\n\ndef boston():\n \"\"\"\n 波士顿房价数据集(回归数据集)\n :return:\n \"\"\"\n #导包\n from sklearn.datasets import load_boston\n from sklearn.model_selection import train_test_split\n boston = load_boston()\n print(\"波士顿房价数据特征值:\",boston.data)\n print(\"波士顿房价数据目标值:\",boston.target)\n # x_train训练集特征值,y_train训练集目标值;x_test测试机特征值,y_test测试机目标值\n x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.target,test_size=0.25)\n print(\"波士顿房价训练集特征值和目标值:\",x_train,y_train)\n print(\"波士顿房价测试机特征值和目标值:\",x_test,y_test)\n\n\n\nif __name__==\"__main__\":\n\n \"\"\"\n sklearn数据集\n 问题:自己准备数据集,耗时耗力,不一定真实\n (1)数据集划分:\n 1.训练数据:用于训练,构建模型\n 2.测试数据:在模型检验时使用,用于评估模型是否有效\n (2)数据集API:sklearn.datasets\n 1.datasets.load_*() 获取小规模数据集,数据保护在datasets里\n 2.datasets.fetch_*(data_home=None) 获取大规模数据集,需要从网络上下载。\n 函数的第一个参数是的目录。\n 返回值:\n load*和fetch*返回的数据类型是datasets.base.Bunch(字典格式)\n data:特征数据数组,是[n_sample*n_features]几行几列的二维numpy.ndarray数组\n target:标签数组,是n_samples的一维numpy.ndarray数组\n feature_names:特征名字(新闻数据,手写数字,回归数据集没有)\n target_names:标签名,回归数据集没有\n (3)数据集分割API:sklearn.model_selection.train_test_split()\n 输入:数据集特征值、数据集目标值、测试集比例大小\n 返回值:训练集特征值、测试集特征值、训练集目标值、测试集特征值\n \"\"\"\n # iris()\n # news_groups()\n # boston()\n\n \"\"\"\n sklearn估计器(estimator):是一类实现了算法的API。分类器和回归器都属于estimator\n 估计器常见API:\n 1.sklearn.neighbors k-近邻\n 2.sklearn.naive_bayes 朴素贝叶斯\n 3.sklearn.linear_model.LogisticRegression 逻辑回归\n 4.sklearn.linear_model.LinearRegression 线性回归\n 5.sklearn.linear_model.Ridge 岭回归\n \"\"\"" }, { "alpha_fraction": 0.7004673480987549, "alphanum_fraction": 0.7356935143470764, "avg_line_length": 32.21083450317383, "blob_id": "8b251982a694bb9e39226154ce179f1eba2046eb", "content_id": "b2d197e87bc4cc87f9a800cb046e2b331deed65c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30736, "license_type": "no_license", "max_line_length": 214, "num_lines": 683, "path": "/泰坦尼克号/泰坦尼克-数据挖掘流程.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use('fivethirtyeight')\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n数据挖掘流程:\n\n(一)数据读取:\n•读取数据,并进行展示\n•统计数据各项指标\n•明确数据规模与要完成任务\n\n(二)特征理解分析\n•单特征分析,逐个变量分析其对结果的影响\n•多变量统计分析,综合考虑多种情况影响\n•统计绘图得出结论\n\n(三)数据清洗与预处理\n•对缺失值进行填充\n•特征标准化/归一化\n•筛选有价值的特征\n•分析特征之间的相关性\n\n(四)建立模型\n•特征数据与标签准备\n•数据集切分\n•多种建模算法对比\n•集成策略等方案改进\n\n\"\"\"\n\"\"\"\n挑选兵器:\n任务已经明确下达,接下来的目的就是挑选几个合适的兵器去进行预测的工作啦,咱们的主线是使用Python,因为在数据分析与机器学习界Python已经成为一哥啦!首先介绍下咱们的兵器谱!\n •Numpy-科学计算库 主要用来做矩阵运算,什么?你不知道哪里会用到矩阵,那么这样想吧,咱们的数据就是行(样本)和列(特征)组成的,那么数据本身不就是一个矩阵嘛。 \n •Pandas-数据分析处理库 很多小伙伴都在说用python处理数据很容易,那么容易在哪呢?其实有了pandas很复杂的操作我们也可以一行代码去解决掉! \n •Matplotlib-可视化库 无论是分析还是建模,光靠好记性可不行,很有必要把结果和过程可视化的展示出来。\n •Seaborn-可视化库 更简单的可视化库封装上Matplot基础之上。\n •Scikit-Learn-机器学习库 非常实用的机器学习算法库,这里面包含了基本你觉得你能用上所有机器学习算法啦。但还远不止如此,还有很多预处理和评估的模块等你来挖掘的!\n\"\"\"\n# 数据读起来,先看看啥东西\ndata=pd.read_csv('./data/train.csv')\ndata.head()\n\n# 有木有缺失值\ndata.isnull().sum() #checking for total null values\n# 整体看看数据啥规模\nprint(data.describe())\n\n# 不是要预测这大船的获救情况嘛,先看看获救比例咋样\nf,ax=plt.subplots(1,2,figsize=(18,8))\ndata['Survived'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True)\nax[0].set_title('Survived')\nax[0].set_ylabel('')\nsns.countplot('Survived',data=data,ax=ax[1])\nax[1].set_title('Survived')\nplt.show()\n\n\"\"\"\n显然,这次事故中没有多少乘客幸免于难。\n在训练集的891名乘客中,只有大约350人幸存下来,只有38.4%的机组人员在空难中幸存下来。我们需要从数据中挖掘出更多的信息,看看哪些类别的乘客幸存下来,哪些没有。\n我们将尝试使用数据集的不同特性来检查生存率。比如性别,年龄,登船地点等,但是首先我们得来理解下数据中的特征!\n\"\"\"\n\n\"\"\"\n数据特征分为:连续值和离散值\n •离散值:性别(男,女) 登船地点(S,Q,C)\n •连续值:年龄,船票价格\n\"\"\"\ndata.groupby(['Sex','Survived'])['Survived'].count()\n\nf,ax=plt.subplots(1,2,figsize=(18,8))\ndata[['Sex','Survived']].groupby(['Sex']).mean().plot.bar(ax=ax[0])\nax[0].set_title('Survived vs Sex')\nsns.countplot('Sex',hue='Survived',data=data,ax=ax[1])\nax[1].set_title('Sex:Survived vs Dead')\nplt.show()\n\"\"\"\n这看起来很有趣。船上的男人比女人多得多。不过,挽救的女性人数几乎是男性的两倍。\n生存率为一个女人在船上是75%左右,而男性在18-19%左右。(让妇女和儿童先走,虽然\n电影忘得差不多了,这句话还记着。。。确实是这样的)\n这看起来是建模的一个非常重要的特性。一会我们会用上他的!\n\"\"\"\n# Pclass --> 船舱等级跟获救情况的关系\npd.crosstab(data.Pclass,data.Survived,margins=True).style.background_gradient(cmap='summer_r')\n\nf,ax=plt.subplots(1,2,figsize=(18,8))\ndata['Pclass'].value_counts().plot.bar(color=['#CD7F32','#FFDF00','#D3D3D3'],ax=ax[0])\nax[0].set_title('Number Of Passengers By Pclass')\nax[0].set_ylabel('Count')\nsns.countplot('Pclass',hue='Survived',data=data,ax=ax[1])\nax[1].set_title('Pclass:Survived vs Dead')\nplt.show()\n\"\"\"\n人们说金钱不能买到一切。但我们可以清楚地看到,船舱等级为1的被给予很高的优先级而救援。尽管数量在pClass 3乘客高了很多,\n仍然存活数从他们是非常低的,大约25%。\n对于pClass1来说存活是63%左右,而pclass2大约是48%。所以金钱和地位很重要。这样一个物欲横流的世界。\n那这些又和性别有关吗?接下来我们再来看看船舱等级和性别对结果的影响\n\"\"\"\npd.crosstab([data.Sex,data.Survived],data.Pclass,margins=True).style.background_gradient(cmap='summer_r')\nsns.factorplot('Pclass','Survived',hue='Sex',data=data)\nplt.show()\n\n\"\"\"\n我们用factorplot这个图,看起来更直观一些。\n我们可以很容易地推断,从pclass1女性生存是95-96%,如94人中只有3的女性从pclass1没获救。\n显而易见的是,不论pClass,女性优先考虑。\n看来Pclass也是一个重要的特征。让我们分析其他特征\nAge--> 连续值特征对结果的影响\n\"\"\"\nprint('Oldest Passenger was of:',data['Age'].max(),'Years')\nprint('Youngest Passenger was of:',data['Age'].min(),'Years')\nprint('Average Age on the ship:',data['Age'].mean(),'Years')\n\nf,ax=plt.subplots(1,2,figsize=(18,8))\nsns.violinplot(\"Pclass\",\"Age\", hue=\"Survived\", data=data,split=True,ax=ax[0])\nax[0].set_title('Pclass and Age vs Survived')\nax[0].set_yticks(range(0,110,10))\nsns.violinplot(\"Sex\",\"Age\", hue=\"Survived\", data=data,split=True,ax=ax[1])\nax[1].set_title('Sex and Age vs Survived')\nax[1].set_yticks(range(0,110,10))\nplt.show()\n\"\"\"\n结果: \n1)10岁以下儿童的存活率随passenegers数量增加。\n2)生存为20-50岁获救几率更高一些。\n3)对男性来说,随着年龄的增长,存活率降低。\n\"\"\"\n\n\"\"\"\n缺失值填充\n•平均值\n•经验值 \n•回归模型预测\n•剔除掉\n\"\"\"\n\n\"\"\"\n正如我们前面看到的,年龄特征有177个空值。为了替换这些缺失值,我们可以给它们分配数据集的平均年龄。\n但问题是,有许多不同年龄的人。最好的办法是找到一个合适的年龄段!\n我们可以检查名字特征。根据这个特征,我们可以看到名字有像先生或夫人这样的称呼,这样我们就可以\n把先生和夫人的平均值分配给各自的组\n\"\"\"\ndata['Initial']=0\nfor i in data:\n data['Initial']=data.Name.str.extract('([A-Za-z]+)\\.')\n# 好了,这里我们使用正则表达式:[A-Za-z] +)来提取信息\n\npd.crosstab(data.Initial,data.Sex).T.style.background_gradient(cmap='summer_r') #Checking the Initials with the Sex\ndata['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don'],['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr'],inplace=True)\n\ndata.groupby('Initial')['Age'].mean() #lets check the average age by Initials\n\n# 填充缺失值\n## 使用每组的均值来进行填充\ndata.loc[(data.Age.isnull())&(data.Initial=='Mr'),'Age']=33\ndata.loc[(data.Age.isnull())&(data.Initial=='Mrs'),'Age']=36\ndata.loc[(data.Age.isnull())&(data.Initial=='Master'),'Age']=5\ndata.loc[(data.Age.isnull())&(data.Initial=='Miss'),'Age']=22\ndata.loc[(data.Age.isnull())&(data.Initial=='Other'),'Age']=46\n\ndata.Age.isnull().any() #看看填充完了咋样\n\nf,ax=plt.subplots(1,2,figsize=(20,10))\ndata[data['Survived']==0].Age.plot.hist(ax=ax[0],bins=20,edgecolor='black',color='red')\nax[0].set_title('Survived= 0')\nx1=list(range(0,85,5))\nax[0].set_xticks(x1)\ndata[data['Survived']==1].Age.plot.hist(ax=ax[1],color='green',bins=20,edgecolor='black')\nax[1].set_title('Survived= 1')\nx2=list(range(0,85,5))\nax[1].set_xticks(x2)\nplt.show()\n\"\"\"\n观察:\n1)幼儿(年龄在5岁以下)获救的还是蛮多的(妇女和儿童优先政策)。\n2)最老的乘客得救了(80年)。\n3)死亡人数最高的是30-40岁年龄组。\n\"\"\"\n\nsns.factorplot('Pclass','Survived',col='Initial',data=data)\nplt.show()\n# 因此,无论性别如何,妇女和儿童第一政策都是正确的。\n\n\"\"\"\nEmbarked--> 登船地点\n\"\"\"\npd.crosstab([data.Embarked,data.Pclass],[data.Sex,data.Survived],margins=True).style.background_gradient(cmap='summer_r')\n\nsns.factorplot('Embarked','Survived',data=data)\nfig=plt.gcf()\nfig.set_size_inches(5,3)\nplt.show()\n# C港生存的可能性最高在0.55左右,而S的生存率最低。\n\nf,ax=plt.subplots(2,2,figsize=(20,15))\nsns.countplot('Embarked',data=data,ax=ax[0,0])\nax[0,0].set_title('No. Of Passengers Boarded')\nsns.countplot('Embarked',hue='Sex',data=data,ax=ax[0,1])\nax[0,1].set_title('Male-Female Split for Embarked')\nsns.countplot('Embarked',hue='Survived',data=data,ax=ax[1,0])\nax[1,0].set_title('Embarked vs Survived')\nsns.countplot('Embarked',hue='Pclass',data=data,ax=ax[1,1])\nax[1,1].set_title('Embarked vs Pclass')\nplt.subplots_adjust(wspace=0.2,hspace=0.5)\nplt.show()\n\"\"\"\n观察:\n1)大部分人的船舱等级是3。\n2)C的乘客看起来很幸运,他们中的一部分幸存下来。\n3)S港口的富人蛮多的。仍然生存的机会很低。\n4)港口Q几乎有95%的乘客都是穷人。\n\"\"\"\n\nsns.factorplot('Pclass','Survived',hue='Sex',col='Embarked',data=data)\nplt.show()\n\"\"\"\n观察:\n1)存活的几率几乎为1 在pclass1和pclass2中的女人。\n2)pclass3 的乘客中男性和女性的生存率都是很偏低的。\n3)端口Q很不幸,因为那里都是3等舱的乘客。\n港口中也存在缺失值,在这里我用众数来进行填充了,因为S登船人最多呀\n\"\"\"\n\ndata['Embarked'].fillna('S',inplace=True)\ndata.Embarked.isnull().any()\n\n\"\"\"\nsibsip -->兄弟姐妹的数量\n这个特征表示一个人是独自一人还是与他的家人在一起。\n\"\"\"\npd.crosstab([data.SibSp],data.Survived).style.background_gradient(cmap='summer_r')\n\nf,ax=plt.subplots(1,2,figsize=(20,8))\nsns.barplot('SibSp','Survived',data=data,ax=ax[0])\nax[0].set_title('SibSp vs Survived')\nsns.factorplot('SibSp','Survived',data=data,ax=ax[1])\nax[1].set_title('SibSp vs Survived')\nplt.close(2)\nplt.show()\n\npd.crosstab(data.SibSp,data.Pclass).style.background_gradient(cmap='summer_r')\n\"\"\"\n观察:\nbarplot和factorplot表明,如果乘客是孤独的船上没有兄弟姐妹,他有34.5%的存活率。如\n果兄弟姐妹的数量增加,该图大致减少。这是有道理的。也就是说,如果我有一个家庭在船上,\n我会尽力拯救他们,而不是先救自己。但是令人惊讶的是,5-8名成员家庭的存活率为0%。原因可能是他们在pclass=3的船舱?\n\"\"\"\n\n\"\"\"\nParch --> 父母和孩子的数量\n\"\"\"\npd.crosstab(data.Parch,data.Pclass).style.background_gradient(cmap='summer_r')\n# 再次表明,大家庭都在pclass3\n\nf,ax=plt.subplots(1,2,figsize=(20,8))\nsns.barplot('Parch','Survived',data=data,ax=ax[0])\nax[0].set_title('Parch vs Survived')\nsns.factorplot('Parch','Survived',data=data,ax=ax[1])\nax[1].set_title('Parch vs Survived')\nplt.close(2)\nplt.show()\n\n\"\"\"\n观察:\n这里的结果也很相似。带着父母的乘客有更大的生存机会。然而,它随着数字的增加而减少。\n在船上的家庭父母人数中有1-3个的人的生存机会是好的。独自一人也证明是致命的,当船上有4个父母时,生存的机会就会减少。\n\"\"\"\n\n\"\"\"\nFare--> 船票的价格\n\"\"\"\nprint('Highest Fare was:',data['Fare'].max())\nprint('Lowest Fare was:',data['Fare'].min())\nprint('Average Fare was:',data['Fare'].mean())\n# 最低票价是0英镑。这价格我也能去!\n\nf,ax=plt.subplots(1,3,figsize=(20,8))\nsns.distplot(data[data['Pclass']==1].Fare,ax=ax[0])\nax[0].set_title('Fares in Pclass 1')\nsns.distplot(data[data['Pclass']==2].Fare,ax=ax[1])\nax[1].set_title('Fares in Pclass 2')\nsns.distplot(data[data['Pclass']==3].Fare,ax=ax[2])\nax[2].set_title('Fares in Pclass 3')\nplt.show()\n\"\"\"\n概括地观察所有的特征: 性别:与男性相比,女性的生存机会很高。\nPclass:有,第一类乘客给你更好的生存机会的一个明显趋势。对于pclass3成活率很低。对于女性来说,从pclass1生存的机会几乎是。\n年龄:小于5-10岁的儿童存活率高。年龄在15到35岁之间的乘客死亡很多。\n港口:上来的仓位也有区别,死亡率也很大!\n家庭:有1-2的兄弟姐妹、配偶或父母上1-3显示而不是独自一人或有一个大家庭旅行,你有更大的概率存活\n\"\"\"\n\n\"\"\"\n特征之间的相关性\n\"\"\"\nsns.heatmap(data.corr(),annot=True,cmap='RdYlGn',linewidths=0.2) #data.corr()-->correlation matrix\nfig=plt.gcf()\nfig.set_size_inches(10,8)\nplt.show()\n\"\"\"\n特征相关性的热度图\n首先要注意的是,只有数值特征进行比较\n正相关:如果特征A的增加导致特征b的增加,那么它们呈正相关。值1表示完全正相关。\n负相关:如果特征A的增加导致特征b的减少,则呈负相关。值-1表示完全负相关。\n现在让我们说两个特性是高度或完全相关的,所以一个增加导致另一个增加。这意味着两个特征都包含高度相似的信息,并且信息很少或没有变化。这样的特征对我们来说是没有价值的!\n那么你认为我们应该同时使用它们吗?。在制作或训练模型时,我们应该尽量减少冗余特性,因为它减少了训练时间和许多优点。\n现在,从上面的图,我们可以看到,特征不显著相关\n\"\"\"\n\n\"\"\"\n特征工程和数据清洗\n当我们得到一个具有特征的数据集时,是不是所有的特性都很重要?可能有许多冗余的特征应该被消除,我们还可以通过观察或从其他特征中提取信息来获得或添加新特性\n\"\"\"\n\"\"\"\n年龄特征:\n正如我前面提到的,年龄是连续的特征,在机器学习模型中存在连续变量的问题。\n如果我说通过性别来组织或安排体育运动,我们可以很容易地把他们分成男女分开。\n如果我说按他们的年龄分组,你会怎么做?如果有30个人,可能有30个年龄值。\n我们需要对连续值进行离散化来分组。\n好的,乘客的最大年龄是80岁。所以我们将范围从0-80成5箱。所以80/5=16。\n\"\"\"\ndata['Age_band']=0\ndata.loc[data['Age']<=16,'Age_band']=0\ndata.loc[(data['Age']>16)&(data['Age']<=32),'Age_band']=1\ndata.loc[(data['Age']>32)&(data['Age']<=48),'Age_band']=2\ndata.loc[(data['Age']>48)&(data['Age']<=64),'Age_band']=3\ndata.loc[data['Age']>64,'Age_band']=4\ndata.head(2)\n\ndata['Age_band'].value_counts().to_frame().style.background_gradient(cmap='summer')#checking the number of passenegers in each band\n\nsns.factorplot('Age_band','Survived',data=data,col='Pclass')\nplt.show()\n# 生存率随年龄的增加而减少,不论Pclass\n\n\"\"\"\nFamily_size:家庭总人数\n光看兄弟姐妹和老人孩子看不太直接,咱们直接看全家的人数\n\"\"\"\ndata['Family_Size']=0\ndata['Family_Size']=data['Parch']+data['SibSp']#family size\ndata['Alone']=0\ndata.loc[data.Family_Size==0,'Alone']=1#Alone\n\nf,ax=plt.subplots(1,2,figsize=(18,6))\nsns.factorplot('Family_Size','Survived',data=data,ax=ax[0])\nax[0].set_title('Family_Size vs Survived')\nsns.factorplot('Alone','Survived',data=data,ax=ax[1])\nax[1].set_title('Alone vs Survived')\nplt.close(2)\nplt.close(3)\nplt.show()\n\"\"\"\nfamily_size = 0意味着passeneger是孤独的。显然,如果你是单独或family_size = 0,那么生存的机会很低。家庭规模4以上,机会也减少。这看起来也是模型的一个重要特性。让我们进一步研究这个问题。\n\"\"\"\nsns.factorplot('Alone','Survived',data=data,hue='Sex',col='Pclass')\nplt.show()\n\n\"\"\"\n船票价格\n\n因为票价也是连续的特性,所以我们需要将它转换为数值\n\"\"\"\ndata['Fare_Range']=pd.qcut(data['Fare'],4)\ndata.groupby(['Fare_Range'])['Survived'].mean().to_frame().style.background_gradient(cmap='summer_r')\n# 如上所述,我们可以清楚地看到,船票价格增加生存的机会增加\n\ndata['Fare_cat']=0\ndata.loc[data['Fare']<=7.91,'Fare_cat']=0\ndata.loc[(data['Fare']>7.91)&(data['Fare']<=14.454),'Fare_cat']=1\ndata.loc[(data['Fare']>14.454)&(data['Fare']<=31),'Fare_cat']=2\ndata.loc[(data['Fare']>31)&(data['Fare']<=513),'Fare_cat']=3\n\nsns.factorplot('Fare_cat','Survived',data=data,hue='Sex')\nplt.show()\n\"\"\"\n显然,随着fare_cat增加,存活的几率增加。随着性别的变化,这一特性可能成为建模过程中的一个重要特征。\n将字符串值转换为数字 因为我们不能把字符串一个机器学习模型\n\"\"\"\n\ndata['Sex'].replace(['male','female'],[0,1],inplace=True)\ndata['Embarked'].replace(['S','C','Q'],[0,1,2],inplace=True)\ndata['Initial'].replace(['Mr','Mrs','Miss','Master','Other'],[0,1,2,3,4],inplace=True)\n\n\"\"\"\n去掉不必要的特征\n名称>我们不需要name特性,因为它不能转换成任何分类值\n年龄——>我们有age_band特征,所以不需要这个\n票号-->这是任意的字符串,不能被归类\n票价——>我们有fare_cat特征,所以不需要\n船仓号——>这个也不要没啥含义\npassengerid -->不能被归类\n\"\"\"\n\ndata.drop(['Name','Age','Ticket','Fare','Cabin','Fare_Range','PassengerId'],axis=1,inplace=True)\nsns.heatmap(data.corr(),annot=True,cmap='RdYlGn',linewidths=0.2,annot_kws={'size':20})\nfig=plt.gcf()\nfig.set_size_inches(18,15)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.show()\n# 现在以上的相关图,我们可以看到一些正相关的特征。他们中的一些人sibsp和family_size和干燥family_size和一些负面的孤独和family_size\n\n\"\"\"\n机器学习建模\n\n我们从EDA部分获得了一些见解。但是,我们不能准确地预测或判断一个乘客是否会幸存或死亡。现在我们将使用一些很好的分类算法来预测乘客是否能生存下来:\n1)logistic回归\n2)支持向量机(线性和径向)\n3)随机森林\n4)k-近邻\n5)朴素贝叶斯\n6)决策树\n7)神经网络\n\"\"\"\n#importing all the required ML packages\nfrom sklearn.linear_model import LogisticRegression #logistic regression\nfrom sklearn import svm #support vector Machine\nfrom sklearn.ensemble import RandomForestClassifier #Random Forest\nfrom sklearn.neighbors import KNeighborsClassifier #KNN\nfrom sklearn.naive_bayes import GaussianNB #Naive bayes\nfrom sklearn.tree import DecisionTreeClassifier #Decision Tree\nfrom sklearn.model_selection import train_test_split #training and testing data split\nfrom sklearn import metrics #accuracy measure\nfrom sklearn.metrics import confusion_matrix #for confusion matrix\n\ntrain,test=train_test_split(data,test_size=0.3,random_state=0,stratify=data['Survived'])\ntrain_X=train[train.columns[1:]]\ntrain_Y=train[train.columns[:1]]\ntest_X=test[test.columns[1:]]\ntest_Y=test[test.columns[:1]]\nX=data[data.columns[1:]]\nY=data['Survived']\n\n# Radial Support Vector Machines(rbf-SVM)\nmodel=svm.SVC(kernel='rbf',C=1,gamma=0.1)\nmodel.fit(train_X,train_Y)\nprediction1=model.predict(test_X)\nprint('Accuracy for rbf SVM is ',metrics.accuracy_score(prediction1,test_Y))\n\n# Linear Support Vector Machine(linear-SVM)\nmodel=svm.SVC(kernel='linear',C=0.1,gamma=0.1)\nmodel.fit(train_X,train_Y)\nprediction2=model.predict(test_X)\nprint('Accuracy for linear SVM is',metrics.accuracy_score(prediction2,test_Y))\n\n# Logistic Regression\nmodel = LogisticRegression()\nmodel.fit(train_X,train_Y)\nprediction3=model.predict(test_X)\nprint('The accuracy of the Logistic Regression is',metrics.accuracy_score(prediction3,test_Y))\n\n# Decision Tree\nmodel=DecisionTreeClassifier()\nmodel.fit(train_X,train_Y)\nprediction4=model.predict(test_X)\nprint('The accuracy of the Decision Tree is',metrics.accuracy_score(prediction4,test_Y))\n\n# K-Nearest Neighbours(KNN)\nmodel=KNeighborsClassifier()\nmodel.fit(train_X,train_Y)\nprediction5=model.predict(test_X)\nprint('The accuracy of the KNN is',metrics.accuracy_score(prediction5,test_Y))\n\n# 现在的精度为KNN模型的变化,我们改变n_neighbours值属性。默认值是5。让我们检查的精度在n_neighbours不同时的结果。\na_index=list(range(1,11))\na=pd.Series()\nx=[0,1,2,3,4,5,6,7,8,9,10]\nfor i in list(range(1,11)):\n model=KNeighborsClassifier(n_neighbors=i)\n model.fit(train_X,train_Y)\n prediction=model.predict(test_X)\n a=a.append(pd.Series(metrics.accuracy_score(prediction,test_Y)))\nplt.plot(a_index, a)\nplt.xticks(x)\nfig=plt.gcf()\nfig.set_size_inches(12,6)\nplt.show()\nprint('Accuracies for different values of n are:',a.values,'with the max value as ',a.values.max())\n\n\nmodel=GaussianNB()\nmodel.fit(train_X,train_Y)\nprediction6=model.predict(test_X)\nprint('The accuracy of the NaiveBayes is',metrics.accuracy_score(prediction6,test_Y))\n\nmodel=RandomForestClassifier(n_estimators=100)\nmodel.fit(train_X,train_Y)\nprediction7=model.predict(test_X)\nprint('The accuracy of the Random Forests is',metrics.accuracy_score(prediction7,test_Y))\n\n\"\"\"\n模型的精度并不是决定分类器效果的唯一因素。假设分类器在训练数据上进行训练,需要在测试集上进行测试才有效果\n现在这个分类器的精确度很高,但是我们可以确认所有的新测试集都是90%吗?答案是否定的,因为我们不能确定分类器在不同数据源上的结果。当训练和测试数据发生变化时,精确度也会改变。它可能会增加或减少。\n为了克服这一点,得到一个广义模型,我们使用交叉验证。\n\"\"\"\n\n\"\"\"\n交叉验证\n\n一个测试集看起来不太够呀,多轮求均值是一个好的策略!\n1)的交叉验证的工作原理是首先将数据集分成k-subsets。\n2)假设我们将数据集划分为(k=5)部分。我们预留1个部分进行测试,并对这4个部分进行训练。\n3)我们通过在每次迭代中改变测试部分并在其他部分中训练算法来继续这个过程。然后对衡量结果求平均值,得到算法的平均精度。\n这就是所谓的交叉验证。\n\"\"\"\nfrom sklearn.model_selection import KFold #for K-fold cross validation\nfrom sklearn.model_selection import cross_val_score #score evaluation\nfrom sklearn.model_selection import cross_val_predict #prediction\nkfold = KFold(n_splits=10, random_state=22) # k=10, split the data into 10 equal parts\nxyz=[]\naccuracy=[]\nstd=[]\nclassifiers=['Linear Svm','Radial Svm','Logistic Regression','KNN','Decision Tree','Naive Bayes','Random Forest']\nmodels=[svm.SVC(kernel='linear'),svm.SVC(kernel='rbf'),LogisticRegression(),KNeighborsClassifier(n_neighbors=9),DecisionTreeClassifier(),GaussianNB(),RandomForestClassifier(n_estimators=100)]\nfor i in models:\n model = i\n cv_result = cross_val_score(model,X,Y, cv = kfold,scoring = \"accuracy\")\n cv_result=cv_result\n xyz.append(cv_result.mean())\n std.append(cv_result.std())\n accuracy.append(cv_result)\nnew_models_dataframe2=pd.DataFrame({'CV Mean':xyz,'Std':std},index=classifiers)\nprint(new_models_dataframe2)\n\nplt.subplots(figsize=(12,6))\nbox=pd.DataFrame(accuracy,index=[classifiers])\nbox.T.boxplot()\n\nnew_models_dataframe2['CV Mean'].plot.barh(width=0.8)\nplt.title('Average CV Mean Accuracy')\nfig=plt.gcf()\nfig.set_size_inches(8,5)\nplt.show()\n\n# 混淆矩阵 它给出分类器的正确和不正确分类的数量\nf,ax=plt.subplots(3,3,figsize=(12,10))\ny_pred = cross_val_predict(svm.SVC(kernel='rbf'),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[0,0],annot=True,fmt='2.0f')\nax[0,0].set_title('Matrix for rbf-SVM')\ny_pred = cross_val_predict(svm.SVC(kernel='linear'),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[0,1],annot=True,fmt='2.0f')\nax[0,1].set_title('Matrix for Linear-SVM')\ny_pred = cross_val_predict(KNeighborsClassifier(n_neighbors=9),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[0,2],annot=True,fmt='2.0f')\nax[0,2].set_title('Matrix for KNN')\ny_pred = cross_val_predict(RandomForestClassifier(n_estimators=100),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[1,0],annot=True,fmt='2.0f')\nax[1,0].set_title('Matrix for Random-Forests')\ny_pred = cross_val_predict(LogisticRegression(),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[1,1],annot=True,fmt='2.0f')\nax[1,1].set_title('Matrix for Logistic Regression')\ny_pred = cross_val_predict(DecisionTreeClassifier(),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[1,2],annot=True,fmt='2.0f')\nax[1,2].set_title('Matrix for Decision Tree')\ny_pred = cross_val_predict(GaussianNB(),X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,y_pred),ax=ax[2,0],annot=True,fmt='2.0f')\nax[2,0].set_title('Matrix for Naive Bayes')\nplt.subplots_adjust(hspace=0.2,wspace=0.2)\nplt.show()\n\"\"\"\n解释混淆矩阵:来看第一个图\n1)预测的正确率为491(死亡)+ 247(存活),平均CV准确率为(491+247)/ 891=82.8%。\n2)58和95都是咱们弄错了的。\n\"\"\"\n\n\"\"\"\n超参数整定\n机器学习模型就像一个黑盒子。这个黑盒有一些默认参数值,我们可以调整或更改以获得更好的模型。比如支持向量机模型中的C和γ,我们称之为超参数,他们对结果可能产生非常大的影响\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\nC=[0.05,0.1,0.2,0.3,0.25,0.4,0.5,0.6,0.7,0.8,0.9,1]\ngamma=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\nkernel=['rbf','linear']\nhyper={'kernel':kernel,'C':C,'gamma':gamma}\ngd=GridSearchCV(estimator=svm.SVC(),param_grid=hyper,verbose=True)\ngd.fit(X,Y)\nprint(gd.best_score_)\nprint(gd.best_estimator_)\n\n# Random Forests\nn_estimators=range(100,1000,100)\nhyper={'n_estimators':n_estimators}\ngd=GridSearchCV(estimator=RandomForestClassifier(random_state=0),param_grid=hyper,verbose=True)\ngd.fit(X,Y)\nprint(gd.best_score_)\nprint(gd.best_estimator_)\n# RBF支持向量机的最佳得分为82.82%,C=0.5,γ=0.1。RandomForest,成绩是81.8%\n\n\"\"\"\n集成\n集成是提高模型的精度和性能的一个很好的方式。简单地说,是各种简单模型的结合创造了一个强大的模型。\n\n1)随机森林类型的,并行的集成\n2)提升类型\n3)堆叠类型\n\n投票分类器 这是将许多不同的简单机器学习模型的预测结合起来的最简单方法。它给出了一个平均预测结果基于各子模型的预测\n\"\"\"\nfrom sklearn.ensemble import VotingClassifier\nensemble_lin_rbf=VotingClassifier(estimators=[('KNN',KNeighborsClassifier(n_neighbors=10)),\n ('RBF',svm.SVC(probability=True,kernel='rbf',C=0.5,gamma=0.1)),\n ('RFor',RandomForestClassifier(n_estimators=500,random_state=0)),\n ('LR',LogisticRegression(C=0.05)),\n ('DT',DecisionTreeClassifier(random_state=0)),\n ('NB',GaussianNB()),\n ('svm',svm.SVC(kernel='linear',probability=True))\n ],\n voting='soft').fit(train_X,train_Y)\nprint('The accuracy for ensembled model is:',ensemble_lin_rbf.score(test_X,test_Y))\ncross=cross_val_score(ensemble_lin_rbf,X,Y, cv = 10,scoring = \"accuracy\")\nprint('The cross validated score is',cross.mean())\n\nfrom sklearn.ensemble import BaggingClassifier\nmodel=BaggingClassifier(base_estimator=KNeighborsClassifier(n_neighbors=3),random_state=0,n_estimators=700)\nmodel.fit(train_X,train_Y)\nprediction=model.predict(test_X)\nprint('The accuracy for bagged KNN is:',metrics.accuracy_score(prediction,test_Y))\nresult=cross_val_score(model,X,Y,cv=10,scoring='accuracy')\nprint('The cross validated score for bagged KNN is:',result.mean())\n\n# Bagged DecisionTree\nmodel=BaggingClassifier(base_estimator=DecisionTreeClassifier(),random_state=0,n_estimators=100)\nmodel.fit(train_X,train_Y)\nprediction=model.predict(test_X)\nprint('The accuracy for bagged Decision Tree is:',metrics.accuracy_score(prediction,test_Y))\nresult=cross_val_score(model,X,Y,cv=10,scoring='accuracy')\n\n\"\"\"\n提升是一个逐步增强的弱模型:\n首先对完整的数据集进行训练。现在模型会得到一些实例,而有些错误。现在,在下一次迭代中,学习者将更多地关注错误预测的实例或赋予它更多的权重\n\"\"\"\n\"\"\"\nAdaBoost(自适应增强) 在这种情况下,弱学习或估计是一个决策树。但我们可以改变缺省base_estimator任何算法的选择\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\nada=AdaBoostClassifier(n_estimators=200,random_state=0,learning_rate=0.1)\nresult=cross_val_score(ada,X,Y,cv=10,scoring='accuracy')\nprint('The cross validated score for AdaBoost is:',result.mean())\n\nfrom sklearn.ensemble import GradientBoostingClassifier\ngrad=GradientBoostingClassifier(n_estimators=500,random_state=0,learning_rate=0.1)\nresult=cross_val_score(grad,X,Y,cv=10,scoring='accuracy')\nprint('The cross validated score for Gradient Boosting is:',result.mean())\n\n# 我们得到了最高的精度为AdaBoost。我们将尝试用超参数调整来增加它\nn_estimators=list(range(100,1100,100))\nlearn_rate=[0.05,0.1,0.2,0.3,0.25,0.4,0.5,0.6,0.7,0.8,0.9,1]\nhyper={'n_estimators':n_estimators,'learning_rate':learn_rate}\ngd=GridSearchCV(estimator=AdaBoostClassifier(),param_grid=hyper,verbose=True)\ngd.fit(X,Y)\nprint(gd.best_score_)\nprint(gd.best_estimator_)\n# 我们可以从AdaBoost的最高精度是83.16%,n_estimators = 200和learning_rate = 0.05\n\nada=AdaBoostClassifier(n_estimators=200,random_state=0,learning_rate=0.05)\nresult=cross_val_predict(ada,X,Y,cv=10)\nsns.heatmap(confusion_matrix(Y,result),cmap='winter',annot=True,fmt='2.0f')\nplt.show()\n\nimport xgboost as xg\n# Feature Importance\nf,ax=plt.subplots(2,2,figsize=(15,12))\nmodel=RandomForestClassifier(n_estimators=500,random_state=0)\nmodel.fit(X,Y)\npd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[0,0])\nax[0,0].set_title('Feature Importance in Random Forests')\nmodel=AdaBoostClassifier(n_estimators=200,learning_rate=0.05,random_state=0)\nmodel.fit(X,Y)\npd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[0,1],color='#ddff11')\nax[0,1].set_title('Feature Importance in AdaBoost')\nmodel=GradientBoostingClassifier(n_estimators=500,learning_rate=0.1,random_state=0)\nmodel.fit(X,Y)\npd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[1,0],cmap='RdYlGn_r')\nax[1,0].set_title('Feature Importance in Gradient Boosting')\nmodel=xg.XGBClassifier(n_estimators=900,learning_rate=0.1)\nmodel.fit(X,Y)\npd.Series(model.feature_importances_,X.columns).sort_values(ascending=True).plot.barh(width=0.8,ax=ax[1,1],color='#FD0F00')\nax[1,1].set_title('Feature Importance in XgBoost')\nplt.show()" }, { "alpha_fraction": 0.5734103918075562, "alphanum_fraction": 0.6289017200469971, "avg_line_length": 35.02777862548828, "blob_id": "a9d6a7e46cd88b6cdf2c8175d0615e45caddec56", "content_id": "7d8f9d3e442bf1c0c3f275e99038fe4a8be5670e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3073, "license_type": "no_license", "max_line_length": 85, "num_lines": 72, "path": "/财政收入影响因素分析及预测/demo/code/03-predict.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\n\n# 代码6-5\n\nimport sys\nsys.path.append('../code') # 设置路径\nimport numpy as np\nimport pandas as pd\n# from GM11 import GM11 # 引入自编的灰色预测函数\n\ndef GM11(x0): #自定义灰色预测函数\n import numpy as np\n x1 = x0.cumsum() #1-AGO序列\n z1 = (x1[:len(x1)-1] + x1[1:])/2.0 #紧邻均值(MEAN)生成序列\n z1 = z1.reshape((len(z1),1))\n B = np.append(-z1, np.ones_like(z1), axis = 1)\n Yn = x0[1:].reshape((len(x0)-1, 1))\n [[a],[b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Yn) #计算参数\n f = lambda k: (x0[0]-b/a)*np.exp(-a*(k-1))-(x0[0]-b/a)*np.exp(-a*(k-2)) #还原值\n delta = np.abs(x0 - np.array([f(i) for i in range(1,len(x0)+1)]))\n C = delta.std()/x0.std()\n P = 1.0*(np.abs(delta - delta.mean()) < 0.6745*x0.std()).sum()/len(x0)\n return f, a, b, x0[0], C, P #返回灰色预测函数、a、b、首项、方差比、小残差概率\n\ninputfile1 = '../tmp/new_reg_data.csv' # 输入的数据文件\ninputfile2 = '../data/data.csv' # 输入的数据文件\nnew_reg_data = pd.read_csv(inputfile1) # 读取经过特征选择后的数据\ndata = pd.read_csv(inputfile2) # 读取总的数据\nnew_reg_data.index = range(1994, 2014)\nnew_reg_data.loc[2014] = None\nnew_reg_data.loc[2015] = None\nl = ['x1', 'x4', 'x5', 'x6', 'x7', 'x8']\nfor i in l:\n f = GM11(new_reg_data.loc[range(1994, 2014),i].as_matrix())[0]\n new_reg_data.loc[2014,i] = f(len(new_reg_data)-1) # 2014年预测结果\n new_reg_data.loc[2015,i] = f(len(new_reg_data)) # 2015年预测结果\n new_reg_data[i] = new_reg_data[i].round(2) # 保留两位小数\noutputfile = '../tmp/new_reg_data_GM11.xls' # 灰色预测后保存的路径\ny = list(data['y'].values) # 提取财政收入列,合并至新数据框中\ny.extend([np.nan,np.nan])\nnew_reg_data['y'] = y\nnew_reg_data.to_excel(outputfile) # 结果输出\nprint('预测结果为:\\n',new_reg_data.loc[2014:2015,:]) # 预测结果展示\n\n\n\n# 代码6-6\n\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import LinearSVR\n\ninputfile = '../tmp/new_reg_data_GM11.xls' # 灰色预测后保存的路径\ndata = pd.read_excel(inputfile) # 读取数据\nfeature = ['x1', 'x4', 'x5', 'x6', 'x7', 'x8'] # 属性所在列\ndata_train = data.loc[range(1994,2014)].copy() # 取2014年前的数据建模\ndata_mean = data_train.mean()\ndata_std = data_train.std()\ndata_train = (data_train - data_mean)/data_std # 数据标准化\nx_train = data_train[feature].as_matrix() # 属性数据\ny_train = data_train['y'].as_matrix() # 标签数据\n\nlinearsvr = LinearSVR() # 调用LinearSVR()函数\nlinearsvr.fit(x_train,y_train)\nx = ((data[feature] - data_mean[feature])/data_std[feature]).as_matrix() # 预测,并还原结果。\ndata[u'y_pred'] = linearsvr.predict(x) * data_std['y'] + data_mean['y']\noutputfile = '../tmp/new_reg_data_GM11_revenue.xls' # SVR预测后保存的结果\ndata.to_excel(outputfile)\n\nprint('真实值与预测值分别为:\\n',data[['y','y_pred']])\n\nfig = data[['y','y_pred']].plot(subplots = True, style=['b-o','r-*']) # 画出预测结果图\nplt.show()\n\n" }, { "alpha_fraction": 0.6377706527709961, "alphanum_fraction": 0.6451285481452942, "avg_line_length": 34.719032287597656, "blob_id": "723bd493447fb2b7ff479ecce26a6c4bf91549e0", "content_id": "e5190148013bff271deb63e877d4188ebb858b58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15474, "license_type": "no_license", "max_line_length": 112, "num_lines": 331, "path": "/ss_11_NLTK自然语言处理.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\nimport nltk\n\"\"\"\nNTLK是著名的Python自然语言处理工具包,但是主要针对的是英文处理。\nNLTK配套有文档,有语料库,有书籍。\n 1.NLP领域中最常用的一个Python库\n 2.开源项目\n 3.自带分类、分词等功能\n 4.强大的社区支持\n 5.语料库,语言的实际使用中真是出现过的语言材料\n 6.http://www.nltk.org/py-modindex.html\n在NLTK的主页详细介绍了如何在Mac、Linux和Windows下安装NLTK:http://nltk.org/install.html ,\n建议直接下载Anaconda,省去了大部分包的安装,安装NLTK完毕,可以import nltk测试一下,如果没有问题,还有下载NLTK官方提供的相关语料。\n\"\"\"\n\"\"\"\n语料库就是把平常我们说话的时候袭的句子、一些文学bai作品的语句段落、\n报刊杂志上出现过的语句段落等等在现实生活中真实出现过的语言材料\n整理在一起,形du成一个语料库,以便做科学研究的时候能够从中取材或者得到数据佐证。\n\"\"\"\ndef nltk_brown():\n # 1.查看语料库\n #引用布朗大学的语料库\n from nltk.corpus import brown # 需要下载brown语料库\n # 查看语料库包含的类别\n print(brown.categories())\n # 查看brown语料库\n print('共有{}个句子'.format(len(brown.sents())))\n print('共有{}个单词'.format(len(brown.words())))\n\ndef nltk_tokenize():\n \"\"\"\n 1.实验实现词条化\n 将句子拆分成具有语言语义学上意义的词\n 中、英文分词区别:\n 英文中,单词之间是以空格作为自然分界符的\n 中文中没有一个形式上的分界符,分词比英文复杂的多\n 中文分词工具,如:结巴分词 pip install jieba\n 得到分词结果后,中英文的后续处理没有太大区别\n \"\"\"\n \"\"\"\n nltk.sent_tokenize(text) #按句子分割 \n nltk.word_tokenize(sentence) #分词 \n nltk的分词是句子级别的,所以对于一篇文档首先要将文章按句子进行分割,然后句子进行分词\n \"\"\"\n # 1)创建一个text字符串,作为样例的文本:\n text = \"Are you curious about tokenization?\" \\\n \" Let's see how it works! We need to \" \\\n \"analyze a couple of sentences with \" \\\n \"punctuations to see it in action.\"\n # 2)加载NLTK模块:\n from nltk.tokenize import sent_tokenize\n \"\"\"\n 3)调用NLTK模块的sent_tokenize()方法,对text文本进行词条化,\n sent_tokenize()方法是以句子为分割单位的词条化方法:\n \"\"\"\n sent_tokenize_list = sent_tokenize(text)\n # 4)输出结果:\n print(\"\\nSentence tokenizer:\")\n print(sent_tokenize_list)\n \"\"\"\n 5)调用NLTK模块的word_tokenize()方法,对text文本进行词条化,\n word_tokenize()方法是以单词为分割单位的词条化方法:\n \"\"\"\n from nltk.tokenize import word_tokenize\n print(\"\\nWord tokenizer:\")\n print(word_tokenize(text))\n \"\"\"\n 6)最后一种单词的词条化方法是WordPunctTokenizer(),\n 使用这种方法我们将会把标点作为保留对象。\n \"\"\"\n # from nltk.tokenize import WordPunctTokenizer\n # word_punct_tokenizer = WordPunctTokenizer()\n # print(\"\\nWord punct tokenizer:\")\n # print(word_punct_tokenizer.tokenize(text))\n pass\n\ndef nltk_stemming():\n \"\"\"2.实验实现词干还原\"\"\"\n # (1)导入词干还原相关的包:\n from nltk.stem.porter import PorterStemmer\n from nltk.stem.lancaster import LancasterStemmer\n from nltk.stem.snowball import SnowballStemmer\n # (2)创建样例:\n words = ['table', 'probably', 'wolves', 'playing', 'is', 'dog',\n 'the', 'beaches', 'grounded', 'dreamt', 'envision']\n # (3)调用NLTK模块中三种不同的词干还原方法:\n stemmer_porter = PorterStemmer()\n stemmer_lancaster = LancasterStemmer()\n stemmer_snowball = SnowballStemmer('english')\n # (4)设置打印输出格式:多值参数\n stemmers = ['PORTER', 'LANCASTER', 'SNOWBALL']\n formatted_row = '{:>16}' * (len(stemmers) + 1)\n print('\\n', formatted_row.format('WORD', *stemmers), '\\n')\n # (5) 使用NLTK模块中词干还原方法对样例单词进行词干还原:\n for word in words:\n stemmed_words = [stemmer_porter.stem(word),\n stemmer_lancaster.stem(word),\n stemmer_snowball.stem(word)]\n print(formatted_row.format(word, *stemmed_words))\n pass\n\ndef nltk_lemmatization():\n # 3.实验实现词型归并\n # (1)导入NLTK中词型归并方法:\n from nltk.stem import WordNetLemmatizer\n # (2)创建样例:\n words = ['table', 'probably', 'wolves', 'playing', 'is',\n 'dog', 'the', 'beaches', 'grounded', 'dreamt', 'envision']\n # (3)调用NLTK模块的WordNetLemmatizer()方法:\n lemmatizer_wordnet = WordNetLemmatizer()\n # (4)设置打印输出格式:\n lemmatizers = ['NOUN LEMMATIZER', 'VERB LEMMATIZER']\n formatted_row = '{:>24}' * (len(lemmatizers) + 1)\n print('\\n', formatted_row.format('WORD', *lemmatizers), '\\n')\n # (5)使用NLTK模块中词型归并方法对样例单词进行词型归并:\n for word in words:\n lemmatized_words = [lemmatizer_wordnet.lemmatize(word, pos='n'),\n lemmatizer_wordnet.lemmatize(word, pos='v')]\n print(formatted_row.format(word, *lemmatized_words))\n pass\n\ndef nltk_POS():\n # 4.词性标注 (Part-Of-Speech) nltk.word_tokenize()\n import nltk\n words = nltk.word_tokenize('Python is a widely used programming language.')\n print(nltk.pos_tag(words)) # 需要下载 averaged_perceptron_tagger\n pass\n\ndef nltk_stop_words():\n # 6.NLTK的Stopwords,去除停用词\n \"\"\"\n 去除停用词\n 为节省存储空间和提高搜索效率,NLP中会自动过滤掉某些字或词\n 停用词都是人工输入、非自动化生成的,形成停用词表\n\n 使用NLTK去除停用词\n stopwords.words()\n 分类\n 语言中的功能词,如the, is…\n 词汇词,通常是使用广泛的词,如want\n 中文停用词表\n 中文停用词库\n 哈工大停用词表\n 四川大学机器智能实验室停用词库\n 百度停用词列表\n 其他语言停用词表\n http://www.ranks.nl/stopwords\n \"\"\"\n from nltk.corpus import stopwords # 需要下载stopwords\n words = nltk.word_tokenize('Python is a widely used programming language.')\n filtered_words = [word for word in words if word not in stopwords.words('english')]\n print('原始词:', words)\n print('去除停用词后:', filtered_words)\n pass\n\n# 典型的文本预处理流程\ndef nltk_demo():\n import nltk\n from nltk.stem import WordNetLemmatizer\n from nltk.corpus import stopwords\n\n # 原始文本\n raw_text = 'Life is like a box of chocolates. You never know what you\\'re gonna get.'\n # 分词\n raw_words = nltk.word_tokenize(raw_text)\n # 词形归一化\n wordnet_lematizer = WordNetLemmatizer()\n words = [wordnet_lematizer.lemmatize(raw_word) for raw_word in raw_words]\n # 去除停用词\n filtered_words = [word for word in words if word not in stopwords.words('english')]\n\n print('原始文本:', raw_text)\n print('预处理结果:', filtered_words)\n\ndef nltk_tfidf():\n \"\"\"\n\n 创建文本分类器目的是将文档集中的多个文本文档划分为不同的类别,\n 文本分类在自然语言处理中是很重要的一种分析手段,\n 为实现文本的分类,我们将使用另一种统计数据方法tf-idf\n (词频-逆文档频率), tf-idf方法与基于单词出现频率的\n 统计方法一样,都是将一个文档数据转化为数值型数据的一种方法。\n \"\"\"\n # (1)导入相关的包:\n from sklearn.datasets import fetch_20newsgroups\n # (2) 创建字典,定义分类类型的列表:\n category_map = {'misc.forsale': 'Sales', 'rec.motorcycles': 'Motorcycles',\n 'rec.sport.baseball': 'Baseball', 'sci.crypt': 'Cryptography', 'sci.space': 'Space'}\n # (3)加载训练数据:\n training_data = fetch_20newsgroups(subset='train',\n categories=category_map.keys(), shuffle=True, random_state=7)\n # (4) 特征提取:\n from sklearn.feature_extraction.text import CountVectorizer\n vectorizer = CountVectorizer()\n X_train_termcounts = vectorizer.fit_transform(training_data.data)\n print(\"\\nDimensions of training data:\", X_train_termcounts.shape)\n # (5)训练分类器模型:\n from sklearn.naive_bayes import MultinomialNB\n from sklearn.feature_extraction.text import TfidfTransformer\n # (6)创建随即样例:\n input_data = [\n \"The curveballs of right handed pitchers tend to curve to the left\",\n \"Caesar cipher is an ancient form of encryption\",\n \"This two-wheeler is really good on slippery roads\"]\n # (7)使用tf-idf 算法实现数值型数据的转化以及训练:\n tfidf_transformer = TfidfTransformer()\n X_train_tfidf = tfidf_transformer.fit_transform(X_train_termcounts)\n classifier = MultinomialNB().fit(X_train_tfidf, training_data.target)\n # (8)词频于tf-idf作为输入的对比:\n X_input_termcounts = vectorizer.transform(input_data)\n X_input_tfidf = tfidf_transformer.transform(X_input_termcounts)\n # (9)打印输出结果:\n predicted_categories = classifier.predict(X_input_tfidf)\n for sentence, category in zip(input_data, predicted_categories):\n print('\\nInput:', sentence, '\\nPredicted category:', category_map[training_data.target_names[category]])\n pass\n\ndef nltk_NB():\n \"\"\"\n 在自然语言处理中通过姓名识别性别是一项有趣的事情。\n 我们算法是通过名字中的最后几个字符以确定其性别。例如,\n 如果名字中的最后几个字符是“la”,它很可能是一名女性的名字,\n 如“Angela”或“Layla”。相反的,如果名字中的最后几个字符是“im”,\n 最有可能的是男性名字,比如“Tim”或“Jim”。\n \"\"\"\n # (1)导入相关包:\n import random\n from nltk.corpus import names\n from nltk import NaiveBayesClassifier\n from nltk.classify import accuracy as nltk_accuracy\n # (2)定义函数获取性别:\n def gender_features(word, num_letters=2):\n return {'feature': word[-num_letters:].lower()}\n\n # (3)定义main函数以及数据:\n if __name__ == '__main__':\n labeled_names = ([(name, 'male') for name in names.words('male.txt')] +\n [(name, 'female') for name in names.words('female.txt')])\n random.seed(7)\n random.shuffle(labeled_names)\n input_names = ['Leonardo', 'Amy', 'Sam']\n # (6)获取末尾字符:\n for i in range(1, 5):\n print('\\nNumber of letters:', i)\n featuresets = [(gender_features(n, i), gender) for (n, gender) in labeled_names]\n # (7)划分训练数据和测试数据:\n train_set, test_set = featuresets[500:], featuresets[:500]\n # (8)分类实现:\n classifier = NaiveBayesClassifier.train(train_set)\n # (9)评测分类效果:\n print('Accuracy ==>', str(100 * nltk_accuracy(classifier, test_set)) + str('%'))\n for name in input_names:\n print(name, '==>', classifier.classify(gender_features(name, i)))\n pass\n\ndef nltk_sentiment_analysis():\n \"\"\"\n 情感分析的实现:\n 本文中我们使用NLTK模块中的朴素贝叶斯分类器来实现文档的分类。\n 在特征提取函数中,我们提取了所有的词。但是,在此我们注意到\n NLTK分类器的输入数据格式为字典格式,因此,我们下文中创建了\n 字典格式的数据,以便我们的NLTK分类器可以使用这些数据。同时,\n 在创建完字典型数据后,我们将数据分成训练数据集和测试数据集,\n 我们的目的是使用训练数据训练我们的分类器,以便分类器可以将\n 数据分为积极与消极。而当我们查看哪些单词包含的信息量最大,\n 也就是最能体现其情感的单词的时候,我们会发现有些单词例如,\n “outstanding”表示积极情感,“insulting”表示消极情感。这是\n 非常有意义的信息,因为它告诉我们什么单词被用来表明积极。\n \"\"\"\n # (1)导入相关包:\n import nltk.classify.util\n from nltk.classify import NaiveBayesClassifier\n from nltk.corpus import movie_reviews\n # (2) 定义函数获取情感数据:\n def extract_features(word_list):\n return dict([(word, True) for word in word_list])\n\n # (3)加载数据,在这里为了方便教学我们使用NLTK自带数据:\n if __name__ == '__main__':\n positive_fileids = movie_reviews.fileids('pos')\n negative_fileids = movie_reviews.fileids('neg')\n # (4)将加载的数据划分为消极和积极:\n features_positive = [(extract_features(movie_reviews.words(fileids=[f])),\n 'Positive') for f in positive_fileids]\n features_negative = [(extract_features(movie_reviews.words(fileids=[f])),\n 'Negative') for f in negative_fileids]\n # (5)将数据划分为训练数据和测试数据:\n threshold_factor = 0.8\n threshold_positive = int(threshold_factor * len(features_positive))\n threshold_negative = int(threshold_factor * len(features_negative))\n # (6)提取特征:\n features_train = features_positive[:threshold_positive] + features_negative[:threshold_negative]\n features_test = features_positive[threshold_positive:] + features_negative[threshold_negative:]\n print(\"\\nNumber of training datapoints:\", len(features_train))\n print(\"Number of test datapoints:\", len(features_test))\n # (7)调用朴素贝叶斯分类器:\n classifier = NaiveBayesClassifier.train(features_train)\n print(\"\\nAccuracy of the classifier:\", nltk.classify.util.accuracy(classifier, features_test))\n # (8)输出分类结果:\n print(\"\\nTop 10 most informative words:\")\n for item in classifier.most_informative_features()[:10]:\n print(item[0])\n # (9)使用分类器对情感进行预测:\n input_reviews = [\n \"It is an amazing movie\",\n \"This is a dull movie. I would never recommend it to anyone.\",\n \"The cinematography is pretty great in this movie\",\n \"The direction was terrible and the story was all over the place\"\n ]\n # (10)输出预测的结果:\n print(\"\\nPredictions:\")\n for review in input_reviews:\n print(\"\\nReview:\", review)\n probdist = classifier.prob_classify(extract_features(review.split()))\n pred_sentiment = probdist.max()\n print(\"Predicted sentiment:\", pred_sentiment)\n print(\"Probability:\", round(probdist.prob(pred_sentiment), 2))\n pass\n\nif __name__==\"__main__\":\n # nltk_brown()\n # nltk_tokenize()\n # nltk_stemming()\n # nltk_lemmatization()\n # nltk_POS()\n # nltk_stop_words()\n nltk_demo()\n # nltk_tfidf()\n # nltk_NB()\n # nltk_sentiment_analysis()\n\n pass\n" }, { "alpha_fraction": 0.35477110743522644, "alphanum_fraction": 0.5501289367675781, "avg_line_length": 28.966182708740234, "blob_id": "e9ff78099de61be3a2b4112545998d5b3c3a4cfc", "content_id": "a5b27a1c787e91ab2d629114d4da4b9f8b28d962", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7802, "license_type": "no_license", "max_line_length": 118, "num_lines": 207, "path": "/ss_01_matplotlib学习.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "from matplotlib import pyplot as plt\nimport random\nfrom matplotlib import rcParams\n\n\n# rcParams[\"font.sans-serif\"] = \"SimHei\"\ndef demo1():\n \"\"\"\n matplotlib基本要点 案例\n :return:\n \"\"\"\n # 数据在x轴的位置,是一个可迭代的对象\n x = range(2, 26, 2)\n # 数据在y轴的位置,是一个可迭代的对象\n y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]\n # x轴,y轴的数据一起组成了所有要绘制出的坐标\n # 分别是(2,15),(4,13),(6,14.5)....\n\n plt.plot(x, y) # 传入x和y,通过plot绘制折线图\n plt.show() # 在执行程序的时候展示图形\n\n\ndef demo2():\n \"\"\"\n matplotlib基本要点 案例改进\n 1.设置图片大小\n 2.保存图片\n :return:\n \"\"\"\n \"\"\"\n 设置图片大小\n figure 图形图标的意思,在这里指的就是我们画的图\n 通过实例化一个figure并且传递参数,能够在后台自动使用该figure实例\n 在图形模糊的时候可以传入dpi参数,让图片更加清晰\n \"\"\"\n plt.figure(figsize=(20, 8), dpi=80)\n\n # 数据在x轴的位置,是一个可迭代的对象\n x = range(2, 26, 2)\n # 数据在y轴的位置,是一个可迭代的对象\n y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]\n # x轴,y轴的数据一起组成了所有要绘制出的坐标\n # 分别是(2,15),(4,13),(6,14.5)....\n\n plt.plot(x, y) # 传入x和y,通过plot绘制折线图\n plt.xticks(x) # 设置x的刻度\n # plt.xticks(x[::2])# 当刻度太密集时候使用列表的步长(间隔取值)来解决\n\n # 保存图片,还可以保存为svg矢量图格式,放大不会有锯齿\n plt.savefig(\"./t1.png\")\n plt.show() # 在执行程序的时候展示图形\n\n\ndef demo_temperature():\n \"\"\"\n 如果列表a表示10点到12点的每一分钟的气温,如何绘制折线图\n 观察每分钟气温的变化情况?\n :return:\n \"\"\"\n plt.figure(figsize=(20, 8), dpi=90)\n x = range(120)\n # 设置随机种子,让不同时候随机得到的结果都一样\n random.seed(10)\n y = [random.uniform(20, 35) for i in range(120)]\n # 绘制折线图,设置颜色,样式\n plt.plot(x, y, color=\"red\", linestyle=\"--\")\n # 设置中文字体\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n # 设置x轴上的刻度\n _x_ticks = [\"10点{0}分\".format(i) for i in x if i < 60]\n _x_ticks += [\"11点{0}分\".format(i - 60) for i in x if i > 60]\n\n \"\"\"\n 让列表x中的数据和_x_ticks上的数据都上传,最终会在x轴上一一对应显示出来\n 两组数据的长度必须一样,否则不能完全覆盖这个轴\n 使用列表的切片操作,每隔5个选一个数据进行展示\n 为了让字符串不会覆盖,使用rotation选项,让字符串旋转90°显示 \n \"\"\"\n plt.xticks(x[::5], _x_ticks[::5], rotation=90)\n # 给图像添加描述信息\n # 设置x轴的label\n plt.xlabel(\"时间\")\n # 设置y轴的label\n plt.ylabel(\"温度(°C)\")\n\n # 设置标题\n plt.title(\"10点到12点每分钟的时间变化情况\")\n plt.show()\n return None\n\n\ndef scatter_graph():\n \"\"\"\n 散点图案例\n :return:\n \"\"\"\n y_3 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18, 21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22,\n 22, 22, 23]\n y_10 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11,\n 13, 12, 13, 6]\n x_3 = range(1, 32)\n x_10 = range(51, 82)\n # 设置字体\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n # 设置图形大小\n plt.figure(figsize=(20, 8), dpi=90)\n # 使用scatter方法绘制散点图,和之前绘制折线图的唯一区别\n plt.scatter(x_3, y_3, label=\"3月份\")\n plt.scatter(x_10, y_10, label=\"10月份\")\n # 调整x轴的刻度\n _x = list(x_3) + list(x_10)\n _xtick_labels = [\"3月{}日\".format(i) for i in x_3]\n _xtick_labels += [\"4月{}日\".format(i - 50) for i in x_10]\n plt.xticks(_x[::3], _xtick_labels[::3], rotation=45)\n # 添加图例\n plt.legend(loc=\"upper left\")\n # 添加描述信息\n plt.xlabel(\"时间\")\n plt.ylabel(\"温度\")\n plt.title(\"标题\")\n # 展示\n plt.show()\n return None\n\ndef bar_graph():\n a = [\"战狼2\", \"速度与激情8\", \"功夫瑜伽\", \"西游伏妖篇\", \"变形金刚5:最后的骑士\",\n \"摔跤吧!爸爸\", \"加勒比海盗5:死无对证\", \"金刚:骷髅岛\", \"极限特工:终极回归\",\n \"生化危机6:终章\",\"乘风破浪\", \"神偷奶爸3\", \"智取威虎山\", \"大闹天竺\",\n \"金刚狼3:殊死一战\", \"蜘蛛侠:英雄归来\", \"悟空传\", \"银河护卫队2\", \"情圣\", \"新木乃伊\", ]\n\n b = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12,\n 10.49, 10.3, 8.75, 7.55, 7.32, 6.99, 6.88,6.86, 6.58, 6.23]\n # 设置字体\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n #设置图形大小\n plt.figure(figsize=(20.,15),dpi=90)\n #绘制条形图\n plt.bar(range(len(a)),a,width=0.3,color=\"orange\")\n #设置字符串到x轴\n plt.xticks(range(len(a)),a,rotation=90)\n\n plt.show()\n return None\n\ndef bar_graph_2():\n a = [\"猩球崛起3:终极之战\", \"敦刻尔克\", \"蜘蛛侠:英雄归来\", \"战狼2\"]\n b_16 = [15746, 312, 4497, 319]\n b_15 = [12357, 156, 2045, 168]\n b_14 = [2358, 399, 2358, 362]\n bar_width = 0.2\n # 设置字体\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n x_14 = list(range(len(a)))\n x_15 = [i+bar_width for i in x_14]\n x_16 = [i+bar_width*2 for i in x_14]\n\n #设置图形大小\n plt.figure(figsize=(20,8),dpi=90)\n\n plt.bar(range(len(a)),b_14,width=bar_width,label=\"9月14日\")\n plt.bar(x_15,b_15,width=bar_width,label=\"9月15日\")\n plt.bar(x_16,b_16,width=bar_width,label=\"9月16日\")\n\n #设置图例\n plt.legend()\n plt.xticks(x_15,a)\n plt.show()\n\ndef hist_graph():\n a = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119,\n 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134,\n 95, 138, 117, 111, 78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130, 126,\n 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136, 123, 117, 119, 105, 137, 123,\n 128, 125, 104, 109, 134, 125, 127, 105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102,\n 120, 114, 105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134, 156, 106, 117,\n 127, 144, 139, 139, 119, 140, 83, 110, 102, 123, 107, 143, 115, 136, 118, 139, 123, 112,\n 118, 125, 109, 119, 133, 112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,\n 115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154, 136, 100, 118, 119, 133,\n 134, 106, 129, 126, 110, 111, 109, 141, 120, 117, 106, 149, 122, 122, 110, 118, 127, 121,\n 114, 125, 126, 114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92, 121, 112,\n 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113, 134, 106, 144, 110, 137, 137, 111,\n 104, 117, 100, 111, 101, 110, 105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133,\n 101, 131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111, 111, 133, 150]\n #计算组数\n d = 3\n num_bins = (max(a)-min(a))//d\n print(max(a), min(a), max(a) - min(a))\n print(num_bins)\n #设置图形大小\n plt.figure(figsize=(20,8),dpi=80)\n #绘制直方图\n plt.hist(a,num_bins)\n #设置x轴的刻度\n plt.xticks(range(min(a),max(a)+d,d))\n plt.grid()\n plt.show()\n return None\n\nif __name__ == \"__main__\":\n demo1()\n # demo2()\n # demo_temperature()\n # scatter_graph()\n # bar_graph()\n # bar_graph_2()\n # hist_graph()\n pass\n\n" }, { "alpha_fraction": 0.4859183430671692, "alphanum_fraction": 0.5330817699432373, "avg_line_length": 21.020771026611328, "blob_id": "6423362bce983ce48abc47a2d83c727efd9b0455", "content_id": "6462e405ccad2aa19a22c251cdfa4f6ee60d10b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9047, "license_type": "no_license", "max_line_length": 77, "num_lines": 337, "path": "/ss_02_numpy.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\n\ndef numpy_base():\n # 创建数组\n # a,b,c内容相同,注意arange和range区别\n # [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]\n a = np.array([1, 2, 3, 4, 5])\n b = np.array(range(1, 6))\n c = np.arange(1, 6)\n print(a, b, c)\n # 数组类型 numpy.ndarray\n # <class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>\n print(type(a), type(b), type(c))\n # 数据的类型\n print(a.dtype) # int32\n\n # 指定创建的数组的数据类型\n a = np.array([1, 0, 1, 0], dtype=np.bool)\n print(a) # [ True False True False]\n # 修改数组的数据类型\n a1 = a.astype(np.int)\n print(a1)\n # 修改浮点型的小数位数\n b = np.array([random.random() for i in range(10)])\n b1 = b.round(2)\n print(b1)\n\n # 数组的形状\n # 创建一个二维数组\n a = np.array([[3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9]])\n print(a)\n # 查看数组的形状,2行6列\n print(a.shape) # (2, 6)\n # 修改数组的形状,3行4列\n print(a.reshape(3, 4))\n # 把数组转化为一维数据\n b = a.reshape(1, 12)\n print(b) # [[3 4 5 6 7 8 4 5 6 7 8 9]]\n print(b.flatten()) # [3 4 5 6 7 8 4 5 6 7 8 9]\n\n # 数组和数的计算\n # 加减乘除会被广播到每个元素上面进行计算\n a = np.arange(12).reshape(2, 6)\n # 加法减法\n print(a + 1)\n # 乘法除法\n print(a * 3)\n\n # 数组和数组的计算\n a = np.arange(12).reshape(2, 6)\n b = np.arange(12, 24).reshape(2, 6)\n # 数组和数组的加减法\n print(a + b)\n # 数组和数组的乘除法\n print(a * b)\n c = np.arange(12).reshape(3, 4)\n d = np.arange(6).reshape(1, 6)\n e = [[1], [2]]\n # 行列均不同维度的两个数组,不能计算\n # print(a*c)\n print(a * d)\n print(a * e)\n\n return None\n\n\ndef youtube_video():\n us_file_path = \"../data/US_video_data_numbers.csv\"\n us_data = np.loadtxt(us_file_path, delimiter=\",\", dtype=\"int\")\n print(us_data)\n # 取行\n print(us_data[2])\n # 取连续的多行\n print(us_data[2:])\n # 取不连续的多行\n print(us_data[[2, 8, 10]])\n\n print(us_data[1, :])\n print(us_data[2:, :])\n print(us_data[[2, 10, 3], :])\n # 取列\n print(us_data[:, 0])\n # 取连续的多列\n print(us_data[:, 2:])\n # 取不连续的多列\n print(us_data[:, [0, 2]])\n # 取多行和多列,取第3行到第五行,第2列到第4列的结果\n # 去的是行和列交叉点的位置\n b = us_data[2:5, 1:4]\n print(b)\n # 取多个不相邻的点\n # 选出来的结果是(0,0) (2,1) (2,3)\n c = us_data[[0, 2, 2], [0, 1, 3]]\n print(c)\n return None\n\n\ndef numpy_t():\n \"\"\"\n numpy中的转置\n 转置是一种变换,对于numpy中的数组来说,\n 就是在对角线方向交换数据,目的也是为了更方便的去处理数据\n 1.transpose()\n 2.T\n 以上的两种方法都可以实现二维数组的转置的效果,\n 大家能够看出来,转置和交换轴的效果一样\n :return:\n \"\"\"\n t = np.arange(18).reshape(3, 6)\n print(t)\n print(t.transpose())\n print(t.T)\n\n\ndef numpy_index():\n \"\"\"\n 对于刚刚加载出来的数据,我如果只想选择其中的\n 某一列(行)我们应该怎么做呢?\n 其实操作很简单,和python中列表的操作一样\n :return:\n \"\"\"\n a = np.arange(12).reshape(3, 4)\n # 取一行\n print(a[1])\n # 取一列\n print(a[:, 2])\n # 取多行\n print(a[1:3])\n # 取多列\n print(a[:, 2:4])\n print(a[[1, 3], :])\n print(a[:, [2, 4]])\n return None\n\n\ndef numpy_modify():\n \"\"\"\n numpy中数值的修改,布尔索引,三元运算符\n 修改行列的值,我们能够很容易的实现,但是如果条件更复杂呢?\n 比如我们想要把t中小于10的数字替换为3\n :return:\n \"\"\"\n t = np.arange(24).reshape(4, 6)\n print(t[:, 2:4])\n t[:, 2:4] = 0\n print(t)\n # 把t中小于10的数字替换为3\n t1 = np.arange(24).reshape(4, 6)\n t1[t1 < 10] = 3\n print(t1)\n # 把t中小于10的数字替换为0,把大于20的替换为20\n t2 = np.arange(24).reshape(4, 6)\n t2 = np.where(t2 < 10, 0, 10)\n print(t2)\n return None\n\n\ndef numpy_clip():\n \"\"\"\n numpy中的clip(裁剪)\n :return:\n \"\"\"\n t = np.arange(12).reshape(3, 4)\n t = t.clip(5, 7)\n print(t)\n return None\n\n\ndef numpy_nan():\n \"\"\"\n numpy中的nan和inf\n :return:\n \"\"\"\n a = np.nan\n print(type(a))\n b = np.inf\n print(type(b))\n\n # numpy中的nan的注意点\n # 1.两个nan是不相等的\n print(np.nan == np.nan)\n print(np.nan != np.nan)\n # 2.判断nan的个数\n a = list([1, 2, np.nan])\n a = np.array(a)\n print(np.count_nonzero(a != a))\n # 3.nan数据进行赋值\n # 4.nan和任何数据计算都为nan\n a[np.isnan(a)] = 0\n print(a)\n return None\n\n\ndef numpy_mean():\n \"\"\"\n ndarry缺失值填充均值\n :return:\n \"\"\"\n # t中存在nan值,如何操作把其中的nan填充为每一列的均值\n t1 = np.array([[0., 1., 2., 3., 4., 5.],\n [6., 7., np.nan, 9., 10., 11.],\n [12., 13., 14., np.nan, 16., 17.],\n [18., 19., 20., 21., 22., 23.]])\n for i in range(t1.shape[1]): # 遍历每一列\n temp_col = t1[:, i] # 当前的一列\n nan_num = np.count_nonzero(temp_col != temp_col)\n if nan_num != 0: # 不为0,说明当前这一列中有nan\n # 当前一列不为nan的array\n temp_not_nan_col = temp_col[temp_col == temp_col]\n # 选中当前为nan的位置,把值赋值为不为nan的均值\n temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()\n print(t1)\n return None\n\n\ndef numpy_youtube_demo():\n \"\"\"\n 英国和美国各自youtube1000的数据结合之前的matplotlib\n 绘制出各自的评论数量的直方图\n :return:\n \"\"\"\n us_file_path = \"../data/US_video_data_numbers.csv\"\n uk_file_path = \"../data/GB_video_data_numbers.csv\"\n\n # t1 = np.loadtxt(us_file_path,delimiter=\",\",dtype=\"int\",unpack=True)\n t_us = np.loadtxt(us_file_path, delimiter=\",\", dtype=\"int\")\n # 取评论的数据\n t_us_comments = t_us[:, -1]\n # 选择比5000小的数据\n t_us_comments = t_us_comments[t_us_comments <= 5000]\n print(t_us_comments.max(), t_us_comments.min())\n\n d = 50\n bin_nums = (t_us_comments.max() - t_us_comments.min()) // d\n\n # 绘图\n plt.figure(figsize=(20, 8), dpi=80)\n plt.hist(t_us_comments, bin_nums)\n plt.show()\n return None\n\n\ndef numpy_youtube_demo2():\n \"\"\"\n 希望了解英国的youtube中视频的评论数和喜欢数的关系,应该如何绘制改图\n :return:\n \"\"\"\n us_file_path = \"../data/US_video_data_numbers.csv\"\n uk_file_path = \"../data/GB_video_data_numbers.csv\"\n\n # t1 = np.loadtxt(us_file_path,delimiter=\",\",dtype=\"int\",unpack=True)\n t_uk = np.loadtxt(uk_file_path, delimiter=\",\", dtype=\"int\")\n # 选择喜欢书比50万小的数据\n t_uk = t_uk[t_uk[:, 1] <= 500000]\n t_uk_comment = t_uk[:, -1]\n t_uk_like = t_uk[:, 1]\n\n plt.figure(figsize=(20, 8), dpi=80)\n plt.scatter(t_uk_like, t_uk_comment)\n plt.show()\n return None\n\n\ndef numpy_stack():\n \"\"\"\n 数组的拼接\n :return:\n \"\"\"\n t1 = np.arange(12).reshape(3, 4)\n t2 = np.arange(12, 24).reshape(3, 4)\n # 竖直拼接\n print(np.vstack((t1, t2)))\n # 水平拼接\n print(np.hstack((t1, t2)))\n return None\n\n\ndef numpy_exchange():\n \"\"\"\n 数组的行列交换\n :return:\n \"\"\"\n t = np.arange(12, 24).reshape(3, 4)\n # 行交换\n t1 = t\n t1[[1, 2], :] = t1[[2, 1], :]\n print(t1)\n # 列交换\n t2 = t\n t2[:, [0, 2]] = t2[:, [2, 0]]\n print(t2)\n return None\n\ndef numpy_country():\n \"\"\"\n 现在希望把之前案例中两个国家的数据方法一起来研究分析,\n 同时保留国家的信息(每条数据的国家来源),应该怎么办\n :return:\n \"\"\"\n us_data = \"../data/US_video_data_numbers.csv\"\n uk_data = \"../data/GB_video_data_numbers.csv\"\n\n # 加载国家数据\n us_data = np.loadtxt(us_data, delimiter=\",\", dtype=int)\n uk_data = np.loadtxt(uk_data, delimiter=\",\", dtype=int)\n\n # 添加国家信息\n # 构造全为0的数据\n zeros_data = np.zeros((us_data.shape[0], 1)).astype(int)\n ones_data = np.ones((uk_data.shape[0], 1)).astype(int)\n\n # 分别添加一列全为0,1的数组\n us_data = np.hstack((us_data, zeros_data))\n uk_data = np.hstack((uk_data, ones_data))\n\n # 拼接两组数据\n final_data = np.vstack((us_data, uk_data))\n print(final_data)\n return None\n\nif __name__ == \"__main__\":\n # numpy_base()\n # youtube_video()\n # numpy_t()\n # numpy_modify()\n # numpy_clip()\n # numpy_nan()\n # numpy_mean()\n # numpy_stack\n # numpy_youtube_demo()\n # numpy_youtube_demo2()\n # numpy_exchange()\n numpy_country()\n pass\n" }, { "alpha_fraction": 0.6207262873649597, "alphanum_fraction": 0.6425992846488953, "avg_line_length": 29, "blob_id": "df8c67b45027b4b28d7d03b91562b7dc5312d86e", "content_id": "73a82a361c6104636f6505a327865595d497a3ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4877, "license_type": "no_license", "max_line_length": 140, "num_lines": 157, "path": "/京东用户购买意向预测/JD_4_Xgboost模型.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import sys\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nimport operator\nfrom matplotlib import pylab as plt\nfrom datetime import datetime\nimport time\nfrom sklearn.model_selection import GridSearchCV\n\ndata = pd.read_csv('./data/train_set.csv')\nprint(data.head())\nprint(data.columns)\n\ndata_x = data.loc[:,data.columns != 'label']\ndata_y = data.loc[:,data.columns == 'label']\n\nprint(data_x.head())\nprint(data_y.head())\n\nx_train, x_test, y_train, y_test = train_test_split(data_x,data_y,test_size = 0.2, random_state = 0)\nprint(x_test.shape)\n\nx_val = x_test.iloc[:1500,:]\ny_val = y_test.iloc[:1500,:]\n\nx_test = x_test.iloc[1500:,:]\ny_test = y_test.iloc[1500:,:]\n\nprint (x_val.shape)\nprint (x_test.shape)\n\ndel x_train['user_id']\ndel x_train['sku_id']\n\ndel x_val['user_id']\ndel x_val['sku_id']\n\nprint(x_train.head())\n\ndtrain = xgb.DMatrix(x_train, label=y_train)\ndvalid = xgb.DMatrix(x_val, label=y_val)\n\nparam = {'n_estimators': 4000, 'max_depth': 3, 'min_child_weight': 5, 'gamma': 0, 'subsample': 1.0,\n 'colsample_bytree': 0.8, 'scale_pos_weight':10, 'eta': 0.1, 'silent': 1, 'objective': 'binary:logistic',\n 'eval_metric':'auc'}\n\nnum_round = param['n_estimators']\n\nplst = param.items()\nevallist = [(dtrain, 'train'), (dvalid, 'eval')]\nbst = xgb.train(plst, dtrain, num_round, evallist, early_stopping_rounds=10)\nbst.save_model('bst.model')\n\nprint (bst.attributes())\n\ndef create_feature_map(features):\n outfile = open(r'xgb.fmap', 'w')\n i = 0\n for feat in features:\n outfile.write('{0}\\t{1}\\tq\\n'.format(i, feat))\n i = i + 1\n outfile.close()\n\n\nfeatures = list(x_train.columns[:])\ncreate_feature_map(features)\n\ndef feature_importance(bst_xgb):\n importance = bst_xgb.get_fscore(fmap=r'xgb.fmap')\n importance = sorted(importance.items(), key=operator.itemgetter(1), reverse=True)\n\n df = pd.DataFrame(importance, columns=['feature', 'fscore'])\n df['fscore'] = df['fscore'] / df['fscore'].sum()\n file_name = './data/feature_importance_' + str(datetime.now().date())[5:] + '.csv'\n df.to_csv(file_name)\n\nfeature_importance(bst)\n\nfi = pd.read_csv('./data/feature_importance_10-24.csv')\nfi.sort_values(\"fscore\", inplace=True, ascending=False)\nprint(fi.head())\n\nprint(x_test.head())\n\nusers = x_test[['user_id', 'sku_id', 'cate']].copy()\ndel x_test['user_id']\ndel x_test['sku_id']\nx_test_DMatrix = xgb.DMatrix(x_test)\ny_pred = bst.predict(x_test_DMatrix, ntree_limit=bst.best_ntree_limit)\n\nx_test['pred_label'] = y_pred\nprint(x_test.head())\n\ndef label(column):\n if column['pred_label'] > 0.5:\n #rint ('yes')\n column['pred_label'] = 1\n else:\n column['pred_label'] = 0\n return column\nx_test = x_test.apply(label,axis = 1)\nprint(x_test.head())\n\nx_test['true_label'] = y_test\nprint(x_test.head())\n\n#x_test users = x_test[['user_id', 'sku_id', 'cate']].copy()\nx_test['user_id'] = users['user_id']\nx_test['sku_id'] = users['sku_id']\nprint(x_test.head())\n\n# 所有购买用户\nall_user_set = x_test[x_test['true_label']==1]['user_id'].unique()\nprint (len(all_user_set))\n# 所有预测购买的用户\nall_user_test_set = x_test[x_test['pred_label'] == 1]['user_id'].unique()\nprint (len(all_user_test_set))\nall_user_test_item_pair = x_test[x_test['pred_label'] == 1]['user_id'].map(str) + '-' + x_test[x_test['pred_label'] == 1]['sku_id'].map(str)\nall_user_test_item_pair = np.array(all_user_test_item_pair)\nprint (len(all_user_test_item_pair))\n#print (all_user_test_item_pair)\n\npos, neg = 0,0\nfor user_id in all_user_test_set:\n if user_id in all_user_set:\n pos += 1\n else:\n neg += 1\nall_user_acc = 1.0 * pos / ( pos + neg)\nall_user_recall = 1.0 * pos / len(all_user_set)\nprint ('所有用户中预测购买用户的准确率为 ' + str(all_user_acc))\nprint ('所有用户中预测购买用户的召回率' + str(all_user_recall))\n\n#所有实际商品对\nall_user_item_pair = x_test[x_test['true_label']==1]['user_id'].map(str) + '-' + x_test[x_test['true_label']==1]['sku_id'].map(str)\nall_user_item_pair = np.array(all_user_item_pair)\n#print (len(all_user_item_pair))\n#print(all_user_item_pair)\npos, neg = 0, 0\nfor user_item_pair in all_user_test_item_pair:\n #print (user_item_pair)\n if user_item_pair in all_user_item_pair:\n pos += 1\n else:\n neg += 1\nall_item_acc = 1.0 * pos / ( pos + neg)\nall_item_recall = 1.0 * pos / len(all_user_item_pair)\nprint ('所有用户中预测购买商品的准确率为 ' + str(all_item_acc))\nprint ('所有用户中预测购买商品的召回率' + str(all_item_recall))\nF11 = 6.0 * all_user_recall * all_user_acc / (5.0 * all_user_recall + all_user_acc)\nF12 = 5.0 * all_item_acc * all_item_recall / (2.0 * all_item_recall + 3 * all_item_acc)\nscore = 0.4 * F11 + 0.6 * F12\nprint ('F11=' + str(F11))\nprint ('F12=' + str(F12))\nprint ('score=' + str(score))" }, { "alpha_fraction": 0.6303669214248657, "alphanum_fraction": 0.6397345662117004, "avg_line_length": 25.968421936035156, "blob_id": "a94ec7fa44c2c115cee9309e678d249e579f9de2", "content_id": "2d76ec7e200db2cc266b14e694011ded7b312f08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3068, "license_type": "no_license", "max_line_length": 78, "num_lines": 95, "path": "/电商产品评论数据情感分析/chapter12/demo/code/02_评论分词.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# 代码12-3\nimport pandas as pd\nimport re\nimport jieba.posseg as psg\nimport numpy as np\n# 1 评论去重的代码\n\n# 去重,去除完全重复的数据\nreviews = pd.read_csv(\"../tmp/reviews.csv\")\nreviews = reviews[['content', 'content_type']].drop_duplicates()\ncontent = reviews['content']\n\n\n\n# 2 数据清洗\n\n# 去除去除英文、数字等\n# 由于评论主要为京东美的电热水器的评论,因此去除这些词语\nstrinfo = re.compile('[0-9a-zA-Z]|京东|美的|电热水器|热水器|')\ncontent = content.apply(lambda x: strinfo.sub('', x))\n\n# 3 分词、词性标注、去除停用词代码\n# 分词\nworker = lambda s: [(x.word, x.flag) for x in psg.cut(s)] # 自定义简单分词函数\nseg_word = content.apply(worker) \n\n# 将词语转为数据框形式,一列是词,一列是词语所在的句子ID,最后一列是词语在该句子的位置\nn_word = seg_word.apply(lambda x: len(x)) # 每一评论中词的个数\n\nn_content = [[x+1]*y for x,y in zip(list(seg_word.index), list(n_word))]\nindex_content = sum(n_content, []) # 将嵌套的列表展开,作为词所在评论的id\n\nseg_word = sum(seg_word, [])\nword = [x[0] for x in seg_word] # 词\n\nnature = [x[1] for x in seg_word] # 词性\n\ncontent_type = [[x]*y for x,y in zip(list(reviews['content_type']), \n list(n_word))]\ncontent_type = sum(content_type, []) # 评论类型\n\nresult = pd.DataFrame({\"index_content\":index_content, \n \"word\":word,\n \"nature\":nature,\n \"content_type\":content_type}) \n\n# 删除标点符号\nresult = result[result['nature'] != 'x'] # x表示标点符号\n\n# 删除停用词\nstop_path = open(\"../data/stoplist.txt\", 'r',encoding='UTF-8')\nstop = stop_path.readlines()\nstop = [x.replace('\\n', '') for x in stop]\nword = list(set(word) - set(stop))\nresult = result[result['word'].isin(word)]\n\n# 构造各词在对应评论的位置列\nn_word = list(result.groupby(by = ['index_content'])['index_content'].count())\nindex_word = [list(np.arange(0, y)) for y in n_word]\nindex_word = sum(index_word, []) # 表示词语在改评论的位置\n\n# 合并评论id,评论中词的id,词,词性,评论类型\nresult['index_word'] = index_word\n\n\n\n# 代码12-4\n\n# 提取含有名词类的评论\nind = result[['n' in x for x in result['nature']]]['index_content'].unique()\nresult = result[[x in ind for x in result['index_content']]]\n\n\n\n# 代码12-5\n\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\n\nfrequencies = result.groupby(by = ['word'])['word'].count()\nfrequencies = frequencies.sort_values(ascending = False)\nbackgroud_Image=plt.imread('../data/pl.jpg')\nwordcloud = WordCloud(font_path=\"G:/workspace/font/STZHONGS.ttf\",\n max_words=100,\n background_color='white',\n mask=backgroud_Image)\nmy_wordcloud = wordcloud.fit_words(frequencies)\nplt.imshow(my_wordcloud)\nplt.axis('off') \nplt.show()\n\n# 将结果写出\nresult.to_csv(\"../tmp/word.csv\", index = False, encoding = 'utf-8')\n" }, { "alpha_fraction": 0.6267251968383789, "alphanum_fraction": 0.6604628562927246, "avg_line_length": 28.94989585876465, "blob_id": "bed438acb1b31cc6695e1612e07a432d3ef4efef", "content_id": "2ba602149344e6f89188e729ff2b69974d917fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17822, "license_type": "no_license", "max_line_length": 226, "num_lines": 479, "path": "/京东用户购买意向预测/JD_1_数据清洗.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\nimport numpy\n\"\"\"\n(1)- 数据清洗\n\n主题:京东用户购买意向预测\n\n故事背景:\n\n京东作为中国最大的自营式电商,在保持高速发展的同时,沉淀了数亿的忠实用户,积累了海量的真实数据。\n如何从历史数据中找出规律,去预测用户未来的购买需求,让最合适的商品遇见最需要的人,是大数据应用\n在精准营销中的关键问题,也是所有电商平台在做智能化升级时所需要的核心技术。 以京东商城真实的用户、\n商品和行为数据(脱敏后)为基础,通过数据挖掘的技术和机器学习的算法,构建用户购买商品的预测模型,\n输出高潜用户和目标商品的匹配结果,为精准营销提供高质量的目标群体。\n\n目标:使用京东多个品类下商品的历史销售数据,构建算法模型,预测用户在未来5天内,对某个目标品类\n下商品的购买意向。\n\n数据集:\n•这里涉及到的数据集是京东最新的数据集:\n•JData_User.csv 用户数据集 105,321个用户\n•JData_Comment.csv 商品评论 558,552条记录\n•JData_Product.csv 预测商品集合 24,187条记录\n•JData_Action_201602.csv 2月份行为交互记录 11,485,424条记录\n•JData_Action_201603.csv 3月份行为交互记录 25,916,378条记录\n•JData_Action_201604.csv 4月份行为交互记录 13,199,934条记录\n\n数据挖掘流程:\n\n(一).数据清洗\n1. 数据集完整性验证\n2. 数据集中是否存在缺失值\n3. 数据集中各特征数值应该如何处理\n4. 哪些数据是我们想要的,哪些是可以过滤掉的\n5. 将有价值数据信息做成新的数据源\n6. 去除无行为交互的商品和用户\n7. 去掉浏览量很大而购买量很少的用户(惰性用户或爬虫用户)\n\n(二).数据理解与分析\n1. 掌握各个特征的含义\n2. 观察数据有哪些特点,是否可利用来建模\n3. 可视化展示便于分析\n4. 用户的购买意向是否随着时间等因素变化\n\n(三).特征提取\n1. 基于清洗后的数据集哪些特征是有价值\n2. 分别对用户与商品以及其之间构成的行为进行特征提取\n3. 行为因素中哪些是核心?如何提取?\n4. 瞬时行为特征or累计行为特征?\n\n(四).模型建立\n1. 使用机器学习算法进行预测 \n2. 参数设置与调节\n3. 数据集切分?\n\"\"\"\n\n\"\"\"\n数据集验证\n首先检查JData_User中的用户和JData_Action中的用户是否一致\n保证行为数据中的所产生的行为均由用户数据中的用户产生(但是可能存在用户在行为数据中无行为)\n\n思路:利用pd.Merge连接sku 和 Action中的sku, 观察Action中的数据是否减少 Example:\n\"\"\"\nimport pandas as pd\n# test sample\ndf1 = pd.DataFrame({'sku':['a','a','e','c'],'data':[1,1,2,3]})\ndf2 = pd.DataFrame({'sku':['a','b','f']})\ndf3 = pd.DataFrame({'sku':['a','b','d']})\ndf4 = pd.DataFrame({'sku':['a','b','c','d']})\n# print (pd.merge(df2,df1))\n# print (pd.merge(df1,df2))\n# print (pd.merge(df3,df1))\n# print (pd.merge(df4,df1))\n#print (pd.merge(df1,df3))\n\ndef user_action_check():\n df_user = pd.read_csv('./data/JData_User.csv',encoding='gbk')\n df_sku = df_user.loc[:,'user_id'].to_frame()\n df_month2 = pd.read_csv('./data/JData_Action_201602.csv',encoding='gbk')\n print ('Is action of Feb. from User file? ', len(df_month2) == len(pd.merge(df_sku,df_month2)))\n df_month3 = pd.read_csv('./data/JData_Action_201603.csv',encoding='gbk')\n print ('Is action of Mar. from User file? ', len(df_month3) == len(pd.merge(df_sku,df_month3)))\n df_month4 = pd.read_csv('./data/JData_Action_201604.csv',encoding='gbk')\n print ('Is action of Apr. from User file? ', len(df_month4) == len(pd.merge(df_sku,df_month4)))\n\n# user_action_check()\n\"\"\"\nIs action of Feb. from User file? True\nIs action of Mar. from User file? True\nIs action of Apr. from User file? True\n结论: User数据集中的用户和交互行为数据集中的用户完全一致\n根据merge前后的数据量比对,能保证Action中的用户ID是User中的ID的子集\n\"\"\"\n\n\"\"\"\n检查是否有重复记录\n\n除去各个数据文件中完全重复的记录,可能解释是重复数据是有意义的,比如用户同时购买多件商品,\n同时添加多个数量的商品到购物车等\n\"\"\"\ndef deduplicate(filepath, filename, newpath):\n df_file = pd.read_csv(filepath,encoding='gbk')\n before = df_file.shape[0]\n df_file.drop_duplicates(inplace=True)\n after = df_file.shape[0]\n n_dup = before-after\n print ('No. of duplicate records for ' + filename + ' is: ' + str(n_dup))\n if n_dup != 0:\n df_file.to_csv(newpath, index=None)\n else:\n print ('no duplicate records in ' + filename)\n\n# deduplicate('data/JData_Action_201602.csv', 'Feb. action', 'data/JData_Action_201602_dedup.csv')\n# deduplicate('data/JData_Action_201603.csv', 'Mar. action', './data/JData_Action_201603_dedup.csv')\n# deduplicate('data/JData_Action_201604.csv', 'Feb. action', './data/JData_Action_201604_dedup.csv')\n# deduplicate('data/JData_Comment.csv', 'Comment', './data/JData_Comment_dedup.csv')\n# deduplicate('data/JData_Product.csv', 'Product', './data/JData_Product_dedup.csv')\n# deduplicate('data/JData_User.csv', 'User', './data/JData_User_dedup.csv')\n\n\n# df_month2 = pd.read_csv('./data/JData_Action_201602.csv',encoding='gbk')\n# IsDuplicated = df_month2.duplicated()\n# df_d=df_month2[IsDuplicated]\n# print(df_d.groupby('type').count()) #发现重复数据大多数都是由于浏览(1),或者点击(6)产生\n\n\"\"\"\n检查是否存在注册时间在2016年-4月-15号之后的用户\n\"\"\"\n# df_user = pd.read_csv('./data/JData_User.csv',encoding='gbk')\n# df_user['user_reg_tm']=pd.to_datetime(df_user['user_reg_tm'])\n# user = df_user.loc[df_user.user_reg_tm >= '2016-4-15']\n# print(user)\n\n\"\"\"\n由于注册时间是京东系统错误造成,如果行为数据中没有在4月15号之后的数据的话,\n那么说明这些用户还是正常用户,并不需要删除。\n\"\"\"\n# df_month = pd.read_csv('data\\JData_Action_201604.csv')\n# df_month['time'] = pd.to_datetime(df_month['time'])\n# month = df_month.loc[df_month.time >= '2016-4-16']\n# print(month)\n\"\"\"\n结论:说明用户没有异常操作数据,所以这一批用户不删除\n\"\"\"\n\n\"\"\"\n行为数据中的user_id为浮点型,进行INT类型转换\n\"\"\"\n# df_month = pd.read_csv('./data/JData_Action_201602.csv',encoding='gbk')\n# df_month['user_id'] = df_month['user_id'].apply(lambda x:int(x))\n# print (df_month['user_id'].dtype)\n# df_month.to_csv('./data/JData_Action_201602.csv',index=None)\n# df_month = pd.read_csv('./data/JData_Action_201603.csv',encoding='gbk')\n# df_month['user_id'] = df_month['user_id'].apply(lambda x:int(x))\n# print (df_month['user_id'].dtype)\n# df_month.to_csv('./data/JData_Action_201603.csv',index=None)\n# df_month = pd.read_csv('./data/JData_Action_201604.csv',encoding='gbk')\n# df_month['user_id'] = df_month['user_id'].apply(lambda x:int(x))\n# print (df_month['user_id'].dtype)\n# df_month.to_csv('./data/JData_Action_201604.csv',index=None)\n\n\"\"\"\n年龄区间的处理\n\"\"\"\ndf_user = pd.read_csv('./data/JData_User.csv',encoding='gbk')\ndef tranAge(x):\n if x == u'15岁以下':\n x='1'\n elif x==u'16-25岁':\n x='2'\n elif x==u'26-35岁':\n x='3'\n elif x==u'36-45岁':\n x='4'\n elif x==u'46-55岁':\n x='5'\n elif x==u'56岁以上':\n x='6'\n return x\ndf_user['age']=df_user['age'].apply(tranAge)\nprint (df_user.groupby(df_user['age']).count())\ndf_user.to_csv('./data/JData_User.csv',index=None)\n\n\"\"\"\n为了能够进行上述清洗,在此首先构造了简单的用户(user)行为特征和商品(item)行为特征,\n对应于两张表user_table和item_table\n\nuser_table\n •user_table特征包括:\n •user_id(用户id),age(年龄),sex(性别),\n •user_lv_cd(用户级别),browse_num(浏览数),\n •addcart_num(加购数),delcart_num(删购数),\n •buy_num(购买数),favor_num(收藏数),\n •click_num(点击数),buy_addcart_ratio(购买加购转化率),\n •buy_browse_ratio(购买浏览转化率),\n •buy_click_ratio(购买点击转化率),\n •buy_favor_ratio(购买收藏转化率)\n \nitem_table特征包括:\n •sku_id(商品id),attr1,attr2,\n •attr3,cate,brand,browse_num,\n •addcart_num,delcart_num,\n •buy_num,favor_num,click_num,\n •buy_addcart_ratio,buy_browse_ratio,\n •buy_click_ratio,buy_favor_ratio,\n •comment_num(评论数),\n •has_bad_comment(是否有差评),\n •bad_comment_rate(差评率)\n\"\"\"\n\n\"\"\"\n构建User_table\n\"\"\"\n#定义文件名\nACTION_201602_FILE = \"./data/JData_Action_201602.csv\"\nACTION_201603_FILE = \"./data/JData_Action_201603.csv\"\nACTION_201604_FILE = \"./data/JData_Action_201604.csv\"\nCOMMENT_FILE = \"./data/JData_Comment.csv\"\nPRODUCT_FILE = \"./data/JData_Product.csv\"\nUSER_FILE = \"./data/JData_User.csv\"\nUSER_TABLE_FILE = \"./data/User_table.csv\"\nITEM_TABLE_FILE = \"./data/Item_table.csv\"\n\n# 导入相关包\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\n\n# 功能函数: 对每一个user分组的数据进行统计\ndef add_type_count(group):\n behavior_type = group.type.astype(int)\n # 用户行为类别\n type_cnt = Counter(behavior_type)\n # 1: 浏览 2: 加购 3: 删除\n # 4: 购买 5: 收藏 6: 点击\n group['browse_num'] = type_cnt[1]\n group['addcart_num'] = type_cnt[2]\n group['delcart_num'] = type_cnt[3]\n group['buy_num'] = type_cnt[4]\n group['favor_num'] = type_cnt[5]\n group['click_num'] = type_cnt[6]\n\n return group[['user_id', 'browse_num', 'addcart_num',\n 'delcart_num', 'buy_num', 'favor_num',\n 'click_num']]\n\n\"\"\"\n由于用户行为数据量较大,一次性读入可能造成内存错误(Memory Error),因而使用\npandas的分块(chunk)读取.\n\"\"\"\n\n#对action数据进行统计。根据自己调节chunk_size大小\ndef get_from_action_data(fname, chunk_size=50000):\n reader = pd.read_csv(fname, header=0, iterator=True,encoding='gbk')\n chunks = []\n loop = True\n while loop:\n try:\n # 只读取user_id和type两个字段\n chunk = reader.get_chunk(chunk_size)[[\"user_id\", \"type\"]]\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n # 将块拼接为pandas dataframe格式\n df_ac = pd.concat(chunks, ignore_index=True)\n # 按user_id分组,对每一组进行统计,as_index 表示无索引形式返回数据\n df_ac = df_ac.groupby(['user_id'], as_index=False).apply(add_type_count)\n # 将重复的行丢弃\n df_ac = df_ac.drop_duplicates('user_id')\n\n return df_ac\n\n\n# 将各个action数据的统计量进行聚合\ndef merge_action_data():\n df_ac = []\n df_ac.append(get_from_action_data(fname=ACTION_201602_FILE))\n df_ac.append(get_from_action_data(fname=ACTION_201603_FILE))\n df_ac.append(get_from_action_data(fname=ACTION_201604_FILE))\n\n df_ac = pd.concat(df_ac, ignore_index=True)\n # 用户在不同action表中统计量求和\n df_ac = df_ac.groupby(['user_id'], as_index=False).sum()\n #  构造转化率字段\n df_ac['buy_addcart_ratio'] = df_ac['buy_num'] / df_ac['addcart_num']\n df_ac['buy_browse_ratio'] = df_ac['buy_num'] / df_ac['browse_num']\n df_ac['buy_click_ratio'] = df_ac['buy_num'] / df_ac['click_num']\n df_ac['buy_favor_ratio'] = df_ac['buy_num'] / df_ac['favor_num']\n\n # 将大于1的转化率字段置为1(100%)\n df_ac.ix[df_ac['buy_addcart_ratio'] > 1., 'buy_addcart_ratio'] = 1.\n df_ac.ix[df_ac['buy_browse_ratio'] > 1., 'buy_browse_ratio'] = 1.\n df_ac.ix[df_ac['buy_click_ratio'] > 1., 'buy_click_ratio'] = 1.\n df_ac.ix[df_ac['buy_favor_ratio'] > 1., 'buy_favor_ratio'] = 1.\n\n return df_ac\n\n# 从FJData_User表中抽取需要的字段\ndef get_from_jdata_user():\n df_usr = pd.read_csv(USER_FILE, header=0)\n df_usr = df_usr[[\"user_id\", \"age\", \"sex\", \"user_lv_cd\"]]\n return df_usr\n\n# user_base = get_from_jdata_user()\n# user_behavior = merge_action_data()\n#\n# # 连接成一张表,类似于SQL的左连接(left join)\n# user_behavior = pd.merge(user_base, user_behavior, on=['user_id'], how='left')\n# # 保存为user_table.csv\n# user_behavior.to_csv(USER_TABLE_FILE, index=False)\n#\n# user_table = pd.read_csv(USER_TABLE_FILE)\n# user_table.head()\n\n\"\"\"\n构建Item_table\n\"\"\"\n#定义文件名\nACTION_201602_FILE = \"data/JData_Action_201602.csv\"\nACTION_201603_FILE = \"data/JData_Action_201603.csv\"\nACTION_201604_FILE = \"data/JData_Action_201604.csv\"\nCOMMENT_FILE = \"data/JData_Comment.csv\"\nPRODUCT_FILE = \"data/JData_Product.csv\"\nUSER_FILE = \"data/JData_User.csv\"\nUSER_TABLE_FILE = \"data/User_table.csv\"\nITEM_TABLE_FILE = \"data/Item_table.csv\"\n\n# 导入相关包\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\n\n# 读取Product中商品\ndef get_from_jdata_product():\n df_item = pd.read_csv(PRODUCT_FILE, header=0,encoding='gbk')\n return df_item\n\n# 对每一个商品分组进行统计\ndef add_type_count(group):\n behavior_type = group.type.astype(int)\n type_cnt = Counter(behavior_type)\n\n group['browse_num'] = type_cnt[1]\n group['addcart_num'] = type_cnt[2]\n group['delcart_num'] = type_cnt[3]\n group['buy_num'] = type_cnt[4]\n group['favor_num'] = type_cnt[5]\n group['click_num'] = type_cnt[6]\n\n return group[['sku_id', 'browse_num', 'addcart_num',\n 'delcart_num', 'buy_num', 'favor_num',\n 'click_num']]\n\n#对action中的数据进行统计\ndef get_from_action_data(fname, chunk_size=50000):\n reader = pd.read_csv(fname, header=0, iterator=True)\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(chunk_size)[[\"sku_id\", \"type\"]]\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n\n df_ac = pd.concat(chunks, ignore_index=True)\n\n df_ac = df_ac.groupby(['sku_id'], as_index=False).apply(add_type_count)\n # Select unique row\n df_ac = df_ac.drop_duplicates('sku_id')\n\n return df_ac\n\n# 获取评论中的商品数据,如果存在某一个商品有两个日期的评论,我们取最晚的那一个\ndef get_from_jdata_comment():\n df_cmt = pd.read_csv(COMMENT_FILE, header=0)\n df_cmt['dt'] = pd.to_datetime(df_cmt['dt'])\n # find latest comment index\n idx = df_cmt.groupby(['sku_id'])['dt'].transform(max) == df_cmt['dt']\n df_cmt = df_cmt[idx]\n\n return df_cmt[['sku_id', 'comment_num',\n 'has_bad_comment', 'bad_comment_rate']]\n\ndef merge_action_data():\n df_ac = []\n df_ac.append(get_from_action_data(fname=ACTION_201602_FILE))\n df_ac.append(get_from_action_data(fname=ACTION_201603_FILE))\n df_ac.append(get_from_action_data(fname=ACTION_201604_FILE))\n\n df_ac = pd.concat(df_ac, ignore_index=True)\n df_ac = df_ac.groupby(['sku_id'], as_index=False).sum()\n\n df_ac['buy_addcart_ratio'] = df_ac['buy_num'] / df_ac['addcart_num']\n df_ac['buy_browse_ratio'] = df_ac['buy_num'] / df_ac['browse_num']\n df_ac['buy_click_ratio'] = df_ac['buy_num'] / df_ac['click_num']\n df_ac['buy_favor_ratio'] = df_ac['buy_num'] / df_ac['favor_num']\n\n df_ac.ix[df_ac['buy_addcart_ratio'] > 1., 'buy_addcart_ratio'] = 1.\n df_ac.ix[df_ac['buy_browse_ratio'] > 1., 'buy_browse_ratio'] = 1.\n df_ac.ix[df_ac['buy_click_ratio'] > 1., 'buy_click_ratio'] = 1.\n df_ac.ix[df_ac['buy_favor_ratio'] > 1., 'buy_favor_ratio'] = 1.\n\n return df_ac\n\n\nitem_base = get_from_jdata_product()\nitem_behavior = merge_action_data()\nitem_comment = get_from_jdata_comment()\n\n# SQL: left join\nitem_behavior = pd.merge(\n item_base, item_behavior, on=['sku_id'], how='left')\nitem_behavior = pd.merge(\n item_behavior, item_comment, on=['sku_id'], how='left')\n\nitem_behavior.to_csv(ITEM_TABLE_FILE, index=False)\n\nitem_table = pd.read_csv(ITEM_TABLE_FILE)\nitem_table.head()\n\n\n\"\"\"\n数据清洗\n\"\"\"\n# 用户清洗\nimport pandas as pd\ndf_user = pd.read_csv('data/User_table.csv',header=0)\npd.options.display.float_format = '{:,.3f}'.format #输出格式设置,保留三位小数\ndf_user.describe()\n\"\"\"\n由上述统计信息发现: 第一行中根据User_id统计发现有105321个用户,发现有3个用户没有\nage,sex字段,而且根据浏览、加购、删购、购买等记录却只有105180条记录,说明存在用户\n无任何交互记录,因此可以删除上述用户。\n\n删除没有age,sex字段的用户\n\"\"\"\ndf_user[df_user['age'].isnull()]\ndelete_list = df_user[df_user['age'].isnull()].index\ndf_user.drop(delete_list,axis=0,inplace=True)\n\n\"\"\"\n删除无交互记录的用户\n\"\"\"\n#删除无交互记录的用户\ndf_naction = df_user[(df_user['browse_num'].isnull()) & (df_user['addcart_num'].isnull()) & (df_user['delcart_num'].isnull()) & (df_user['buy_num'].isnull()) & (df_user['favor_num'].isnull()) & (df_user['click_num'].isnull())]\ndf_user.drop(df_naction.index,axis=0,inplace=True)\nprint (len(df_user))\n\n\"\"\"\n统计并删除无购买记录的用户\n\"\"\"\n#统计无购买记录的用户\ndf_bzero = df_user[df_user['buy_num']==0]\n#输出购买数为0的总记录数\nprint (len(df_bzero))\n\n#删除无购买记录的用户\ndf_user = df_user[df_user['buy_num']!=0]\n\ndf_user.describe()\n\n# 删除爬虫及惰性用户\n# 由上表所知,浏览购买转换比和点击购买转换比均值为0.018,0.030,因此这里认为浏览购买转换比和点\n# 击购买转换比小于0.0005的用户为惰性用户\nbindex = df_user[df_user['buy_browse_ratio']<0.0005].index\nprint (len(bindex))\ndf_user.drop(bindex,axis=0,inplace=True)\n\ncindex = df_user[df_user['buy_click_ratio']<0.0005].index\nprint (len(cindex))\ndf_user.drop(cindex,axis=0,inplace=True)\n\nprint(df_user.describe())\n\n\"\"\"\n最后这29070个用户为最终预测用户数据集\n\"\"\"" }, { "alpha_fraction": 0.5927641987800598, "alphanum_fraction": 0.6097506880760193, "avg_line_length": 31.61870574951172, "blob_id": "440c67754ccba14507144025487d9c9724563ccc", "content_id": "eb89f785ca481b784abfb26549b2c963b2fd59d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5341, "license_type": "no_license", "max_line_length": 93, "num_lines": 139, "path": "/泰迪杯.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import model_selection\nimport jieba\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import classification_report\ndef taidi1():\n \"\"\"\n 泰迪杯第一问\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n df2 = pd.read_excel(\"../data/2.xlsx\")\n # 去除空格,制表符\n df2[\"留言详情\"] = df2[\"留言详情\"].apply(lambda x:x.replace('\\n', '').replace('\\t', ''))\n # 2个series合并为DataFrame\n # df_data = list(zip(df2[\"留言详情\"],df2[\"留言主题\"]))\n df_data = np.array(df2[\"留言详情\"])\n df_target = np.array(df2[\"一级分类\"])\n # 数据分割\n x_train, x_test, y_train, y_test = train_test_split(df_data, df_target, test_size=0.25)\n # 对数据进行特征抽取,实例化TF-IDF\n tf = TfidfVectorizer()\n # 以训练集中的词的列表进行每篇文章重要性统计\n x_train = tf.fit_transform(x_train)\n x_test = tf.transform(x_test)\n # 进行朴素贝叶斯算法的预测\n mlt = MultinomialNB(alpha=1.0)\n mlt.fit(x_train, y_train)\n y_predict = mlt.predict(x_test)\n f1 = model_selection.cross_val_score(mlt,\n x_train, y_train, scoring='f1_weighted', cv=5)\n print(\"F1 score: \" + str(round(100 * f1.mean(), 2)) + \"%\")\n print(\"预测测试集前10个结果:\", y_predict[:10])\n # 获取预测的准确率\n print(\"测试集准确率为:\", mlt.score(x_test, y_test))\n return None\n\n\ndef taidi():\n \"\"\"\n 泰迪杯第一问\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n df2 = pd.read_excel(\"../data/2test.xlsx\")\n # 去除空格,制表符\n df2[\"留言详情\"] = df2[\"留言详情\"].apply(lambda x:x.replace('\\n', '').replace('\\t', ''))\n # 2个series合并为DataFrame\n # df_data = list(zip(df2[\"留言详情\"],df2[\"留言主题\"]))\n df_data = df2[\"留言详情\"].values.tolist()\n # df_target = df2[\"一级标签\"].values.tolist()\n # # 数据分割\n # x_train, x_test, y_train, y_test = train_test_split(df_data, df_target, test_size=0.25)\n # print(type(x_test))\n # print(type(df_data))\n # # 对数据进行特征抽取,实例化TF-IDF\n # tf = TfidfVectorizer()\n # # 以训练集中的词的列表进行每篇文章重要性统计\n # x_train = tf.fit_transform(x_train)\n # x_test = tf.transform(x_test)\n # print(x_train.shape)\n # print(x_test.shape)\n # # 进行朴素贝叶斯算法的预测\n # mlt = MultinomialNB(alpha=1.0)\n # mlt.fit(x_train, y_train)\n # y_predict = mlt.predict(x_test)\n # f1 = model_selection.cross_val_score(mlt,\n # x_train, y_train, scoring='f1_weighted', cv=5)\n # print(\"F1 score: \" + str(round(100 * f1.mean(), 2)) + \"%\")\n # print(\"预测测试集前10个结果:\", y_predict[:10])\n # # 获取预测的准确率\n # print(\"测试集准确率为:\", mlt.score(x_test, y_test))\n #\n from sklearn.externals import joblib\n # joblib.dump(mlt, \"./mlt.pkl\")\n #\n # # 测试保存的模型\n model = joblib.load(\"./mlt.pkl\")\n # predict_result = standard_y.inverse_transform(model.predict(x_test))\n predict_result = model.predict([df_data])\n print(predict_result)\n\n\n return None\n\n\ndef taidi3():\n \"\"\"\n 泰迪杯第一问\n :return:\n \"\"\"\n # 获取目标值数据、特征值数据文件\n df2 = pd.read_excel(\"../data/2.xlsx\")\n # 去除空格,制表符\n df2[\"留言详情\"] = df2[\"留言详情\"].apply(lambda x:x.replace('\\n', '').replace('\\t', ''))\n # 2个series合并为DataFrame\n # df_data = list(zip(df2[\"留言详情\"],df2[\"留言主题\"]))\n df_data = df2[\"留言详情\"].values.tolist()\n sent_words = [list(jieba.cut(sent)) for sent in df_data]\n document = [\" \".join(sent) for sent in sent_words]\n # 对数据进行特征抽取,实例化TF-IDF\n tfidf_model = TfidfVectorizer().fit(document)\n # print(tfidf_model.vocabulary_)\n sparse_result = tfidf_model.transform(document)\n print(sparse_result)\n return None\n\n\ndef taidi4():\n df2 = pd.read_excel(\"../data/2.xlsx\")\n # 去除空格,制表符 \n df2[\"留言详情\"] = df2[\"留言详情\"].apply(lambda x: x.replace('\\n', '').replace('\\t', ''))\n df_data = df2[\"留言详情\"].values.tolist()\n df_target = df2[\"一级标签\"].values.tolist()\n # 拆分数据集\n x_train, x_test, y_train, y_test = train_test_split(df_data, df_target, test_size=0.25)\n # 实例化CountVectorizer()\n vectorizer = CountVectorizer()\n # 调用fit_transfrom输入并转换数据\n words = vectorizer.fit_transform(x_train)\n test_word = vectorizer.transform(x_test)\n # 实例化多项式分布的朴素贝叶斯\n clf = MultinomialNB().fit(words,y_train)\n predicted = clf.predict(test_word)\n for doc,category in zip(x_test,predicted):\n print(doc,\":\",category)\n print(\"每个类别的精确率和召回率:\\n\",classification_report(y_test, predicted))\n pass\nif __name__==\"__main__\":\n taidi()\n # taidi1()\n # taidi3()\n # taidi4()\n pass" }, { "alpha_fraction": 0.7057822942733765, "alphanum_fraction": 0.7176870703697205, "avg_line_length": 24.565217971801758, "blob_id": "85ae74a438799f21c00e5af8046db6fef9f624a4", "content_id": "bd5e0e5ed9ecbb09fe1d7861a1a2e68ae34f2ddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/商品零售购物篮分析/demo/code/02_data_clean.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# 5 数据转换\n\nimport pandas as pd\ninputfile='../data/GoodsOrder.csv'\ndata = pd.read_csv(inputfile,encoding = 'gbk')\n\n# 根据id对“Goods”列合并,并使用“,”将各商品隔开\ndata['Goods'] = data['Goods'].apply(lambda x:','+x)\ndata = data.groupby('id').sum().reset_index()\n\n# 对合并的商品列转换数据格式\ndata['Goods'] = data['Goods'].apply(lambda x :[x[1:]])\ndata_list = list(data['Goods'])\n\n# 分割商品名为每个元素\ndata_translation = []\nfor i in data_list:\n p = i[0].split(',')\n data_translation.append(p)\nprint('数据转换结果的前5个元素:\\n', data_translation[0:5])\n\n# 使用关联分析进行关联\n# 导包\nimport pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori\n\nte = TransactionEncoder()\n# 进行one-hot编码\nte_ary = te.fit(data_translation).transform(data_translation)\nprint(type(te_ary))\ndf = pd.DataFrame(te_ary, columns=te.columns_)\n# 利用apriori找出频繁项集\nfreq = apriori(df, min_support=0.02, use_colnames=True)\n\n# 导入关联规则包\nfrom mlxtend.frequent_patterns import association_rules\n\n# 计算关联规则\nresult = association_rules(freq, metric=\"confidence\", min_threshold=0.35)\n# 排序\nresult.sort_values(by='confidence', ascending=False, axis=0)\nprint(result)\nresult.to_excel(\"./result.xlsx\")\n" }, { "alpha_fraction": 0.6012775897979736, "alphanum_fraction": 0.6111683249473572, "avg_line_length": 36.32307815551758, "blob_id": "c84406db883067c525cb1f4423ad5ff9b06e9be2", "content_id": "78a5a4130ff079983b2eff370187ca45e5c042ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5483, "license_type": "no_license", "max_line_length": 84, "num_lines": 130, "path": "/电商产品评论数据情感分析/chapter12/demo/code/03_情感分析.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# 代码12-6 匹配情感词\n\nimport pandas as pd\nimport numpy as np\nword = pd.read_csv(\"../tmp/word.csv\")\n\n# 读入正面、负面情感评价词\npos_comment = pd.read_csv(\"../data/正面评价词语(中文).txt\", header=None,sep=\"\\n\", \n encoding = 'utf-8', engine='python')\nneg_comment = pd.read_csv(\"../data/负面评价词语(中文).txt\", header=None,sep=\"\\n\", \n encoding = 'utf-8', engine='python')\npos_emotion = pd.read_csv(\"../data/正面情感词语(中文).txt\", header=None,sep=\"\\n\", \n encoding = 'utf-8', engine='python')\nneg_emotion = pd.read_csv(\"../data/负面情感词语(中文).txt\", header=None,sep=\"\\n\", \n encoding = 'utf-8', engine='python') \n\n# 合并情感词与评价词\npositive = set(pos_comment.iloc[:,0])|set(pos_emotion.iloc[:,0])\nnegative = set(neg_comment.iloc[:,0])|set(neg_emotion.iloc[:,0])\nintersection = positive&negative # 正负面情感词表中相同的词语\npositive = list(positive - intersection)\nnegative = list(negative - intersection)\npositive = pd.DataFrame({\"word\":positive,\n \"weight\":[1]*len(positive)})\nnegative = pd.DataFrame({\"word\":negative,\n \"weight\":[-1]*len(negative)}) \n\nposneg = positive.append(negative)\n\n# 将分词结果与正负面情感词表合并,定位情感词\ndata_posneg = posneg.merge(word, left_on = 'word', right_on = 'word', \n how = 'right')\ndata_posneg = data_posneg.sort_values(by = ['index_content','index_word'])\n\n\n\n# 代码12-7 修正情感倾向\n\n# 根据情感词前时候有否定词或双层否定词对情感值进行修正\n# 载入否定词表\nnotdict = pd.read_csv(\"../data/not.csv\")\n\n# 处理否定修饰词\ndata_posneg['amend_weight'] = data_posneg['weight'] # 构造新列,作为经过否定词修正后的情感值\ndata_posneg['id'] = np.arange(0, len(data_posneg))\nonly_inclination = data_posneg.dropna() # 只保留有情感值的词语\nonly_inclination.index = np.arange(0, len(only_inclination))\nindex = only_inclination['id']\n\nfor i in np.arange(0, len(only_inclination)):\n review = data_posneg[data_posneg['index_content'] == \n only_inclination['index_content'][i]] # 提取第i个情感词所在的评论\n review.index = np.arange(0, len(review))\n affective = only_inclination['index_word'][i] # 第i个情感值在该文档的位置\n if affective == 1:\n ne = sum([i in notdict['term'] for i in review['word'][affective - 1]])\n if ne == 1:\n data_posneg['amend_weight'][index[i]] = -\\\n data_posneg['weight'][index[i]] \n elif affective > 1:\n ne = sum([i in notdict['term'] for i in review['word'][[affective - 1, \n affective - 2]]])\n if ne == 1:\n data_posneg['amend_weight'][index[i]] = -\\\n data_posneg['weight'][index[i]]\n \n# 更新只保留情感值的数据\nonly_inclination = only_inclination.dropna()\n\n# 计算每条评论的情感值\nemotional_value = only_inclination.groupby(['index_content'],\n as_index=False)['amend_weight'].sum()\n\n# 去除情感值为0的评论\nemotional_value = emotional_value[emotional_value['amend_weight'] != 0]\n\n\n\n# 代码12-8 查看情感分析效果\n\n# 给情感值大于0的赋予评论类型(content_type)为pos,小于0的为neg\nemotional_value['a_type'] = ''\nemotional_value['a_type'][emotional_value['amend_weight'] > 0] = 'pos'\nemotional_value['a_type'][emotional_value['amend_weight'] < 0] = 'neg'\n\n# 查看情感分析结果\nresult = emotional_value.merge(word, \n left_on = 'index_content', \n right_on = 'index_content',\n how = 'left')\n\nresult = result[['index_content','content_type', 'a_type']].drop_duplicates() \nconfusion_matrix = pd.crosstab(result['content_type'], result['a_type'], \n margins=True) # 制作交叉表\n(confusion_matrix.iat[0,0] + confusion_matrix.iat[1,1])/confusion_matrix.iat[2,2]\n\n# 提取正负面评论信息\nind_pos = list(emotional_value[emotional_value['a_type'] == 'pos']['index_content'])\nind_neg = list(emotional_value[emotional_value['a_type'] == 'neg']['index_content'])\nposdata = word[[i in ind_pos for i in word['index_content']]]\nnegdata = word[[i in ind_neg for i in word['index_content']]]\n\n# 绘制词云\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\n# 正面情感词词云\nfreq_pos = posdata.groupby(by = ['word'])['word'].count()\nfreq_pos = freq_pos.sort_values(ascending = False)\nbackgroud_Image=plt.imread('../data/pl.jpg')\nwordcloud = WordCloud(font_path=\"G:/workspace/font/STZHONGS.ttf\",\n max_words=100,\n background_color='white',\n mask=backgroud_Image)\npos_wordcloud = wordcloud.fit_words(freq_pos)\nplt.imshow(pos_wordcloud)\nplt.axis('off') \nplt.show()\n# 负面情感词词云\nfreq_neg = negdata.groupby(by = ['word'])['word'].count()\nfreq_neg = freq_neg.sort_values(ascending = False)\nneg_wordcloud = wordcloud.fit_words(freq_neg)\nplt.imshow(neg_wordcloud)\nplt.axis('off') \nplt.show()\n\n# 将结果写出,每条评论作为一行\nposdata.to_csv(\"../tmp/posdata.csv\", index = False, encoding = 'utf-8')\nnegdata.to_csv(\"../tmp/negdata.csv\", index = False, encoding = 'utf-8')\n\n" }, { "alpha_fraction": 0.6640602350234985, "alphanum_fraction": 0.6869388818740845, "avg_line_length": 31.876190185546875, "blob_id": "5ba276b93db0fa8cf3188fe46d6915aa3c8c0550", "content_id": "3abf0b309627b074f2b225e273559fe9dc52c43a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4347, "license_type": "no_license", "max_line_length": 105, "num_lines": 105, "path": "/商品零售购物篮分析/test/01_data_explore.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\n\ninputfile = '../data/GoodsOrder.csv' # 输入的数据文件\ndata = pd.read_csv(inputfile,encoding = 'gbk') # 读取数据\ndata .info() # 查看数据属性\n\ndata = data['id']\ndescription = [data.count(),data.min(), data.max()] # 依次计算总数、最小值、最大值\ndescription = pd.DataFrame(description, index = ['Count','Min', 'Max']).T # 将结果存入数据框\nprint('描述性统计结果:\\n',np.round(description)) # 输出结果\n\n\n\n\n# 销量排行前10商品的销量及其占比\nimport pandas as pd\ninputfile = '../data/GoodsOrder.csv' # 输入的数据文件\ndata = pd.read_csv(inputfile,encoding = 'gbk') # 读取数据\ngroup = data.groupby(['Goods']).count().reset_index() # 对商品进行分类汇总\nsorted=group.sort_values('id',ascending=False)\nprint('销量排行前10商品的销量:\\n', sorted[:10]) # 排序并查看前10位热销商品\n\n# 画条形图展示出销量排行前10商品的销量\nimport matplotlib.pyplot as plt\nx=sorted[:10]['Goods']\ny=sorted[:10]['id']\nplt.figure(figsize = (8, 4)) # 设置画布大小 \nplt.barh(x,y)\nplt.rcParams['font.sans-serif'] = 'SimHei'\nplt.xlabel('销量') # 设置x轴标题\nplt.ylabel('商品类别') # 设置y轴标题\nplt.title('商品的销量TOP10') # 设置标题\nplt.savefig('../tmp/top10.png') # 把图片以.png格式保存\nplt.show() # 展示图片\n\n# 销量排行前10商品的销量占比\ndata_nums = data.shape[0]\nfor idnex, row in sorted[:10].iterrows():\n print(row['Goods'],row['id'],row['id']/data_nums)\n\n\n\t\n\t\nimport pandas as pd\ninputfile1 = '../data/GoodsOrder.csv'\ninputfile2 = '../data/GoodsTypes.csv'\ndata = pd.read_csv(inputfile1,encoding = 'gbk')\ntypes = pd.read_csv(inputfile2,encoding = 'gbk') # 读入数据\n\ngroup = data.groupby(['Goods']).count().reset_index()\nsort = group.sort_values('id',ascending = False).reset_index()\ndata_nums = data.shape[0] # 总量\ndel sort['index']\n\nsort_links = pd.merge(sort,types) # 合并两个datafreame 根据type\n# 根据类别求和,每个商品类别的总量,并排序\nsort_link = sort_links.groupby(['Types']).sum().reset_index()\nsort_link = sort_link.sort_values('id',ascending = False).reset_index()\ndel sort_link['index'] # 删除“index”列\n\n# 求百分比,然后更换列名,最后输出到文件\nsort_link['count'] = sort_link.apply(lambda line: line['id']/data_nums,axis = 1)\nsort_link.rename(columns = {'count':'percent'},inplace = True)\nprint('各类别商品的销量及其占比:\\n',sort_link)\noutfile1 = '../tmp/percent.xlsx'\nsort_link.to_excel(outfile1,index = False,header = True) # 保存结果\n\n# 画饼图展示每类商品销量占比\nimport matplotlib.pyplot as plt\ndata = sort_link['percent']\nlabels = sort_link['Types']\nplt.figure(figsize = (8, 6)) # 设置画布大小 \nplt.pie(data,labels=labels,autopct = '%1.2f%%')\nplt.rcParams['font.sans-serif'] = 'SimHei'\nplt.title('每类商品销量占比') # 设置标题\nplt.savefig('../tmp/persent.png') # 把图片以.png格式保存\nplt.show()\n\n\n\n\n# 先筛选“非酒精饮料”类型的商品,然后求百分比,然后输出结果到文件。\nselected = sort_links.loc[sort_links['Types'] == '非酒精饮料'] # 挑选商品类别为“非酒精饮料”并排序\nchild_nums = selected['id'].sum() # 对所有的“非酒精饮料”求和\nselected['child_percent'] = selected.apply(lambda line: line['id']/child_nums,axis = 1) # 求百分比\nselected.rename(columns = {'id':'count'},inplace = True)\nprint('非酒精饮料内部商品的销量及其占比:\\n',selected)\noutfile2 = '../tmp/child_percent.xlsx'\nsort_link.to_excel(outfile2,index = False,header = True) # 输出结果\n\n# 画饼图展示非酒精饮品内部各商品的销量占比\nimport matplotlib.pyplot as plt\ndata = selected['child_percent']\nlabels = selected['Goods']\nplt.figure(figsize = (8,6)) # 设置画布大小 \nexplode = (0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.08,0.3,0.1,0.3) # 设置每一块分割出的间隙大小\nplt.pie(data,explode = explode,labels = labels,autopct = '%1.2f%%',pctdistance = 1.1,labeldistance = 1.2)\nplt.rcParams['font.sans-serif'] = 'SimHei'\nplt.title(\"非酒精饮料内部各商品的销量占比\") # 设置标题\nplt.axis('equal')\nplt.savefig('../tmp/child_persent.png') # 保存图形\nplt.show() # 展示图形\n\n" }, { "alpha_fraction": 0.606107771396637, "alphanum_fraction": 0.6584321856498718, "avg_line_length": 24.839195251464844, "blob_id": "37f95e37fe652de37e32411e1890199d87684eba", "content_id": "fb1182c00a0117687c660e0aaaec22444a5900c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6897, "license_type": "no_license", "max_line_length": 118, "num_lines": 199, "path": "/京东用户购买意向预测/JD_异常值判断.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n#定义文件名\nACTION_201602_FILE = \"data/JData_Action_201602.csv\"\nACTION_201603_FILE = \"data/JData_Action_201603.csv\"\nACTION_201604_FILE = \"data/JData_Action_201604.csv\"\nCOMMENT_FILE = \"data/JData_Comment.csv\"\nPRODUCT_FILE = \"data/JData_Product.csv\"\nUSER_FILE = \"data/JData_User.csv\"\nUSER_TABLE_FILE = \"data/User_table.csv\"\nITEM_TABLE_FILE = \"data/Item_table.csv\"\n\n\"\"\"\n数据背景信息\n\n根据官方给出的数据介绍里,可以知道数据可能存在哪些异常信息\n •用户文件◾用户的age存在未知的情况,标记为-1\n ◾用户的sex存在保密情况,标记为2\n ◾后续分析发现,用户注册日期存在系统异常导致在预测日之后的情况,不过目前针对该特征没有想法,所以不作处理\n •商品文件\n ◾属性a1,a2,a3均存在未知情形,标记为-1\n •行为文件\n ◾model_id为点击模块编号,针对用户的行为类型为6时,可能存在空值\n\"\"\"\n\n\"\"\"\n空值判断\n\"\"\"\ndef check_empty(file_path, file_name):\n df_file = pd.read_csv(file_path)\n print ('Is there any missing value in {0}? {1}'.format(file_name, df_file.isnull().any().any()))\n\ncheck_empty(USER_FILE, 'User')\ncheck_empty(ACTION_201602_FILE, 'Action 2')\ncheck_empty(ACTION_201603_FILE, 'Action 3')\ncheck_empty(ACTION_201604_FILE, 'Action 4')\ncheck_empty(COMMENT_FILE, 'Comment')\ncheck_empty(PRODUCT_FILE, 'Product')\n\n\"\"\"\n由上述简单的分析可知,用户表及行为表中均存在空值记录,而评论表和商品表则不存在,\n但是结合之前的数据背景分析商品表中存在属性未知的情况,后续也需要针对分析,进一\n步的我们看看用户表和行为表中的空值情况\n\"\"\"\ndef empty_detail(f_path, f_name):\n df_file = pd.read_csv(f_path)\n print ('empty info in detail of {0}:'.format(f_name))\n print (pd.isnull(df_file).any())\n\nempty_detail(USER_FILE, 'User')\nempty_detail(ACTION_201602_FILE, 'Action 2')\nempty_detail(ACTION_201603_FILE, 'Action 3')\nempty_detail(ACTION_201604_FILE, 'Action 4')\n\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n上面简单的输出了下存在空值的文件中具体哪些列存在空值(True),结果如下\n* User\n * age\n * sex\n * user_reg_tm\n* Action\n * model_id\n \n接下来具体看看各文件中的空值情况:\n\"\"\"\ndef empty_records(f_path, f_name, col_name):\n df_file = pd.read_csv(f_path)\n missing = df_file[col_name].isnull().sum().sum()\n print ('No. of missing {0} in {1} is {2}'.format(col_name, f_name, missing))\n print ('percent: ', missing * 1.0 / df_file.shape[0])\n\nempty_records(USER_FILE, 'User', 'age')\nempty_records(USER_FILE, 'User', 'sex')\nempty_records(USER_FILE, 'User', 'user_reg_tm')\nempty_records(ACTION_201602_FILE, 'Action 2', 'model_id')\nempty_records(ACTION_201603_FILE, 'Action 3', 'model_id')\nempty_records(ACTION_201604_FILE, 'Action 4', 'model_id')\n\n\"\"\"\n对比下数据集的记录数:\n\n 文件 文件说明 记录数\n1. JData_User.csv 用户数据集 105,321个用户 \n2. JData_Comment.csv 商品评论 558,552条记录 \n3. JData_Product.csv 预测商品集合 24,187条记录 \n4. JData_Action_201602.csv 2月份行为交互记录 11,485,424条记录 \n5. JData_Action_201603.csv 3月份行为交互记录 25,916,378条记录 \n6. JData_Action_201604.csv 4月份行为交互记录 13,199,934条记录 \n\n两相对比结合前面输出的情况,针对不同数据进行不同处理\n•用户文件 \n ◾age,sex:先填充为对应的未知状态(-1|2),后续作为未知状态的值进一步分析和处理\n ◾user_reg_tm:暂时不做处理\n•行为文件\n ◾model_id涉及数目接近一半,而且当前针对该特征没有很好的处理方法,待定\n\"\"\"\nuser = pd.read_csv(USER_FILE)\nuser['age'].fillna('-1', inplace=True)\nuser['sex'].fillna(2, inplace=True)\n\nprint (pd.isnull(user).any())\n\nnan_reg_tm = user[user['user_reg_tm'].isnull()]\nprint (nan_reg_tm)\n\nprint (len(user['age'].unique()))\nprint (len(user['sex'].unique()))\nprint (len(user['user_lv_cd'].unique()))\n\nprod = pd.read_csv(PRODUCT_FILE)\n\nprint (len(prod['a1'].unique()))\nprint (len(prod['a2'].unique()))\nprint (len(prod['a3'].unique()))\n# print (len(prod['a2'].unique()))\nprint (len(prod['brand'].unique()))\n\n\"\"\"\n未知记录\n\n接下来看看各个文件中的未知记录占的比重\n\"\"\"\nprint ('No. of unknown age user: {0} and the percent: {1} '.format(user[user['age']=='-1'].shape[0],\n user[user['age']=='-1'].shape[0]*1.0/user.shape[0]))\nprint ('No. of unknown sex user: {0} and the percent: {1} '.format(user[user['sex']==2].shape[0],\n user[user['sex']==2].shape[0]*1.0/user.shape[0]))\n\n\ndef unknown_records(f_path, f_name, col_name):\n df_file = pd.read_csv(f_path)\n missing = df_file[df_file[col_name] == -1].shape[0]\n print\n ('No. of unknown {0} in {1} is {2}'.format(col_name, f_name, missing))\n print\n ('percent: ', missing * 1.0 / df_file.shape[0])\n\n\nunknown_records(PRODUCT_FILE, 'Product', 'a1')\nunknown_records(PRODUCT_FILE, 'Product', 'a2')\nunknown_records(PRODUCT_FILE, 'Product', 'a3')\n\"\"\"\n小结一下\n •空值部分对3条用户的sex,age填充为未知值,注册时间不作处理,此外行为数据部分model_id待定: 43.2%,40.7%,39.0%\n •未知值部分,用户age存在部分未知值: 13.7%,sex存在大量保密情况(超过一半) 52.0%\n •商品中各个属性存在部分未知的情况,a1<a3<a2,分别为: 7.0%,16.7%,15.8%\n\"\"\"\n\n\"\"\"\n异常值检测\n对于任何的分析,在数据预处理的过程中检测数据中的异常值都是非常重要的一步。\n异常值的出现会使得把这些值考虑进去后结果出现倾斜。这里有很多关于怎样定义\n什么是数据集中的异常值的经验法则。这里我们将使用Tukey的定义异常值的方法:\n一个异常阶(outlier step)被定义成1.5倍的四分位距(interquartile range,IQR)。\n一个数据点如果某个特征包含在该特征的IQR之外的特征,那么该数据点被认定为异常点。\n\"\"\"\n# 对于每一个特征,找到值异常高或者是异常低的数据点\n# for feature in log_data.keys():\n# # TODO:计算给定特征的Q1(数据的25th分位点)\n# Q1 = np.percentile(log_data[feature], 25)\n#\n# # TODO:计算给定特征的Q3(数据的75th分位点)\n# Q3 = np.percentile(log_data[feature], 75)\n#\n# # TODO:使用四分位范围计算异常阶(1.5倍的四分位距)\n# step = 1.5 * (Q3 - Q1)\n#\n# # 显示异常点\n# print\n# (\"Data points considered outliers for the feature '{}':\".format(feature)\n# display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]))" }, { "alpha_fraction": 0.5939226746559143, "alphanum_fraction": 0.6145596504211426, "avg_line_length": 22.669231414794922, "blob_id": "dab6497ed891fe091eafe8ec20d8aa1681fe50d9", "content_id": "0c2fb27ba1a8ad34d5ab96b59cc5cde88832c5a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8872, "license_type": "no_license", "max_line_length": 97, "num_lines": 260, "path": "/ss_05_scikit_learn数据预处理.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\ndef dictvec():\n \"\"\"\n 字典数据抽取:对字典数据进行特征值化\n :return:None\n \"\"\"\n #实例化DictVectorizer\n # sklearn.feature_extraction特征抽取API\n from sklearn.feature_extraction import DictVectorizer\n dict = DictVectorizer(sparse=False)\n #调用fit_transform方法输入数据并转换,返回矩阵形式数据\n data = dict.fit_transform([{'city': '北京','temperature': 100},{'city': '上海','temperature':60},\n {'city': '深圳','temperature': 30}])\n #获取特征值\n print(dict.get_feature_names())\n # 获取转换之前数据\n print(dict.inverse_transform(data))\n #转换后的数据\n print(data)\n return None\n\ndef countvec():\n \"\"\"\n 英文文本特征抽取:对文本数据进行特征值化\n :return:\n \"\"\"\n #导入包\n from sklearn.feature_extraction.text import CountVectorizer\n #实例化CountVectorizer()\n vector = CountVectorizer()\n #调用fit_transform输入并转换数据\n res = vector.fit_transform([\"life is short,i like python\",\n \"life is too long,i dislike python\"])\n # 获取特征值\n print(vector.get_feature_names())\n # 转换后的数据\n # print(res.toarray())\n return None\n\ndef countvec_chinese():\n \"\"\"\n 中文文本特征抽取:\n 存在问题:对中文分词有误\n 解决办法:使用jieba分词\n :return:\n \"\"\"\n from sklearn.feature_extraction.text import CountVectorizer\n #实例化CountVectorizer()\n vector = CountVectorizer()\n #调用fit_transfrom输入并转换数据\n # data = vector.fit_transform(\n # [\"人生苦短,我用python\",\"人生漫长,不用python\"])\n data = vector.fit_transform(\n [\"人生苦短,我喜欢python\",\"人生漫长,不用python\"])\n #获取数据特征值\n print(vector.get_feature_names())\n #转换后的数据\n # print(data.toarray())\n return None\n\ndef jieba_cutword():\n \"\"\"\n 利用jieba.cut进行分词,返回词语生成器。\n 将分词结果变成字符串当作fit_transform的输入值\n :return:\n \"\"\"\n import jieba\n con1 = jieba.cut(\"今天很残酷,明天更残酷,后天很美好,\"\n \"但绝对大部分是死在明天晚上,所以每个人不要放弃今天。\")\n\n con2 = jieba.cut(\"我们看到的从很远星系来的光是在几百万年之前发出的,\"\n \"这样当我们看到宇宙时,我们是在看它的过去。\")\n\n con3 = jieba.cut(\"如果只用一种方式了解某样事物,你就不会真正了解它。\"\n \"了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。\")\n\n #转换成列表\n content1 = list(con1)\n content2 = list(con2)\n content3 = list(con3)\n print(content1)\n #列表转字符串\n c1 = ' '.join(content1)\n c2 = ' '.join(content2)\n c3 = ' '.join(content3)\n return c1,c2,c3\n\ndef countvec_chinese_jieba():\n \"\"\"\n 使用jieba分词对中文进行分词\n :return:\n \"\"\"\n from sklearn.feature_extraction.text import CountVectorizer\n c1,c2,c3 = jieba_cutword()\n # print(c1,c2,c3)\n #实例化CountVectorizer()\n cv = CountVectorizer()\n # 调用fit_transfrom输入并转换数据\n a = [c1,c2,c3]\n print(a)\n data = cv.fit_transform([c1,c2,c3])\n # 获取数据特征值\n # print(cv.get_feature_names())\n # 转换后的数据\n # print(data.toarray())\n return None\n\ndef tfidf_countvec_chinese_jieba():\n \"\"\"\n TF-IDF-文本词语占比分析:\n TF-IDF的主要思想是:如果某个词或短语在一篇文章中出现的概率高,并且在其他文章中很少出现,\n 则认为此词或者短语具有很好的类别区分能力,适合用来分类。\n :return:\n \"\"\"\n #导包\n from sklearn.feature_extraction.text import TfidfVectorizer\n #字符串\n c1,c2,c3 = jieba_cutword()\n #实例化TF-IDF\n tf = TfidfVectorizer()\n #调用fit_transform()输入并转换数据\n data = tf.fit_transform([c1,c2,c3])\n #获取数据特征值\n print(tf.get_feature_names())\n #转换后的数据\n print(data.toarray())\n return None\n\ndef min_max_scaler():\n \"\"\"\n 归一化处理:\n 通过对原始数据进行变换把数据映射到(默认为[0,1])之间\n 缺点:最大值与最小值非常容易受异常点影响,这种方法鲁棒性较差,只适合传统精确小数据场景。\n :return:\n \"\"\"\n from sklearn.preprocessing import MinMaxScaler\n #实例化MinMaxScaler()\n mm = MinMaxScaler()\n # 调用fit_transform()输入并转换数据\n data = mm.fit_transform([[90,2,10,40],[60,4,15,45],[75,3,13,46]])\n # 转换后的数据\n print(data)\n return None\n\ndef standard_scaler():\n \"\"\"\n 标准化方法:通过对原始数据进行变换把数据变换到均值为0,方差为1范围内\n 如果出现异常点,由于具有一定数据量,少量的异常点对于平均值的影响并不大,从而方差改变较小。\n :return:\n \"\"\"\n from sklearn.preprocessing import StandardScaler\n #实例化StandardScaler()\n standard = StandardScaler()\n #调用fit_transform()输入并转换数据\n data = standard.fit_transform([[1,-1,3],[2,4,2],[4,6,1]])\n #转换后的数据\n print(data)\n return None\n\ndef imputer():\n \"\"\"\n 缺失值处理\n :return:\n \"\"\"\n from sklearn.impute import SimpleImputer\n import numpy as np\n #实例化SimpleImputer(),指定缺失值为missing_values=np.NaN,\n # 填补策略为平均值strategy=\"mean\"\n im = SimpleImputer(missing_values=np.NaN,strategy=\"mean\")\n # 调用fit_transform()输入并转换数据\n data = im.fit_transform([[1,2],[np.NaN,3],[7,6]])\n # 转换后的数据\n print(data)\n return None\n\ndef variance_threshold():\n \"\"\"\n 特征选择-过滤式:删除低方差特征\n :return:\n \"\"\"\n from sklearn.feature_selection import VarianceThreshold\n #实例化VarianceThreshold()\n var = VarianceThreshold()\n #调用fit_transform()输入并转换数据\n data = var.fit_transform([[0,2,0,3],[0,1,4,3],[0,1,1,3]])\n #转换后的数据\n print(data)\n return None\n\ndef pca():\n \"\"\"\n PCA主成分分析进行特征降维\n :return:\n \"\"\"\n #导包\n from sklearn.decomposition import PCA\n #实例化PCA,\n # n_components小数是百分比:n_components=0.9保留90%数据,一般取值90%-95%\n #n_components整数是保留的特征数量,一般不用\n pca = PCA(n_components=0.9)\n #输入并转换数据\n data = pca.fit_transform([[2,8,4,5],[6,3,0,8],[5,4,9,1]])\n #转换后的数据\n print(data)\n return None\n\n\nif __name__==\"__main__\":\n \"\"\"\n 特征工程是将原始数据转换为更好地代表预测模型的潜在问题的特征的过程,从而提高了对未知数据的模型准确性。\n 意义:直接影响模型的预测结果\n \"\"\"\n \"\"\"\n 数据预处理步骤1:特征抽取\n 特点:特征抽取针对非连续型数据,特征抽取对文本等进行特征值化。\n 特征值化是为了计算机更好的去理解数据\n 分类:字典特征抽取和文本特征抽取\n \"\"\"\n dictvec()\n # countvec()\n # countvec_chinese()\n # jieba_cutword()\n # countvec_chinese_jieba()\n\n \"\"\" \n 数据预处理步骤2:特征处理\n 通过特定的统计方法(数学方法)将数据转换成算法要求的数据\n 方法:\n 数值型数据:标准缩放:\t1、归一化 2、标准化\n 类别型数据:one-hot编码\n 时间类型:时间的切分\n \"\"\"\n # min_max_scaler()\n # standard_scaler()\n\n \"\"\"\n 数据预处理步骤3:缺失值处理\n 方法:\n 1.删除:如果每列或者行数据缺失值达到一定的比例,建议放弃整行或者整列\n 2.插补:可以通过缺失值每行或者每列的平均值、中位数来填充\n API:Imputer包\n \"\"\"\n # imputer()\n\n \"\"\"\n 数据预处理步骤4:特征选择\n 概念:特征选择就是单纯地从提取到的所有特征中选择部分特征作为训练集特征,\n 特征在选择前和选择后可以改变值、也不改变值,但是选择后的特征维数肯定比选择前小,\n 毕竟我们只选择了其中的一部分特征。\n 方法:\n 1.过滤:variance threshold 删除所有低方差特征,默认值是保留所有非零方差特征,\n 即删除所有样本中具有相同值的特征。\n \n \"\"\"\n # variance_threshold()\n \"\"\"\n 数据预处理步骤5:降维(PCA)\n PCA,是数据维数压缩,尽可能降低原数据的维数(复杂度),损失少量信息。\n 可以削减回归分析或者聚类分析中特征的数量\n \"\"\"\n # pca()" }, { "alpha_fraction": 0.5619972944259644, "alphanum_fraction": 0.5834450125694275, "avg_line_length": 26.620370864868164, "blob_id": "83ff242fcf6107fc5c70bba1fdd7192beea2c5f7", "content_id": "704d4dc00bb07d960a17540388928af3f76845af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3366, "license_type": "no_license", "max_line_length": 102, "num_lines": 108, "path": "/电商产品评论数据情感分析/chapter12/test/03_LDA.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport re\nimport itertools\nimport matplotlib.pyplot as plt\n\n# 载入情感分析后的数据\nposdata = pd.read_csv(\"../data/posdata.csv\", encoding = 'utf-8')\nnegdata = pd.read_csv(\"../data/negdata.csv\", encoding = 'utf-8')\n\nfrom gensim import corpora, models\n# 建立词典\npos_dict = corpora.Dictionary([[i] for i in posdata['word']]) # 正面\nneg_dict = corpora.Dictionary([[i] for i in negdata['word']]) # 负面\n\n# 建立语料库\npos_corpus = [pos_dict.doc2bow(j) for j in [[i] for i in posdata['word']]] # 正面\nneg_corpus = [neg_dict.doc2bow(j) for j in [[i] for i in negdata['word']]] # 负面\n\n\n\n\n\n# 构造主题数寻优函数\ndef cos(vector1, vector2): # 余弦相似度函数\n dot_product = 0.0; \n normA = 0.0; \n normB = 0.0; \n for a,b in zip(vector1, vector2): \n dot_product += a*b \n normA += a**2 \n normB += b**2 \n if normA == 0.0 or normB==0.0: \n return(None) \n else: \n return(dot_product / ((normA*normB)**0.5)) \n\n# 主题数寻优\ndef lda_k(x_corpus, x_dict): \n \n # 初始化平均余弦相似度\n mean_similarity = []\n mean_similarity.append(1)\n \n # 循环生成主题并计算主题间相似度\n for i in np.arange(2,11):\n lda = models.LdaModel(x_corpus, num_topics = i, id2word = x_dict) # LDA模型训练\n for j in np.arange(i):\n term = lda.show_topics(num_words = 50)\n \n # 提取各主题词\n top_word = []\n for k in np.arange(i):\n top_word.append([''.join(re.findall('\"(.*)\"',i)) for i in term[k][1].split('+')]) # 列出所有词\n \n # 构造词频向量\n word = sum(top_word,[]) # 列出所有的词 \n unique_word = set(word) # 去除重复的词\n \n # 构造主题词列表,行表示主题号,列表示各主题词\n mat = []\n for j in np.arange(i):\n top_w = top_word[j]\n mat.append(tuple([top_w.count(k) for k in unique_word])) \n \n p = list(itertools.permutations(list(np.arange(i)),2))\n l = len(p)\n top_similarity = [0]\n for w in np.arange(l):\n vector1 = mat[p[w][0]]\n vector2 = mat[p[w][1]]\n top_similarity.append(cos(vector1, vector2))\n \n # 计算平均余弦相似度\n mean_similarity.append(sum(top_similarity)/l)\n return(mean_similarity)\n \n# 计算主题平均余弦相似度\npos_k = lda_k(pos_corpus, pos_dict)\nneg_k = lda_k(neg_corpus, neg_dict) \n\n# 绘制主题平均余弦相似度图形\nfrom matplotlib.font_manager import FontProperties \nfont = FontProperties(size=14)\n#解决中文显示问题\nplt.rcParams['font.sans-serif']=['SimHei']\nplt.rcParams['axes.unicode_minus'] = False \nfig = plt.figure(figsize=(10,8))\nax1 = fig.add_subplot(211)\nax1.plot(pos_k)\nax1.set_xlabel('正面评论LDA主题数寻优', fontproperties=font)\n\nax2 = fig.add_subplot(212)\nax2.plot(neg_k)\nax2.set_xlabel('负面评论LDA主题数寻优', fontproperties=font)\n\n\n\n\n\n# LDA主题分析\npos_lda = models.LdaModel(pos_corpus, num_topics = 3, id2word = pos_dict) \nneg_lda = models.LdaModel(neg_corpus, num_topics = 3, id2word = neg_dict) \npos_lda.print_topics(num_words = 10)\n\nneg_lda.print_topics(num_words = 10)\n\n" }, { "alpha_fraction": 0.5454767942428589, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 25.783607482910156, "blob_id": "8aa9dc783cc12d8269499b23cdff5486af477395", "content_id": "8f912d884cf5d04c8613d8c62189fd760778ebc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10115, "license_type": "no_license", "max_line_length": 111, "num_lines": 305, "path": "/ss_10_人脸识别.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import cv2\n\n\ndef show_image():\n \"\"\"\n OpenCV读取图像\n :return:\n \"\"\"\n # 导包\n import cv2\n # 读取照片\n img = cv2.imread(\"../data/lena.jpg\") # 路径中不能有中文\n # 显示图片\n cv2.imshow(\"read_img\", img)\n # 输入毫秒值,传0就是无限等待\n cv2.waitKey(3000)\n # 释放内存,由于OpenCV底层是C++写的\n cv2.destroyAllWindows()\n return None\n\n\ndef gray_level():\n \"\"\"\n OpenCV进行灰度转换\n :return:\n \"\"\"\n import cv2\n img = cv2.imread(\"../data/lena.jpg\")\n # cv2.imshow(\"BGR_IMG\", img)\n # 将图片转化为灰度\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # 展示图片\n cv2.imshow(\"gray_img\", gray_img)\n # 设置展示时间\n cv2.waitKey(3000)\n # 保存图片\n cv2.imwrite(\"./gray_lena.jpg\", gray_img)\n # 释放内存\n cv2.destroyAllWindows()\n return None\n\n\ndef size_image():\n import cv2\n # 读取图例\n img = cv2.imread(\"../data/lena.jpg\")\n # 展示图像\n cv2.imshow(\"img\", img)\n print(\"原来图片的形状\", img.shape)\n # 设置图片的形状\n resize_img = cv2.resize(img, dsize=(600, 600))\n print(\"修改后的形状\", resize_img.shape)\n cv2.imshow(\"resize_img\", resize_img)\n # 设置等待时间\n cv2.waitKey(0)\n # 释放内存\n cv2.destroyAllWindows()\n return None\n\n\ndef draw_image():\n \"\"\"\n OpenCV画图,对图片进行编辑\n :return:\n \"\"\"\n # 导包\n import cv2\n img = cv2.imread(\"../data/lena.jpg\")\n # 左上角的坐标是(x,y),矩形的宽度和高度是(w,h)\n x, y, w, h = 100, 100, 100, 100\n # 绘制矩形\n cv2.rectangle(img, (x, y, x + w, y + h), color=(0, 0, 255), thickness=2)\n # 绘制圆\n x, y, r = 200, 200, 100\n cv2.circle(img, center=(x, y), radius=r, color=(0, 0, 255), thickness=2)\n # 显示图片\n cv2.imshow(\"rectangle_img\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return None\n\n\ndef out_face_detect_static():\n def face_detect_static():\n \"\"\"\n 静态人脸检测\n\n 调用opencv训练好的分类器和自带的检测函数检测人脸人眼等的步骤简单直接:\n 1.加载分类器,当然分类器事先要放在工程目录中去。分类器本来的位置是在*\\opencv\\sources\\data\\haarcascades(harr分类器,也有其他的可以用,也可以自己训练)\n 2.调用detectMultiScale()函数检测,调整函数的参数可以使检测结果更加精确。\n 3.把检测到的人脸等用矩形(或者圆形等其他图形)画出来。\n :return:\n \"\"\"\n # 导包\n import cv2\n # 图片转化为灰度图片\n gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # 加载特征数据 CascadeClassifier级联分类器\n face_detector = cv2.CascadeClassifier(\n \"C:/ProgramData/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\n faces = face_detector.detectMultiScale(gray_image)\n for x, y, w, h in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2)\n cv2.imshow(\"result\", img)\n\n # 加载图片\n img = cv2.imread('../data/lena.jpg')\n # 调用人脸检测方法\n face_detect_static()\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return None\n\n\ndef out_many_face_detect_static():\n import cv2\n def many_face_detect_static():\n # 图片进行灰度处理\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # 加载数据特征\n face_detector = cv2.CascadeClassifier(\n \"C:/ProgramData/Anaconda3/Lib/site-packages/cv2\"\n \"/data/haarcascade_frontalface_default.xml\")\n faces = face_detector.detectMultiScale(gray)\n for x, y, w, h in faces:\n print(x, y, w, h)\n cv2.rectangle(img, (x, y), (x + w, y + h),\n color=(0, 0, 255), thickness=2)\n cv2.circle(img, (x + w // 2, y + w // 2),\n radius=w // 2, color=(0, 255, 0), thickness=2)\n cv2.imshow(\"result\", img)\n\n # 加载图片\n img = cv2.imread(\"../data/face3.jpg\")\n # 调用人脸检测方法\n many_face_detect_static()\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return None\n\n\ndef video_face_detect():\n \"\"\"\n 视频人脸检测\n :return:\n \"\"\"\n\n def face_detect(frame):\n # 将图片进行灰度化\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # 加载特征数据\n face_detector = cv2.CascadeClassifier(\n \"C:/ProgramData/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\n faces = face_detector.detectMultiScale(gray)\n for x, y, w, h in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)\n cv2.circle(frame, center=(x + w // 2, y + h // 2), radius=(w // 2), color=(0, 255, 0), thickness=2)\n cv2.imshow(\"result\", frame)\n\n video_face = cv2.VideoCapture(\"G:/video.mp4\")\n while True:\n # read()方法返回视频中检测的对象,,视频在播放flag为True,frame为当前帧上的图片\n flag, frame = video_face.read()\n print(\"flag:\", flag, \"frame.shape:\", frame.shape)\n if not flag:\n break\n face_detect(frame)\n cv2.waitKey(20)\n cv2.destroyAllWindows()\n video_face.release()\n\n\ndef out_getImageAndLabels():\n import numpy as np\n def getImageAndLabels(path):\n \"\"\"\n 获取图片特征值和目标值\n :param path:\n :return:\n \"\"\"\n # 导包\n import os\n import cv2\n import sys\n from PIL import Image\n \"\"\"\n PIL(Python Image Library)是python的第三方图像处理库,\n 但是由于其强大的功能与众多的使用人数,几乎已经被认为\n 是python官方图像处理库了。Image模块是在Python PIL图像\n 处理中常见的模块,对图像进行基础操作的功能基本都包含于此模块内。\n 如open、save、conver、show…等功能\n \"\"\"\n facesSamples = []\n ids = []\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n face_detector = cv2.CascadeClassifier(\n \"C:/ProgramData/Anaconda3/Lib/site-packages/cv2/data\"\n \"/haarcascade_frontalface_default.xml\")\n # 遍历列表中的图片\n for imagePath in imagePaths:\n # 打开图片。convert()函数,用于不同模式图像之间的转换。\n # PIL中有九种不同模式,分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。主要尝试1和L。\n # 模式”1”为二值图像,非黑即白。但是它每个像素用8个bit表示,0表示黑,255表示白。\n # 模式“L” 为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。\n PIL_img = Image.open(imagePath).convert(\"L\")\n # 将图像转换我数组\n img_numpy = np.array(PIL_img, \"uint8\")\n faces = face_detector.detectMultiScale(img_numpy)\n # 获取每张图片的id\n id = int(os.path.split(imagePath)[1].split(\".\")[0])\n for x, y, w, h in faces:\n # 添加人脸区域图片\n facesSamples.append(img_numpy[y:y + h, x:x + w])\n ids.append(id)\n return facesSamples, ids\n\n # 图片路径\n path = \"../data/jm\"\n # 获取图像数组和id数组标签\n faces, ids = getImageAndLabels(path)\n # 训练对象\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n recognizer.train(faces, np.array(ids))\n # 保存训练文件\n recognizer.write(\"./trainer.yml\")\n\n\ndef match_face():\n \"\"\"\n 人脸匹配\n :return:\n \"\"\"\n # 导包\n import cv2\n import numpy as np\n import os\n # 加载训练数据集文件\n recogizer = cv2.face.LBPHFaceRecognizer_create()\n recogizer.read(\"./trainer.yml\")\n # 准备识别的图片\n img = cv2.imread(\"../data/jm/1.pgm\")\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n face_detector = cv2.CascadeClassifier(\n \"C:/ProgramData/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\n faces = face_detector.detectMultiScale(gray)\n for x, y, w, h in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # 人脸识别\n id, confidence = recogizer.predict(gray[y:y + h, x:x + w])\n print(\"标签id:\", id, \"置信度评分:\", confidence)\n cv2.imshow(\"result\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n \"\"\"\n 人脸识别:基于OpenCV的人脸识别\n OpenCV全程Open Source Computer Vision Library,是一个跨平台的计算机视觉库。用C++语言编写\n 安装:pip install opencv-python \n \"\"\"\n \"\"\"\n OpenCV用法1:显示图像\n API:\n imshow() 显示图像\n waitkey() 设置图片显示的时长,单位毫秒,0无限等待,为一直显示\n \"\"\"\n # show_image()\n\n \"\"\"\n OpenCV用法2:图片灰度转换。减少计算量\n \"\"\"\n # gray_level()\n\n \"\"\"\n OpenCV用法3:修改图片尺寸\n \"\"\"\n # size_image()\n\n \"\"\"\n OpenCV用法4:画图\n \n \"\"\"\n # draw_image()\n\n \"\"\"\n OpenCV用法5:静态人脸检测\n 摄影作品可能包含很多令人愉悦的细节。 但是, 由于灯光、 视角、 视距、 摄像头抖动以及数字噪声的变化, 图像细节变得不稳定。\n Haar级联数据\n \"\"\"\n # out_face_detect_static()\n # out_many_face_detect_static()\n\n \"\"\"\n OpenCV用法6:视频人脸检测\n \"\"\"\n # video_face_detect()\n\n \"\"\"\n OpenCV用法7:LBPH人脸识别,预测人脸归属\n LBPH(Local Binary Pattern Histogram) 将检测到的人脸分为小单元,\n 并将其与模型中的对应单元进行比较, 对每个区域的匹配值产生一个直方图。\n \"\"\"\n # out_getImageAndLabels()\n match_face()\n" }, { "alpha_fraction": 0.6398604512214661, "alphanum_fraction": 0.6543049812316895, "avg_line_length": 30.276649475097656, "blob_id": "70a7bce0d00ded2cec700f749641366e68eabf6a", "content_id": "4fcf47c97f11b7fc35ba7c5fd257efe276f43157", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15895, "license_type": "no_license", "max_line_length": 129, "num_lines": 394, "path": "/ss_06_分类算法.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "def knn_breast_cancer():\n \"\"\"\n K-近邻算法\n 威斯康星州乳腺癌数据集\n 含有30个特征、569条记录、目标值为0或1\n :return:\n \"\"\"\n # 导包\n from sklearn.datasets import load_breast_cancer\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.neighbors import KNeighborsClassifier\n from sklearn.metrics import classification_report\n from sklearn.model_selection import GridSearchCV\n # 导入数据\n data_cancer = load_breast_cancer()\n # 将数据集划分为训练集和测试集\n x_train, x_test, y_train, y_test = train_test_split(\n data_cancer.data, data_cancer.target, test_size=0.25)\n # 数据标准化处理\n stdScaler = StandardScaler().fit(x_train)\n x_trainStd = stdScaler.transform(x_train)\n x_testStd = stdScaler.transform(x_test)\n # 使用KNeighborsClassifier函数构建knn模型\n knn_model = KNeighborsClassifier()\n knn_model.fit(x_trainStd, y_train)\n param_grid = {\"n_neighbors\": [1, 3, 5, 7]}\n grid_search = GridSearchCV(knn_model, param_grid=param_grid, cv=5).fit(x_trainStd, y_train)\n print(\"网格搜索中最佳结果的参数设置:\", grid_search.best_params_)\n print(\"网格搜索中最高分数估计器的分数为:\", grid_search.best_score_)\n print(\"测试集准确率为:\", knn_model.score(x_testStd, y_test))\n print(\"每个类别的精确率和召回率:\\n\", classification_report(y_test, knn_model.predict(x_testStd),\n target_names=data_cancer.target_names))\n print(\"预测测试集前5个结果为:\", knn_model.predict(x_testStd)[:5])\n # print(\"测试集前5个最近邻点为:\\n\", knn_model.kneighbors(x_testStd)[0][:5],\n # \"\\n测试集前5个最近邻点的距离:\\n\", knn_model.kneighbors(x_testStd)[1][:5])\n\n\ndef knn_iris():\n \"\"\"\n K-近邻算法\n 鸢尾花数据集\n 含有3个特征、150条记录、目标值为0、1、2\n :return:\n \"\"\"\n # 导包\n from sklearn.datasets import load_iris\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.neighbors import KNeighborsClassifier\n from sklearn.metrics import classification_report\n # 导入数据\n data_iris = load_iris()\n # 将数据集划分为训练集和测试集\n x_train, x_test, y_train, y_test = train_test_split(\n data_iris.data, data_iris.target, test_size=0.25)\n # 数据标准化处理\n stdScaler = StandardScaler().fit(x_train)\n x_trainStd = stdScaler.transform(x_train)\n x_testStd = stdScaler.transform(x_test)\n # 使用KNeighborsClassifier函数构建knn模型\n knn_model = KNeighborsClassifier()\n knn_model.fit(x_trainStd, y_train)\n print(\"测试集准确率为:\", knn_model.score(x_testStd, y_test))\n print(\"每个类别的精确率和召回率:\\n\",\n classification_report(y_test, knn_model.predict(x_test), target_names=data_iris.target_names))\n print(\"预测测试集前5个结果为:\", knn_model.predict(x_testStd)[:5])\n # print(\"测试集前5个最近邻点为:\\n\", knn_model.kneighbors(x_testStd)[0][:5],\n # \"\\n测试集前5个最近邻点的距离:\\n\", knn_model.kneighbors(x_testStd)[1][:5])\n\n\ndef knn():\n \"\"\"\n k-近邻算法预测用户签到位置\n :return:\n \"\"\"\n import pandas as pd\n # 读取数据\n data = pd.read_csv(\"./\")\n\n # 处理数据\n # 1.缩小数据范围,查询数据信息\n data = data.query(\"x>1.0 & x<1.25 & y>2.5 & y<2.75\")\n # 处理时间的数据\n time_value = pd.to_datetime(data[\"time\"], unit=\"s\")\n # 把日期格式转换成字典格式\n time_value = pd.DatetimeIndex(time_value)\n\n # 构造特征值\n data[\"day\"] = time_value.day\n data[\"hour\"] = time_value.hour\n data[\"weekday\"] = time_value.weekday\n\n # 删除时间戳特征\n data = data.drop([\"time\"], axis=1)\n\n # 把签到的数量少于n个目标位置删除\n place_count = data.groupby(\"place_id\").count()\n tf = place_count[place_count.row_id > 3].reset_index()\n data = data[data[\"place_id\"].isin(tf.place_id)]\n\n # 取出数据中的特征值和目标值\n y = data[\"place_id\"]\n x = data.drop([\"place_id\"], axis=1)\n\n\ndef naive_bayes():\n \"\"\"\n 朴素贝叶斯进行文本分类\n 对20类新闻数据进行预估\n 处理流程:\n 1.加载20类新闻数据集,并进行分割\n 2.生成文章特征词\n 3.朴素贝叶斯估计器预估\n :return:\n \"\"\"\n from sklearn.datasets import fetch_20newsgroups\n from sklearn.model_selection import train_test_split\n from sklearn.feature_extraction.text import TfidfVectorizer\n from sklearn.naive_bayes import MultinomialNB\n # 加载数据\n news = fetch_20newsgroups(subset=\"all\")\n # 数据分割\n print(news.data[:2])\n x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25)\n # 对数据进行特征抽取,实例化TF-IDF\n tf = TfidfVectorizer()\n # 以训练集中的词的列表进行每篇文章重要性统计\n x_train = tf.fit_transform(x_train)\n # print(tf.get_feature_names())\n x_test = tf.transform(x_test)\n print(x_train.shape)\n print(x_test.shape)\n # 进行朴素贝叶斯算法的预测\n mlt = MultinomialNB(alpha=1.0)\n mlt.fit(x_train, y_train)\n y_predict = mlt.predict(x_test)\n print(\"预测测试集前10个结果:\", y_predict[:10])\n # 获取预测的准确率\n print(\"测试集准确率为:\", mlt.score(x_test, y_test))\n return None\n\n\ndef decision_tree_iris():\n \"\"\"\n 决策树鸢尾花数据集\n :return:\n \"\"\"\n # 导包\n from sklearn.model_selection import train_test_split\n from sklearn.datasets import load_iris\n from sklearn.tree import DecisionTreeClassifier\n from sklearn import tree\n import graphviz\n # 加载数据\n data_iris = load_iris()\n # 拆分数据集\n x_train, x_test, y_train, y_test = train_test_split(data_iris.data, data_iris.target, test_size=0.25)\n # 实例化决策树估计器\n decision_tree_model = DecisionTreeClassifier()\n # 训练数据\n decision_tree_model.fit(x_train, y_train)\n # 测试集得分\n print(\"测试集得分: \", decision_tree_model.score(x_test, y_test))\n # 决策过程可视化,安装graphviz,windows运行需要添加到环境变量,结果输出为pdf文件\n dot_data = tree.export_graphviz(decision_tree_model,out_file=None)\n graph = graphviz.Source(dot_data)\n graph.render(\"iris\")\n pass\n\n\ndef decision_tree():\n \"\"\"\n 决策树:\n 泰坦尼克号乘客生存分类分析\n 处理流程:\n 1.pd读取数据\n 2.选择有影响的特征\n 3.处理缺失值\n 4.进行特征工程,pd转换字典,特征抽取\n 5.决策树估计器预估\n :return:\n \"\"\"\n # 导包\n import pandas as pd\n from sklearn.model_selection import train_test_split\n from sklearn.feature_extraction import DictVectorizer\n from sklearn.tree import DecisionTreeClassifier, export_graphviz\n # 加载数据\n titan = pd.read_csv(\"http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt\")\n # 处理数据,找出特征值和目标值\n x = titan[[\"pclass\", \"age\", \"sex\"]]\n print(type(x))\n y = titan[\"survived\"]\n # print(x[\"age\"])\n # 缺失值处理。\n # inplace=True,不创建新的对象,直接对原始对象进行修改\n # inplace=False,对数据进行修改,创建并返回新的对象接收修改的结果\n x[\"age\"].fillna(x[\"age\"].mean(), inplace=True)\n\n # 分割数据集为训练集和测试机\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\n # 特征工程:DictVectorizer对非数字化数据进行特征值化 (one_hot编码)\n dict = DictVectorizer(sparse=False)\n # 调用fit_transform()输入数据并转换,输入的数据是字典格式\n x_train = dict.fit_transform(x_train.to_dict(orient=\"records\"))\n print(dict.get_feature_names())\n # orient=\"records\" 形成[{column -> value}, … , {column -> value}]的结构\n # 整体构成一个列表,内层是将原始数据的每行提取出来形成字典\n x_test = dict.transform(x_test.to_dict(orient=\"records\"))\n # print(x_train)\n # 使用决策树估计器进行预测\n deci_tree = DecisionTreeClassifier()\n # 训练数据\n deci_tree.fit(x_train, y_train)\n print(\"预测的准确率:\", deci_tree.score(x_test, y_test))\n # dot_data = export_graphviz(deci_tree,out_file=None,feature_names=[\"年龄\",\"pclass=1st\",\"pclass=2st\",\"pclass=3st\",'女性', '男性'])\n\n\ndef random_forest():\n \"\"\"\n 随机森林\n 泰坦尼克号乘客生存分析\n :return:\n \"\"\"\n # 导包\n import pandas as pd\n from sklearn.model_selection import train_test_split\n from sklearn.feature_extraction import DictVectorizer\n from sklearn.ensemble import RandomForestClassifier\n from sklearn.model_selection import GridSearchCV\n\n # 加载数据\n titan = pd.read_csv(\"http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt\")\n # 处理数据,找出特征值和目标值\n x = titan[[\"pclass\", \"age\", \"sex\"]]\n y = titan[\"survived\"]\n # print(x.loc[:,\"age\"])\n\n # 缺失值处理。inplace=True不创建对象直接对原对象进行修改\n x.loc[:, \"age\"].fillna(x.loc[:, \"age\"].mean, inplace=True)\n # x[\"age\"].fillna(x[\"age\"].mean,inplace=True)\n\n # 分割数据集为训练集和测试集\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\n\n # 数据处理:对数据进行特征值化(特征抽取)。\n dict = DictVectorizer(sparse=False)\n\n # 训练转换数据\n x_train = dict.fit_transform(x_train.to_dict(orient=\"records\"))\n\n x_test = dict.transform(x_test.to_dict(orient=\"records\"))\n\n # 随机森林进行预测\n rf = RandomForestClassifier()\n # 超参数\n param = {\"n_estimators\": [120, 200, 300, 500, 800, 1200], \"max_depth\": [5, 8, 15, 25, 30]}\n # 网格搜索与交叉验证\n gc = GridSearchCV(rf, param_grid=param, cv=2)\n gc.fit(x_train, y_train)\n print(\"准确率:\", gc.score(x_test, y_test))\n print(\"查看选择的参数:\", gc.best_params_)\n return None\n\ndef random_forest_cancer():\n \"\"\"\n 随机森林\n 威斯康星州乳腺癌数据集\n 含有30个特征、569条记录、目标值为0或1\n :return:\n \"\"\"\n from sklearn.datasets import load_breast_cancer\n from sklearn.model_selection import train_test_split\n from sklearn.ensemble import RandomForestClassifier\n from sklearn.preprocessing import StandardScaler\n # 导入数据\n data_cancer = load_breast_cancer()\n # 将数据集划分为训练集和测试集\n x_train,x_test,y_train,y_test = train_test_split(\n data_cancer.data,data_cancer.target,test_size=0.25)\n # # 数据标准化处理\n # stdScaler = StandardScaler().fit(x_train)\n # x_trainStd = stdScaler.transform(x_train)\n # x_testStd = stdScaler.transform(x_test)\n rf_model = RandomForestClassifier(n_estimators=10)\n rf_model.fit(x_train,y_train)\n print(\"训练出的前2个决策树的模型为:\",rf_model.estimators_[0:2])\n print(\"预测测试集前10个结果为:\",rf_model.predict(x_test)[:10])\n print(\"测试集准确率为:\",rf_model.score(x_test,y_test))\n pass\n\ndef logistic_regression():\n \"\"\"\n 逻辑回归分类算法\n 应用场景:\n 判断用户性别,预测用户是否购买给定的商品,判断一条评论是正面还是负面\n 数据:load_breast_cancer(威斯康星州乳腺癌数据),包含30个特征,569条记录,目标值为0或1\n :return:\n \"\"\"\n # 导包\n from sklearn.datasets import load_breast_cancer\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.linear_model import LogisticRegression\n\n # 加载数据\n data_cancer = load_breast_cancer()\n # 将数据集划分为训练集和测试机\n x_train, x_test, y_train, y_test = train_test_split(data_cancer[\"data\"], data_cancer[\"target\"], test_size=0.25)\n\n # 数据标准化\n standard = StandardScaler()\n standard.fit(x_train)\n x_trainStd = standard.transform(x_train)\n x_testStd = standard.transform(x_test)\n\n # 构建模型\n logestic_model = LogisticRegression(solver=\"saga\")\n logestic_model.fit(x_trainStd, y_train)\n print(\"训练的模型为:\", logestic_model)\n print(\"模型各特征的相关系数:\", logestic_model.coef_)\n\n # 预测测试机\n print(\"预测的测试机结果为:\\n\", logestic_model.predict(x_testStd))\n print(\"预测的准确率为:\\n\", logestic_model.score(x_testStd, y_test))\n return None\n\n\n\n\n\nif __name__ == \"__main__\":\n \"\"\"\n 分类算法1:k近邻算法(KNN)\n 概念:如果一个样本中在特定空间中的K个最相似(即特征空间中最相邻)的样本中的大多数属于某一个类别,\n 则该样本也属于这个类别\n K近邻算法API:sklearn.neighbors.KNeighborsClassifier(n_neighbors=5,algorithm='auto')\n n_neighbors:邻居数,默认是5\n algorithm:选用计算最近邻居的算法,默认'auto',自动选择 \n 距离采用:欧氏距离\n \"\"\"\n \"\"\"\n 分类算法2:朴素贝叶斯(所有特征之间是条件独立的)\n API:sklearn.naive_bayes.MultinomialNB(alpha=1.0)\n alpha:拉普拉斯平滑系数,默认1\n \"\"\"\n # naive_bayes()\n knn_breast_cancer()\n # knn_iris()kn\n\n \"\"\"\n 分类算法3:决策树。思想很简单就是if else\n 信息熵代表信息量的大小,值越大代表信息量越大\n 信息增益:得知一个信息之后,信息熵减少的大小\n API:sklearn.tree.DecisionTreeClassifier(criterion='gini',max_depth=None,random_state=None)\n criterion:默认是'gini'系数,也可以选择信息增益的熵'entropy'\n max_depth:树的深度大小\n random_state:随机数种子\n 返回值:决策树的路径\n \"\"\"\n # decision_tree()\n # decision_tree_iris()\n\n\n \"\"\"\n 分类算法4:随机森林(又叫集成学习)\n 随机森林就是通过集成学习的思想将多棵树集成的一种算法,它的基本单元是决策树,本质是机器学习分支--集成学习(Ensemble learing)方法。\n 每棵树都是一个分类器,那么对于一个输入样本,N棵树会有N个分类结果。随机森林集成了所有的分类投票结果,将投票次数最多的类别指定为最终的输出。\n 注意:\n 1.随机抽样训练集。避免训练出的树分类结果都一样\n 2.有放回的抽样,避免每棵树的训练样本完全不同,没有交集,这样每棵树都是\"有偏的\",都是绝对\"片面的\" \n API:sklearn.ensemble.RandomForestClassifier(n_estimators=10,criterion='gini',max_depth=None,bootstrap=True,random_state=None)\n n_estimators:森林里的树木数量,默认10\n criteria:分割特征的测量方法,默认gini系数\n max_depth:树的最大深度,默认无\n bootstrap:构建有放回的抽样,默认True\n 优点:\n 1.当前几个算法中具有极高的准确率 \n 2.有效的运行在大数据集上\n 3.能够处理高维数据,且不用降维\n 4.对缺省的数据能够获得很好的结果\n \"\"\"\n # random_forest()\n # random_forest_cancer()\n\n \"\"\"\n 分类算法5:逻辑回归\n 逻辑回归是解决二分类问题的利器。\n sigmoid函数:输出的值在[0,1]之间,默认概率0.5阈值,超过0.5认为有可能发生,小于0.5认为不可能发生\n API:sklearn.linear_model.LogisticRegression\n \n \"\"\"\n # logistic_regression()\n" }, { "alpha_fraction": 0.5219970345497131, "alphanum_fraction": 0.53880375623703, "avg_line_length": 28.28985595703125, "blob_id": "f34e4a894b759ac0f0be3b2a6819b6da7309b341", "content_id": "5b07274dee4b2bdd087735fb97311dcd877fc57e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3079, "license_type": "no_license", "max_line_length": 81, "num_lines": 69, "path": "/ss_09_推荐算法.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\n\ndef apriori():\n \"\"\"\n 使用Apriori算法找出数据的频繁项集,进而分析物品关联度\n :return:\n \"\"\"\n\n #导包\n import pandas as pd\n from mlxtend.preprocessing import TransactionEncoder\n from mlxtend.frequent_patterns import apriori\n # 导入关联规则包\n from mlxtend.frequent_patterns import association_rules\n\n #设置数据集\n data_set = [['牛奶','洋葱','肉豆蔻','芸豆','鸡蛋','酸奶'],\n ['莳萝','洋葱','肉豆蔻','芸豆','鸡蛋','酸奶'],\n ['牛奶','苹果','芸豆','鸡蛋'],\n ['牛奶','独角兽','玉米','芸豆','酸奶'],\n ['玉米','洋葱','洋葱','芸豆','冰淇淋','鸡蛋']]\n\n te = TransactionEncoder()\n #进行one-hot编码\n te_ary = te.fit(data_set).transform(data_set)\n # print(type(te_ary))\n df = pd.DataFrame(te_ary,columns=te.columns_)\n #利用apriori找出频繁项集\n freq = apriori(df,min_support=0.4,use_colnames=True)\n #计算关联规则\n result = association_rules(freq,metric=\"confidence\",min_threshold=0.6)\n # 排序\n result.sort_values(by = 'confidence',ascending=False,axis=0)\n print(result)\n result.to_excel(\"./result.xlsx\")\n return None\n\n\nif __name__==\"__main__\":\n \"\"\"\n 无监督学习算法\n 推荐算法:又叫亲和性分析、关联规则\n 简单点说,就是先找频繁项集,再根据关联规则找关联物品。\n Apriori算法进行物品的关联分析\n 支持度(support):可以理解为物品的流行程度。支持度=(包含物品A的记录数)/(总的记录数)\n 置信度(confidence):置信度是指如果购买物品A,有多大可能购买物品B。置信度(A->B)=(包含物品A和B的记录数)/(包含A的记录数)\n 提升度(lift):指当销售一个物品时,另一个物品销售率会增加多少。提升度(A->B)=置信度(A->B)/(支持度A)。\n 提升度大于1,说明A物品卖的越多,B也会卖的越多。等于1 说明A、B之间没有关联。小于1,说明A卖的越多反而建设B卖的数量\n \n 问题:\n 顾客 购买商品集合\n 顾客1:牛奶,洋葱,肉豆蔻,芸豆,鸡蛋,酸奶\n 顾客2:莳萝,洋葱,肉豆蔻,芸豆,鸡蛋,酸奶\n 顾客3:牛奶,苹果,芸豆,鸡蛋\n 顾客4:牛奶,独角兽,玉米,芸豆,酸奶\n 顾客5:玉米,洋葱,洋葱,芸豆,冰淇淋,鸡蛋\n \n 支持度:(包含物品A的记录数)/(总的记录数)\n 牛奶 = 3/5\n 鸡蛋 = 4/5\n 置信度:(包含物品A和B的记录数)/(包含A的记录数)\n {牛奶,鸡蛋} = 2次\n {牛奶}=3次\n confidence{牛奶,鸡蛋} = 2/3\n 购买牛奶的顾客中,有2/3的顾客会购买鸡蛋\n 提升度:置信度(A->B)/(支持度B)。\n {牛奶,鸡蛋}的置信度为:2/3\n 牛奶的支持度为:4/5\n 提升度为:(2/3)/(4/5)=0.83\n \"\"\"\n apriori()\n" }, { "alpha_fraction": 0.6457800269126892, "alphanum_fraction": 0.6636828780174255, "avg_line_length": 20.63888931274414, "blob_id": "0bdc50fa3a32402d69f77ba1d7407cf1d3e91ad3", "content_id": "976c3b783e7a8d775a6651cec8bdc7872beba0f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 92, "num_lines": 36, "path": "/财政收入影响因素分析及预测/demo/code/01-summary.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\n\n# 代码6-1\n\nimport numpy as np\nimport pandas as pd\n\ninputfile = '../data/data.csv' # 输入的数据文件\ndata = pd.read_csv(inputfile) # 读取数据\n\n# 描述性统计分析\ndescription = [data.min(), data.max(), data.mean(), data.std()] # 依次计算最小值、最大值、均值、标准差\ndescription = pd.DataFrame(description, index = ['Min', 'Max', 'Mean', 'STD']).T # 将结果存入数据框\nprint('描述性统计结果:\\n',np.round(description, 2)) # 保留两位小数\n\n\n\n# 代码6-2\n\n# 相关性分析\ncorr = data.corr(method = 'pearson') # 计算相关系数矩阵\nprint('相关系数矩阵为:\\n',np.round(corr, 2)) # 保留两位小数\n\n\n\n# 代码6-3\n\n# 绘制热力图\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.rcParams['font.sans-serif']=['SimHei']\nplt.subplots(figsize=(10, 10)) # 设置画面大小 \nsns.heatmap(corr, annot=True, vmax=1, square=True, cmap=\"Blues\") \nplt.title('相关性热力图')\nplt.show()\nplt.close\n\n\n\n" }, { "alpha_fraction": 0.6019613146781921, "alphanum_fraction": 0.6338323950767517, "avg_line_length": 31.44318199157715, "blob_id": "f5b0a41f7a1f5e19fd8f79dd1de2052e56d66d5d", "content_id": "57ab59bab79006a306dcb983c841a201df73bee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13428, "license_type": "no_license", "max_line_length": 140, "num_lines": 352, "path": "/京东用户购买意向预测/test.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import time\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pandas as pd\nimport pickle\nimport os\nimport math\nimport numpy as np\n\"\"\"\n特征工程\n\n特征\n\n用户基本特征:\n•获取基本的用户特征,基于用户本身属性多为类别特征的特点,对age,sex,usr_lv_cd进行独热编码操作,对于用户注册时间暂时不处理\n\n商品基本特征:\n•根据商品文件获取基本的特征\n•针对属性a1,a2,a3进行独热编码\n•商品类别和品牌直接作为特征\n\n评论特征:\n•分时间段,\n•对评论数进行独热编码\n\n行为特征:\n•分时间段\n•对行为类别进行独热编码\n•分别按照用户-类别行为分组和用户-类别-商品行为分组统计,然后计算\n•用户对同类别下其他商品的行为计数\n•不同时间累积的行为计数(3,5,7,10,15,21,30\n\n累积用户特征:\n•分时间段\n•用户不同行为的\n•购买转化率\n•均值\n\n用户近期行为特征:\n•在上面针对用户进行累积特征提取的基础上,分别提取用户近一个月、近三天的特征,然后提取一个月内用户除去最近三天的行为占据一个月的行为的比重\n\n用户对同类别下各种商品的行为:\n•用户对各个类别的各项行为操作统计\n•用户对各个类别操作行为统计占对所有类别操作行为统计的比重\n\n累积商品特征:\n•分时间段\n•针对商品的不同行为的\n•购买转化率\n•均值\n\n类别特征\n•分时间段下各个商品类别的\n•购买转化率\n•均值\n\n\"\"\"\ntest = pd.read_csv('./data/JData_Action_201602.csv')\ntest[['user_id','sku_id','model_id','type','cate','brand']] = test[['user_id','sku_id','model_id','type','cate','brand']].astype('float32')\ntest.dtypes\nprint(test.info())\n\ntest = pd.read_csv('data/JData_Action_201602.csv')\n#test[['user_id','sku_id','model_id','type','cate','brand']] = test[['user_id','sku_id','model_id','type','cate','brand']].astype('float32')\ntest.dtypes\nprint(test.info())\n\naction_1_path = r'./data/JData_Action_201602.csv'\naction_2_path = r'./data/JData_Action_201603.csv'\naction_3_path = r'./data/JData_Action_201604.csv'\n#action_1_path = r'./data/actions1.csv'\n#action_2_path = r'./data/actions2.csv'\n#action_3_path = r'./data/actions3.csv'\ncomment_path = r'./data/JData_Comment.csv'\nproduct_path = r'./data/JData_Product.csv'\nuser_path = r'./data/JData_User.csv'\n#user_path = r'data/user.csv'\n\ncomment_date = [\n \"2016-02-01\", \"2016-02-08\", \"2016-02-15\", \"2016-02-22\", \"2016-02-29\",\n \"2016-03-07\", \"2016-03-14\", \"2016-03-21\", \"2016-03-28\", \"2016-04-04\",\n \"2016-04-11\", \"2016-04-15\"\n]\n\n\ndef get_actions_0():\n action = pd.read_csv(action_1_path)\n return action\n\n\ndef get_actions_1():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n return action\n\n\ndef get_actions_2():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n\n return action\n\n\ndef get_actions_3():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n\n return action\n\n\ndef get_actions_10():\n reader = pd.read_csv(action_1_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\ndef get_actions_20():\n reader = pd.read_csv(action_2_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\ndef get_actions_30():\n reader = pd.read_csv(action_3_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\n# 读取并拼接所有行为记录文件\n\ndef get_all_action():\n action_1 = get_actions_1()\n action_2 = get_actions_2()\n action_3 = get_actions_3()\n actions = pd.concat([action_1, action_2, action_3]) # type: # pd.DataFrame\n # actions = pd.concat([action_1, action_2])\n # actions = pd.read_csv(action_path)\n return actions\n\n\n# 获取某个时间段的行为记录\ndef get_actions(start_date, end_date, all_actions):\n \"\"\"\n :param start_date:\n :param end_date:\n :return: actions: pd.Dataframe\n \"\"\"\n actions = all_actions[(all_actions.time >= start_date) & (all_actions.time < end_date)].copy()\n return actions\n\n\n\"\"\"\n用户特征\n\n用户基本特征\n获取基本的用户特征,基于用户本身属性多为类别特征的特点,对age,sex,usr_lv_cd进行独热编码操作,对于用户注册时间暂时不处理\n\"\"\"\n\nfrom sklearn import preprocessing\n\ndef get_basic_user_feat():\n # 针对年龄的中文字符问题处理,首先是读入的时候编码,填充空值,然后将其数值化,最后独热编码,此外对于sex也进行了数值类型转换\n user = pd.read_csv(user_path, encoding='gbk')\n #user['age'].fillna('-1', inplace=True)\n #user['sex'].fillna(2, inplace=True)\n user.dropna(axis=0, how='any',inplace=True)\n user['sex'] = user['sex'].astype(int)\n user['age'] = user['age'].astype(int)\n le = preprocessing.LabelEncoder()\n age_df = le.fit_transform(user['age'])\n # print list(le.classes_)\n\n age_df = pd.get_dummies(age_df, prefix='age')\n sex_df = pd.get_dummies(user['sex'], prefix='sex')\n user_lv_df = pd.get_dummies(user['user_lv_cd'], prefix='user_lv_cd')\n user = pd.concat([user['user_id'], age_df, sex_df, user_lv_df], axis=1)\n return user\n\nuser = pd.read_csv(user_path, encoding='gbk')\nuser.isnull().any()\n\nuser[user.isnull().values==True]\n\nuser.dropna(axis=0, how='any',inplace=True)\nuser.isnull().any()\n#user[user.isnull().values==True]\n\n\"\"\"\n商品特征¶\n\n商品基本特征\n根据商品文件获取基本的特征,针对属性a1,a2,a3进行独热编码,商品类别和品牌直接作为特征\n\"\"\"\ndef get_basic_product_feat():\n product = pd.read_csv(product_path)\n attr1_df = pd.get_dummies(product[\"a1\"], prefix=\"a1\")\n attr2_df = pd.get_dummies(product[\"a2\"], prefix=\"a2\")\n attr3_df = pd.get_dummies(product[\"a3\"], prefix=\"a3\")\n product = pd.concat([product[['sku_id', 'cate', 'brand']], attr1_df, attr2_df, attr3_df], axis=1)\n return product\n\n\"\"\"\n评论特征\n •分时间段\n •对评论数进行独热编码\n\"\"\"\n\n\ndef get_comments_product_feat(end_date):\n comments = pd.read_csv(comment_path)\n comment_date_end = end_date\n comment_date_begin = comment_date[0]\n for date in reversed(comment_date):\n if date < comment_date_end:\n comment_date_begin = date\n break\n comments = comments[comments.dt == comment_date_begin]\n df = pd.get_dummies(comments['comment_num'], prefix='comment_num')\n # 为了防止某个时间段不具备评论数为0的情况(测试集出现过这种情况)\n for i in range(0, 5):\n if 'comment_num_' + str(i) not in df.columns:\n df['comment_num_' + str(i)] = 0\n df = df[['comment_num_0', 'comment_num_1', 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n\n comments = pd.concat([comments, df], axis=1) # type: pd.DataFrame\n # del comments['dt']\n # del comments['comment_num']\n comments = comments[['sku_id', 'has_bad_comment', 'bad_comment_rate', 'comment_num_0', 'comment_num_1',\n 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n return comments\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\nday = 3\n\nstart_date = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=day)\nstart_date = start_date.strftime('%Y-%m-%d')\n\ncomments = pd.read_csv(comment_path)\ncomment_date_end = train_end_date\ncomment_date_begin = comment_date[0]\nfor date in reversed(comment_date):\n if date < comment_date_end:\n comment_date_begin = date\n break\ncomments = comments[comments.dt == comment_date_begin]\ndf = pd.get_dummies(comments['comment_num'], prefix='comment_num')\nfor i in range(0, 5):\n if 'comment_num_' + str(i) not in df.columns:\n df['comment_num_' + str(i)] = 0\ndf = df[['comment_num_0', 'comment_num_1', 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n\ncomments = pd.concat([comments, df], axis=1) # type: pd.DataFrame\n# del comments['dt']\n# del comments['comment_num']\ncomments = comments[['sku_id', 'has_bad_comment', 'bad_comment_rate', 'comment_num_0', 'comment_num_1',\n 'comment_num_2', 'comment_num_3', 'comment_num_4']]\nprint(comments.head())\n\n\n\"\"\"\n行为特征\n•分时间段\n•对行为类别进行独热编码\n•分别按照用户-类别行为分组和用户-类别-商品行为分组统计,然后计算\n ◾用户对同类别下其他商品的行为计数\n ◾针对用户对同类别下目标商品的行为计数与该时间段的行为均值作差\n\"\"\"\ndef get_action_feat(start_date, end_date, all_actions, i):\n actions = get_actions(start_date, end_date, all_actions)\n actions = actions[['user_id', 'sku_id', 'cate','type']]\n # 不同时间累积的行为计数(3,5,7,10,15,21,30)\n df = pd.get_dummies(actions['type'], prefix='action_before_%s' %i)\n before_date = 'action_before_%s' %i\n actions = pd.concat([actions, df], axis=1) # type: pd.DataFrame\n # 分组统计,用户-类别-商品,不同用户对不同类别下商品的行为计数\n actions = actions.groupby(['user_id', 'sku_id','cate'], as_index=False).sum()\n # 分组统计,用户-类别,不同用户对不同商品类别的行为计数\n user_cate = actions.groupby(['user_id','cate'], as_index=False).sum()\n del user_cate['sku_id']\n del user_cate['type']\n actions = pd.merge(actions, user_cate, how='left', on=['user_id','cate'])\n #本类别下其他商品点击量\n # 前述两种分组含有相同名称的不同行为的计数,系统会自动针对名称调整添加后缀,x,y,所以这里作差统计的是同一类别下其他商品的行为计数\n actions[before_date+'_1.0_y'] = actions[before_date+'_1.0_y'] - actions[before_date+'_1.0_x']\n actions[before_date+'_2.0_y'] = actions[before_date+'_2.0_y'] - actions[before_date+'_2.0_x']\n actions[before_date+'_3.0_y'] = actions[before_date+'_3.0_y'] - actions[before_date+'_3.0_x']\n actions[before_date+'_4.0_y'] = actions[before_date+'_4.0_y'] - actions[before_date+'_4.0_x']\n actions[before_date+'_5.0_y'] = actions[before_date+'_5.0_y'] - actions[before_date+'_5.0_x']\n actions[before_date+'_6.0_y'] = actions[before_date+'_6.0_y'] - actions[before_date+'_6.0_x']\n # 统计用户对不同类别下商品计数与该类别下商品行为计数均值(对时间)的差值\n actions[before_date+'minus_mean_1'] = actions[before_date+'_1.0_x'] - (actions[before_date+'_1.0_x']/i)\n actions[before_date+'minus_mean_2'] = actions[before_date+'_2.0_x'] - (actions[before_date+'_2.0_x']/i)\n actions[before_date+'minus_mean_3'] = actions[before_date+'_3.0_x'] - (actions[before_date+'_3.0_x']/i)\n actions[before_date+'minus_mean_4'] = actions[before_date+'_4.0_x'] - (actions[before_date+'_4.0_x']/i)\n actions[before_date+'minus_mean_5'] = actions[before_date+'_5.0_x'] - (actions[before_date+'_5.0_x']/i)\n actions[before_date+'minus_mean_6'] = actions[before_date+'_6.0_x'] - (actions[before_date+'_6.0_x']/i)\n del actions['type']\n # 保留cate特征\n # del actions['cate']\n\n return actions\nall_actions = get_all_action()\nactions = get_actions(start_date, train_end_date, all_actions)\nactions = actions[['user_id', 'sku_id', 'cate','type']]\n # 不同时间累积的行为计数(3,5,7,10,15,21,30)\ndf = pd.get_dummies(actions['type'], prefix='action_before_%s' %3)\nbefore_date = 'action_before_%s' %3\nactions = pd.concat([actions, df], axis=1) # type: pd.DataFrame\n # 分组统计,用户-类别-商品,不同用户对不同类别下商品的行为计数\nactions = actions.groupby(['user_id', 'sku_id','cate'], as_index=False).sum()\nprint(actions.head(20))\n\n" }, { "alpha_fraction": 0.5833415985107422, "alphanum_fraction": 0.6178758144378662, "avg_line_length": 40.272579193115234, "blob_id": "0c2d56b9fdd1413f5e0bf86cad36404a79def56b", "content_id": "c1f86e500d63b638f389de23cb2d7d8b3097f957", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53690, "license_type": "no_license", "max_line_length": 140, "num_lines": 1218, "path": "/京东用户购买意向预测/JD_3_特征工程.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import time\nfrom datetime import datetime\nfrom datetime import timedelta\nimport pandas as pd\nimport pickle\nimport os\nimport math\nimport numpy as np\n\"\"\"\n特征工程\n\n特征\n\n用户基本特征:\n•获取基本的用户特征,基于用户本身属性多为类别特征的特点,对age,sex,usr_lv_cd进行独热编码操作,对于用户注册时间暂时不处理\n\n商品基本特征:\n•根据商品文件获取基本的特征\n•针对属性a1,a2,a3进行独热编码\n•商品类别和品牌直接作为特征\n\n评论特征:\n•分时间段,\n•对评论数进行独热编码\n\n行为特征:\n•分时间段\n•对行为类别进行独热编码\n•分别按照用户-类别行为分组和用户-类别-商品行为分组统计,然后计算\n•用户对同类别下其他商品的行为计数\n•不同时间累积的行为计数(3,5,7,10,15,21,30\n\n累积用户特征:\n•分时间段\n•用户不同行为的\n•购买转化率\n•均值\n\n用户近期行为特征:\n•在上面针对用户进行累积特征提取的基础上,分别提取用户近一个月、近三天的特征,然后提取一个月内用户除去最近三天的行为占据一个月的行为的比重\n\n用户对同类别下各种商品的行为:\n•用户对各个类别的各项行为操作统计\n•用户对各个类别操作行为统计占对所有类别操作行为统计的比重\n\n累积商品特征:\n•分时间段\n•针对商品的不同行为的\n•购买转化率\n•均值\n\n类别特征\n•分时间段下各个商品类别的\n•购买转化率\n•均值\n\n\"\"\"\ntest = pd.read_csv('./data/JData_Action_201602.csv')\ntest[['user_id','sku_id','model_id','type','cate','brand']] = test[['user_id','sku_id','model_id','type','cate','brand']].astype('float32')\ntest.dtypes\nprint(test.info())\n\ntest = pd.read_csv('data/JData_Action_201602.csv')\n#test[['user_id','sku_id','model_id','type','cate','brand']] = test[['user_id','sku_id','model_id','type','cate','brand']].astype('float32')\ntest.dtypes\nprint(test.info())\n\naction_1_path = r'./data/JData_Action_201602.csv'\naction_2_path = r'./data/JData_Action_201603.csv'\naction_3_path = r'./data/JData_Action_201604.csv'\n#action_1_path = r'./data/actions1.csv'\n#action_2_path = r'./data/actions2.csv'\n#action_3_path = r'./data/actions3.csv'\ncomment_path = r'./data/JData_Comment.csv'\nproduct_path = r'./data/JData_Product.csv'\nuser_path = r'./data/JData_User.csv'\n#user_path = r'data/user.csv'\n\ncomment_date = [\n \"2016-02-01\", \"2016-02-08\", \"2016-02-15\", \"2016-02-22\", \"2016-02-29\",\n \"2016-03-07\", \"2016-03-14\", \"2016-03-21\", \"2016-03-28\", \"2016-04-04\",\n \"2016-04-11\", \"2016-04-15\"\n]\n\n\ndef get_actions_0():\n action = pd.read_csv(action_1_path)\n return action\n\n\ndef get_actions_1():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n return action\n\n\ndef get_actions_2():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n\n return action\n\n\ndef get_actions_3():\n action = pd.read_csv(action_1_path)\n action[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = action[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n\n return action\n\n\ndef get_actions_10():\n reader = pd.read_csv(action_1_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\ndef get_actions_20():\n reader = pd.read_csv(action_2_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\ndef get_actions_30():\n reader = pd.read_csv(action_3_path, iterator=True)\n reader[['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']] = reader[\n ['user_id', 'sku_id', 'model_id', 'type', 'cate', 'brand']].astype('float32')\n chunks = []\n loop = True\n while loop:\n try:\n chunk = reader.get_chunk(50000)\n chunks.append(chunk)\n except StopIteration:\n loop = False\n print(\"Iteration is stopped\")\n action = pd.concat(chunks, ignore_index=True)\n\n return action\n\n\n# 读取并拼接所有行为记录文件\n\ndef get_all_action():\n action_1 = get_actions_1()\n action_2 = get_actions_2()\n action_3 = get_actions_3()\n actions = pd.concat([action_1, action_2, action_3]) # type: # pd.DataFrame\n # actions = pd.concat([action_1, action_2])\n # actions = pd.read_csv(action_path)\n return actions\n\n\n# 获取某个时间段的行为记录\ndef get_actions(start_date, end_date, all_actions):\n \"\"\"\n :param start_date:\n :param end_date:\n :return: actions: pd.Dataframe\n \"\"\"\n actions = all_actions[(all_actions.time >= start_date) & (all_actions.time < end_date)].copy()\n return actions\n\n\n\"\"\"\n用户特征\n\n用户基本特征\n获取基本的用户特征,基于用户本身属性多为类别特征的特点,对age,sex,usr_lv_cd进行独热编码操作,对于用户注册时间暂时不处理\n\"\"\"\n\nfrom sklearn import preprocessing\n\ndef get_basic_user_feat():\n # 针对年龄的中文字符问题处理,首先是读入的时候编码,填充空值,然后将其数值化,最后独热编码,此外对于sex也进行了数值类型转换\n user = pd.read_csv(user_path, encoding='gbk')\n #user['age'].fillna('-1', inplace=True)\n #user['sex'].fillna(2, inplace=True)\n user.dropna(axis=0, how='any',inplace=True)\n user['sex'] = user['sex'].astype(int)\n user['age'] = user['age'].astype(int)\n le = preprocessing.LabelEncoder()\n age_df = le.fit_transform(user['age'])\n # print list(le.classes_)\n\n age_df = pd.get_dummies(age_df, prefix='age')\n sex_df = pd.get_dummies(user['sex'], prefix='sex')\n user_lv_df = pd.get_dummies(user['user_lv_cd'], prefix='user_lv_cd')\n user = pd.concat([user['user_id'], age_df, sex_df, user_lv_df], axis=1)\n return user\n\nuser = pd.read_csv(user_path, encoding='gbk')\nuser.isnull().any()\n\nuser[user.isnull().values==True]\n\nuser.dropna(axis=0, how='any',inplace=True)\nuser.isnull().any()\n#user[user.isnull().values==True]\n\n\"\"\"\n商品特征¶\n\n商品基本特征\n根据商品文件获取基本的特征,针对属性a1,a2,a3进行独热编码,商品类别和品牌直接作为特征\n\"\"\"\ndef get_basic_product_feat():\n product = pd.read_csv(product_path)\n attr1_df = pd.get_dummies(product[\"a1\"], prefix=\"a1\")\n attr2_df = pd.get_dummies(product[\"a2\"], prefix=\"a2\")\n attr3_df = pd.get_dummies(product[\"a3\"], prefix=\"a3\")\n product = pd.concat([product[['sku_id', 'cate', 'brand']], attr1_df, attr2_df, attr3_df], axis=1)\n return product\n\n\"\"\"\n评论特征\n •分时间段\n •对评论数进行独热编码\n\"\"\"\n\n\ndef get_comments_product_feat(end_date):\n comments = pd.read_csv(comment_path)\n comment_date_end = end_date\n comment_date_begin = comment_date[0]\n for date in reversed(comment_date):\n if date < comment_date_end:\n comment_date_begin = date\n break\n comments = comments[comments.dt == comment_date_begin]\n df = pd.get_dummies(comments['comment_num'], prefix='comment_num')\n # 为了防止某个时间段不具备评论数为0的情况(测试集出现过这种情况)\n for i in range(0, 5):\n if 'comment_num_' + str(i) not in df.columns:\n df['comment_num_' + str(i)] = 0\n df = df[['comment_num_0', 'comment_num_1', 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n\n comments = pd.concat([comments, df], axis=1) # type: pd.DataFrame\n # del comments['dt']\n # del comments['comment_num']\n comments = comments[['sku_id', 'has_bad_comment', 'bad_comment_rate', 'comment_num_0', 'comment_num_1',\n 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n return comments\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\nday = 3\n\nstart_date = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=day)\nstart_date = start_date.strftime('%Y-%m-%d')\n\ncomments = pd.read_csv(comment_path)\ncomment_date_end = train_end_date\ncomment_date_begin = comment_date[0]\nfor date in reversed(comment_date):\n if date < comment_date_end:\n comment_date_begin = date\n break\ncomments = comments[comments.dt == comment_date_begin]\ndf = pd.get_dummies(comments['comment_num'], prefix='comment_num')\nfor i in range(0, 5):\n if 'comment_num_' + str(i) not in df.columns:\n df['comment_num_' + str(i)] = 0\ndf = df[['comment_num_0', 'comment_num_1', 'comment_num_2', 'comment_num_3', 'comment_num_4']]\n\ncomments = pd.concat([comments, df], axis=1) # type: pd.DataFrame\n# del comments['dt']\n# del comments['comment_num']\ncomments = comments[['sku_id', 'has_bad_comment', 'bad_comment_rate', 'comment_num_0', 'comment_num_1',\n 'comment_num_2', 'comment_num_3', 'comment_num_4']]\nprint(comments.head())\n\n\n\"\"\"\n行为特征\n•分时间段\n•对行为类别进行独热编码\n•分别按照用户-类别行为分组和用户-类别-商品行为分组统计,然后计算\n ◾用户对同类别下其他商品的行为计数\n ◾针对用户对同类别下目标商品的行为计数与该时间段的行为均值作差\n\"\"\"\ndef get_action_feat(start_date, end_date, all_actions, i):\n actions = get_actions(start_date, end_date, all_actions)\n actions = actions[['user_id', 'sku_id', 'cate','type']]\n # 不同时间累积的行为计数(3,5,7,10,15,21,30)\n df = pd.get_dummies(actions['type'], prefix='action_before_%s' %i)\n before_date = 'action_before_%s' %i\n actions = pd.concat([actions, df], axis=1) # type: pd.DataFrame\n # 分组统计,用户-类别-商品,不同用户对不同类别下商品的行为计数\n actions = actions.groupby(['user_id', 'sku_id','cate'], as_index=False).sum()\n # 分组统计,用户-类别,不同用户对不同商品类别的行为计数\n user_cate = actions.groupby(['user_id','cate'], as_index=False).sum()\n del user_cate['sku_id']\n del user_cate['type']\n actions = pd.merge(actions, user_cate, how='left', on=['user_id','cate'])\n #本类别下其他商品点击量\n # 前述两种分组含有相同名称的不同行为的计数,系统会自动针对名称调整添加后缀,x,y,所以这里作差统计的是同一类别下其他商品的行为计数\n actions[before_date+'_1.0_y'] = actions[before_date+'_1.0_y'] - actions[before_date+'_1.0_x']\n actions[before_date+'_2.0_y'] = actions[before_date+'_2.0_y'] - actions[before_date+'_2.0_x']\n actions[before_date+'_3.0_y'] = actions[before_date+'_3.0_y'] - actions[before_date+'_3.0_x']\n actions[before_date+'_4.0_y'] = actions[before_date+'_4.0_y'] - actions[before_date+'_4.0_x']\n actions[before_date+'_5.0_y'] = actions[before_date+'_5.0_y'] - actions[before_date+'_5.0_x']\n actions[before_date+'_6.0_y'] = actions[before_date+'_6.0_y'] - actions[before_date+'_6.0_x']\n # 统计用户对不同类别下商品计数与该类别下商品行为计数均值(对时间)的差值\n actions[before_date+'minus_mean_1'] = actions[before_date+'_1.0_x'] - (actions[before_date+'_1.0_x']/i)\n actions[before_date+'minus_mean_2'] = actions[before_date+'_2.0_x'] - (actions[before_date+'_2.0_x']/i)\n actions[before_date+'minus_mean_3'] = actions[before_date+'_3.0_x'] - (actions[before_date+'_3.0_x']/i)\n actions[before_date+'minus_mean_4'] = actions[before_date+'_4.0_x'] - (actions[before_date+'_4.0_x']/i)\n actions[before_date+'minus_mean_5'] = actions[before_date+'_5.0_x'] - (actions[before_date+'_5.0_x']/i)\n actions[before_date+'minus_mean_6'] = actions[before_date+'_6.0_x'] - (actions[before_date+'_6.0_x']/i)\n del actions['type']\n # 保留cate特征\n # del actions['cate']\n\n return actions\n# TODO 错误\nall_actions = get_all_action()\nactions = get_actions(start_date, train_end_date, all_actions)\nactions = actions[['user_id', 'sku_id', 'cate','type']]\n # 不同时间累积的行为计数(3,5,7,10,15,21,30)\ndf = pd.get_dummies(actions['type'], prefix='action_before_%s' %3)\nbefore_date = 'action_before_%s' %3\nactions = pd.concat([actions, df], axis=1) # type: pd.DataFrame\n # 分组统计,用户-类别-商品,不同用户对不同类别下商品的行为计数\nactions = actions.groupby(['user_id', 'sku_id','cate'], as_index=False).sum()\nprint(actions.head(20))\n\n\n# 分组统计,用户-类别,不同用户对不同商品类别的行为计数\nuser_cate = actions.groupby(['user_id','cate'], as_index=False).sum()\ndel user_cate['sku_id']\ndel user_cate['type']\nuser_cate.head()\n\nactions = pd.merge(actions, user_cate, how='left', on=['user_id','cate'])\nactions.head()\n\nactions[before_date+'_1_y'] = actions[before_date+'_1.0_y'] - actions[before_date+'_1.0_x']\nactions.head()\n\n\n\"\"\"\n用户-行为\n\n累积用户特征\n •分时间段\n •用户不同行为的\n ◾购买转化率\n ◾均值\n\"\"\"\ndef get_accumulate_user_feat(end_date, all_actions, day):\n start_date = datetime.strptime(end_date, '%Y-%m-%d') - timedelta(days=day)\n start_date = start_date.strftime('%Y-%m-%d')\n before_date = 'user_action_%s' % day\n\n feature = [\n 'user_id', before_date + '_1', before_date + '_2', before_date + '_3',\n before_date + '_4', before_date + '_5', before_date + '_6',\n before_date + '_1_ratio', before_date + '_2_ratio',\n before_date + '_3_ratio', before_date + '_5_ratio',\n before_date + '_6_ratio', before_date + '_1_mean',\n before_date + '_2_mean', before_date + '_3_mean',\n before_date + '_4_mean', before_date + '_5_mean',\n before_date + '_6_mean', before_date + '_1_std',\n before_date + '_2_std', before_date + '_3_std', before_date + '_4_std',\n before_date + '_5_std', before_date + '_6_std'\n ]\n\n actions = get_actions(start_date, end_date, all_actions)\n df = pd.get_dummies(actions['type'], prefix=before_date)\n\n actions['date'] = pd.to_datetime(actions['time']).apply(lambda x: x.date())\n\n actions = pd.concat([actions[['user_id', 'date']], df], axis=1)\n # 分组统计,用户不同日期的行为计算标准差\n# actions_date = actions.groupby(['user_id', 'date']).sum()\n# actions_date = actions_date.unstack()\n# actions_date.fillna(0, inplace=True)\n# action_1 = np.std(actions_date[before_date + '_1'], axis=1)\n# action_1 = action_1.to_frame()\n# action_1.columns = [before_date + '_1_std']\n# action_2 = np.std(actions_date[before_date + '_2'], axis=1)\n# action_2 = action_2.to_frame()\n# action_2.columns = [before_date + '_2_std']\n# action_3 = np.std(actions_date[before_date + '_3'], axis=1)\n# action_3 = action_3.to_frame()\n# action_3.columns = [before_date + '_3_std']\n# action_4 = np.std(actions_date[before_date + '_4'], axis=1)\n# action_4 = action_4.to_frame()\n# action_4.columns = [before_date + '_4_std']\n# action_5 = np.std(actions_date[before_date + '_5'], axis=1)\n# action_5 = action_5.to_frame()\n# action_5.columns = [before_date + '_5_std']\n# action_6 = np.std(actions_date[before_date + '_6'], axis=1)\n# action_6 = action_6.to_frame()\n# action_6.columns = [before_date + '_6_std']\n# actions_date = pd.concat(\n# [action_1, action_2, action_3, action_4, action_5, action_6], axis=1)\n# actions_date['user_id'] = actions_date.index\n # 分组统计,按用户分组,统计用户各项行为的转化率、均值\n actions = actions.groupby(['user_id'], as_index=False).sum()\n# days_interal = (datetime.strptime(end_date, '%Y-%m-%d') -\n# datetime.strptime(start_date, '%Y-%m-%d')).days\n # 转化率\n# actions[before_date + '_1_ratio'] = actions[before_date +\n# '_4'] / actions[before_date +\n# '_1']\n# actions[before_date + '_2_ratio'] = actions[before_date +\n# '_4'] / actions[before_date +\n# '_2']\n# actions[before_date + '_3_ratio'] = actions[before_date +\n# '_4'] / actions[before_date +\n# '_3']\n# actions[before_date + '_5_ratio'] = actions[before_date +\n# '_4'] / actions[before_date +\n# '_5']\n# actions[before_date + '_6_ratio'] = actions[before_date +\n# '_4'] / actions[before_date +\n# '_6']\n actions[before_date + '_1_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_1.0'])\n actions[before_date + '_2_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_2.0'])\n actions[before_date + '_3_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_3.0'])\n actions[before_date + '_5_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_5.0'])\n actions[before_date + '_6_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_6.0'])\n # 均值\n actions[before_date + '_1_mean'] = actions[before_date + '_1.0'] / day\n actions[before_date + '_2_mean'] = actions[before_date + '_2.0'] / day\n actions[before_date + '_3_mean'] = actions[before_date + '_3.0'] / day\n actions[before_date + '_4_mean'] = actions[before_date + '_4.0'] / day\n actions[before_date + '_5_mean'] = actions[before_date + '_5.0'] / day\n actions[before_date + '_6_mean'] = actions[before_date + '_6.0'] / day\n #actions = pd.merge(actions, actions_date, how='left', on='user_id')\n #actions = actions[feature]\n return actions\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\nday = 3\n\nstart_date = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=day)\nstart_date = start_date.strftime('%Y-%m-%d')\nbefore_date = 'user_action_%s' % day\n\nprint (start_date)\nprint (train_end_date)\n\nprint(all_actions.shape)\n\nactions = get_actions(start_date, train_end_date, all_actions)\nactions.shape\n\nprint(actions.head())\n\ndf = pd.get_dummies(actions['type'], prefix=before_date)\ndf.head()\n\nactions['date'] = pd.to_datetime(actions['time']).apply(lambda x: x.date())\nactions = pd.concat([actions[['user_id', 'date']], df], axis=1)\nactions_date = actions.groupby(['user_id', 'date']).sum()\nprint(actions_date.head())\n#actions_date = actions_date.unstack()\n#actions_date.fillna(0, inplace=True)\n\nactions_date = actions_date.unstack()\nactions_date.fillna(0, inplace=True)\nprint(actions_date.head(3))\n\nactions = actions.groupby(['user_id'], as_index=False).sum()\nprint(actions.head())\n\nactions[before_date + '_1_ratio'] = np.log(1 + actions[before_date + '_4.0']) - np.log(1 + actions[before_date +'_1.0'])\nprint(actions.head())\n\nactions[before_date + '_1_mean'] = actions[before_date + '_1.0'] / day\nprint(actions.head())\n\n\"\"\"\n用户近期行为特征\n\n在上面针对用户进行累积特征提取的基础上,分别提取用户近一个月、近三天的特征,\n然后提取一个月内用户除去最近三天的行为占据一个月的行为的比重\n\"\"\"\n\n# all_actions = get_all_action()\ndef get_recent_user_feat(end_date, all_actions):\n actions_3 = get_accumulate_user_feat(end_date, all_actions, 3)\n actions_30 = get_accumulate_user_feat(end_date, all_actions, 30)\n actions = pd.merge(actions_3, actions_30, how='left', on='user_id')\n del actions_3\n del actions_30\n\n actions['recent_action1'] = np.log(1 + actions['user_action_30_1.0'] - actions['user_action_3_1.0']) - np.log(\n 1 + actions['user_action_30_1.0'])\n actions['recent_action2'] = np.log(1 + actions['user_action_30_2.0'] - actions['user_action_3_2.0']) - np.log(\n 1 + actions['user_action_30_2.0'])\n actions['recent_action3'] = np.log(1 + actions['user_action_30_3.0'] - actions['user_action_3_3.0']) - np.log(\n 1 + actions['user_action_30_3.0'])\n actions['recent_action4'] = np.log(1 + actions['user_action_30_4.0'] - actions['user_action_3_4.0']) - np.log(\n 1 + actions['user_action_30_4.0'])\n actions['recent_action5'] = np.log(1 + actions['user_action_30_5.0'] - actions['user_action_3_5.0']) - np.log(\n 1 + actions['user_action_30_5.0'])\n actions['recent_action6'] = np.log(1 + actions['user_action_30_6.0'] - actions['user_action_3_6.0']) - np.log(\n 1 + actions['user_action_30_6.0'])\n\n # actions['recent_action1'] = (actions['user_action_30_1']-actions['user_action_3_1'])/actions['user_action_30_1']\n # actions['recent_action2'] = (actions['user_action_30_2']-actions['user_action_3_2'])/actions['user_action_30_2']\n # actions['recent_action3'] = (actions['user_action_30_3']-actions['user_action_3_3'])/actions['user_action_30_3']\n # actions['recent_action4'] = (actions['user_action_30_4']-actions['user_action_3_4'])/actions['user_action_30_4']\n # actions['recent_action5'] = (actions['user_action_30_5']-actions['user_action_3_5'])/actions['user_action_30_5']\n # actions['recent_action6'] = (actions['user_action_30_6']-actions['user_action_3_6'])/actions['user_action_30_6']\n\n return actions\n\n\"\"\"\n用户对同类别下各种商品的行为\n •用户对各个类别的各项行为操作统计\n •用户对各个类别操作行为统计占对所有类别操作行为统计的比重\n\"\"\"\n\n#增加了用户对不同类别的交互特征\ndef get_user_cate_feature(start_date, end_date, all_actions):\n actions = get_actions(start_date, end_date, all_actions)\n actions = actions[['user_id', 'cate', 'type']]\n df = pd.get_dummies(actions['type'], prefix='type')\n actions = pd.concat([actions[['user_id', 'cate']], df], axis=1)\n actions = actions.groupby(['user_id', 'cate']).sum()\n actions = actions.unstack()\n actions.columns = actions.columns.swaplevel(0, 1)\n actions.columns = actions.columns.droplevel()\n actions.columns = [\n 'cate_4_type1', 'cate_5_type1', 'cate_6_type1', 'cate_7_type1',\n 'cate_8_type1', 'cate_9_type1', 'cate_10_type1', 'cate_11_type1',\n 'cate_4_type2', 'cate_5_type2', 'cate_6_type2', 'cate_7_type2',\n 'cate_8_type2', 'cate_9_type2', 'cate_10_type2', 'cate_11_type2',\n 'cate_4_type3', 'cate_5_type3', 'cate_6_type3', 'cate_7_type3',\n 'cate_8_type3', 'cate_9_type3', 'cate_10_type3', 'cate_11_type3',\n 'cate_4_type4', 'cate_5_type4', 'cate_6_type4', 'cate_7_type4',\n 'cate_8_type4', 'cate_9_type4', 'cate_10_type4', 'cate_11_type4',\n 'cate_4_type5', 'cate_5_type5', 'cate_6_type5', 'cate_7_type5',\n 'cate_8_type5', 'cate_9_type5', 'cate_10_type5', 'cate_11_type5',\n 'cate_4_type6', 'cate_5_type6', 'cate_6_type6', 'cate_7_type6',\n 'cate_8_type6', 'cate_9_type6', 'cate_10_type6', 'cate_11_type6'\n ]\n actions = actions.fillna(0)\n actions['cate_action_sum'] = actions.sum(axis=1)\n actions['cate8_percentage'] = (\n actions['cate_8_type1'] + actions['cate_8_type2'] +\n actions['cate_8_type3'] + actions['cate_8_type4'] +\n actions['cate_8_type5'] + actions['cate_8_type6']\n ) / actions['cate_action_sum']\n actions['cate4_percentage'] = (\n actions['cate_4_type1'] + actions['cate_4_type2'] +\n actions['cate_4_type3'] + actions['cate_4_type4'] +\n actions['cate_4_type5'] + actions['cate_4_type6']\n ) / actions['cate_action_sum']\n actions['cate5_percentage'] = (\n actions['cate_5_type1'] + actions['cate_5_type2'] +\n actions['cate_5_type3'] + actions['cate_5_type4'] +\n actions['cate_5_type5'] + actions['cate_5_type6']\n ) / actions['cate_action_sum']\n actions['cate6_percentage'] = (\n actions['cate_6_type1'] + actions['cate_6_type2'] +\n actions['cate_6_type3'] + actions['cate_6_type4'] +\n actions['cate_6_type5'] + actions['cate_6_type6']\n ) / actions['cate_action_sum']\n actions['cate7_percentage'] = (\n actions['cate_7_type1'] + actions['cate_7_type2'] +\n actions['cate_7_type3'] + actions['cate_7_type4'] +\n actions['cate_7_type5'] + actions['cate_7_type6']\n ) / actions['cate_action_sum']\n actions['cate9_percentage'] = (\n actions['cate_9_type1'] + actions['cate_9_type2'] +\n actions['cate_9_type3'] + actions['cate_9_type4'] +\n actions['cate_9_type5'] + actions['cate_9_type6']\n ) / actions['cate_action_sum']\n actions['cate10_percentage'] = (\n actions['cate_10_type1'] + actions['cate_10_type2'] +\n actions['cate_10_type3'] + actions['cate_10_type4'] +\n actions['cate_10_type5'] + actions['cate_10_type6']\n ) / actions['cate_action_sum']\n actions['cate11_percentage'] = (\n actions['cate_11_type1'] + actions['cate_11_type2'] +\n actions['cate_11_type3'] + actions['cate_11_type4'] +\n actions['cate_11_type5'] + actions['cate_11_type6']\n ) / actions['cate_action_sum']\n\n actions['cate8_type1_percentage'] = np.log(\n 1 + actions['cate_8_type1']) - np.log(\n 1 + actions['cate_8_type1'] + actions['cate_4_type1'] +\n actions['cate_5_type1'] + actions['cate_6_type1'] +\n actions['cate_7_type1'] + actions['cate_9_type1'] +\n actions['cate_10_type1'] + actions['cate_11_type1'])\n\n actions['cate8_type2_percentage'] = np.log(\n 1 + actions['cate_8_type2']) - np.log(\n 1 + actions['cate_8_type2'] + actions['cate_4_type2'] +\n actions['cate_5_type2'] + actions['cate_6_type2'] +\n actions['cate_7_type2'] + actions['cate_9_type2'] +\n actions['cate_10_type2'] + actions['cate_11_type2'])\n actions['cate8_type3_percentage'] = np.log(\n 1 + actions['cate_8_type3']) - np.log(\n 1 + actions['cate_8_type3'] + actions['cate_4_type3'] +\n actions['cate_5_type3'] + actions['cate_6_type3'] +\n actions['cate_7_type3'] + actions['cate_9_type3'] +\n actions['cate_10_type3'] + actions['cate_11_type3'])\n actions['cate8_type4_percentage'] = np.log(\n 1 + actions['cate_8_type4']) - np.log(\n 1 + actions['cate_8_type4'] + actions['cate_4_type4'] +\n actions['cate_5_type4'] + actions['cate_6_type4'] +\n actions['cate_7_type4'] + actions['cate_9_type4'] +\n actions['cate_10_type4'] + actions['cate_11_type4'])\n actions['cate8_type5_percentage'] = np.log(\n 1 + actions['cate_8_type5']) - np.log(\n 1 + actions['cate_8_type5'] + actions['cate_4_type5'] +\n actions['cate_5_type5'] + actions['cate_6_type5'] +\n actions['cate_7_type5'] + actions['cate_9_type5'] +\n actions['cate_10_type5'] + actions['cate_11_type5'])\n actions['cate8_type6_percentage'] = np.log(\n 1 + actions['cate_8_type6']) - np.log(\n 1 + actions['cate_8_type6'] + actions['cate_4_type6'] +\n actions['cate_5_type6'] + actions['cate_6_type6'] +\n actions['cate_7_type6'] + actions['cate_9_type6'] +\n actions['cate_10_type6'] + actions['cate_11_type6'])\n actions['user_id'] = actions.index\n actions = actions[[\n 'user_id', 'cate8_percentage', 'cate4_percentage', 'cate5_percentage',\n 'cate6_percentage', 'cate7_percentage', 'cate9_percentage',\n 'cate10_percentage', 'cate11_percentage', 'cate8_type1_percentage',\n 'cate8_type2_percentage', 'cate8_type3_percentage',\n 'cate8_type4_percentage', 'cate8_type5_percentage',\n 'cate8_type6_percentage'\n ]]\n return actions\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\nday = 3\n\nstart_date = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=day)\nstart_date = start_date.strftime('%Y-%m-%d')\n\nprint (start_date)\nprint (train_end_date)\n\nactions = get_actions(start_date, train_end_date, all_actions)\nactions = actions[['user_id', 'cate', 'type']]\nprint(actions.head())\n\ndf = pd.get_dummies(actions['type'], prefix='type')\nactions = pd.concat([actions[['user_id', 'cate']], df], axis=1)\nactions = actions.groupby(['user_id', 'cate']).sum()\nprint(actions.head())\n\nactions = actions.unstack()\nprint(actions.head())\n\nprint(actions.columns)\n\nactions.columns = actions.columns.swaplevel(0, 1)\nprint(actions.columns)\n\nactions.columns = actions.columns.droplevel()\nprint(actions.columns)\n\nactions.columns = [\n 'cate_4_type1', 'cate_5_type1', 'cate_6_type1', 'cate_7_type1',\n 'cate_8_type1', 'cate_9_type1', 'cate_10_type1', 'cate_11_type1',\n 'cate_4_type2', 'cate_5_type2', 'cate_6_type2', 'cate_7_type2',\n 'cate_8_type2', 'cate_9_type2', 'cate_10_type2', 'cate_11_type2',\n 'cate_4_type3', 'cate_5_type3', 'cate_6_type3', 'cate_7_type3',\n 'cate_8_type3', 'cate_9_type3', 'cate_10_type3', 'cate_11_type3',\n 'cate_4_type4', 'cate_5_type4', 'cate_6_type4', 'cate_7_type4',\n 'cate_8_type4', 'cate_9_type4', 'cate_10_type4', 'cate_11_type4',\n 'cate_4_type5', 'cate_5_type5', 'cate_6_type5', 'cate_7_type5',\n 'cate_8_type5', 'cate_9_type5', 'cate_10_type5', 'cate_11_type5',\n 'cate_4_type6', 'cate_5_type6', 'cate_6_type6', 'cate_7_type6',\n 'cate_8_type6', 'cate_9_type6', 'cate_10_type6', 'cate_11_type6'\n ]\nprint(actions.columns)\n\nactions = actions.fillna(0)\nactions['cate_action_sum'] = actions.sum(axis=1)\nprint(actions.head())\n\nactions['cate8_percentage'] = (\n actions['cate_8_type1'] + actions['cate_8_type2'] +\n actions['cate_8_type3'] + actions['cate_8_type4'] +\n actions['cate_8_type5'] + actions['cate_8_type6']\n ) / actions['cate_action_sum']\nprint(actions.head())\n\nactions['cate8_type1_percentage'] = np.log(\n 1 + actions['cate_8_type1']) - np.log(\n 1 + actions['cate_8_type1'] + actions['cate_4_type1'] +\n actions['cate_5_type1'] + actions['cate_6_type1'] +\n actions['cate_7_type1'] + actions['cate_9_type1'] +\n actions['cate_10_type1'] + actions['cate_11_type1'])\nprint(actions.head())\n\n\"\"\"\n商品-行为\n\n累积商品特征\n •分时间段\n •针对商品的不同行为的\n ◾购买转化率\n ◾均值\n ◾标准差\n\"\"\"\ndef get_accumulate_product_feat(start_date, end_date, all_actions):\n feature = [\n 'sku_id', 'product_action_1', 'product_action_2',\n 'product_action_3', 'product_action_4',\n 'product_action_5', 'product_action_6',\n 'product_action_1_ratio', 'product_action_2_ratio',\n 'product_action_3_ratio', 'product_action_5_ratio',\n 'product_action_6_ratio', 'product_action_1_mean',\n 'product_action_2_mean', 'product_action_3_mean',\n 'product_action_4_mean', 'product_action_5_mean',\n 'product_action_6_mean', 'product_action_1_std',\n 'product_action_2_std', 'product_action_3_std', 'product_action_4_std',\n 'product_action_5_std', 'product_action_6_std'\n ]\n\n actions = get_actions(start_date, end_date, all_actions)\n df = pd.get_dummies(actions['type'], prefix='product_action')\n # 按照商品-日期分组,计算某个时间段该商品的各项行为的标准差\n actions['date'] = pd.to_datetime(actions['time']).apply(lambda x: x.date())\n actions = pd.concat([actions[['sku_id', 'date']], df], axis=1)\n# actions_date = actions.groupby(['sku_id', 'date']).sum()\n# actions_date = actions_date.unstack()\n# actions_date.fillna(0, inplace=True)\n# action_1 = np.std(actions_date['product_action_1'], axis=1)\n# action_1 = action_1.to_frame()\n# action_1.columns = ['product_action_1_std']\n# action_2 = np.std(actions_date['product_action_2'], axis=1)\n# action_2 = action_2.to_frame()\n# action_2.columns = ['product_action_2_std']\n# action_3 = np.std(actions_date['product_action_3'], axis=1)\n# action_3 = action_3.to_frame()\n# action_3.columns = ['product_action_3_std']\n# action_4 = np.std(actions_date['product_action_4'], axis=1)\n# action_4 = action_4.to_frame()\n# action_4.columns = ['product_action_4_std']\n# action_5 = np.std(actions_date['product_action_5'], axis=1)# action_5 = action_5.to_frame()\n# action_5.columns = ['product_action_5_std']\n# action_6 = np.std(actions_date['product_action_6'], axis=1)\n# action_6 = action_6.to_frame()\n# action_6.columns = ['product_action_6_std']\n# actions_date = pd.concat(\n# [action_1, action_2, action_3, action_4, action_5, action_6], axis=1)\n# actions_date['sku_id'] = actions_date.index\n\n actions = actions.groupby(['sku_id'], as_index=False).sum()\n days_interal = (datetime.strptime(end_date, '%Y-%m-%d') - datetime.strptime(start_date, '%Y-%m-%d')).days\n # 针对商品分组,计算购买转化率\n# actions['product_action_1_ratio'] = actions['product_action_4'] / actions[\n# 'product_action_1']\n# actions['product_action_2_ratio'] = actions['product_action_4'] / actions[\n# 'product_action_2']\n# actions['product_action_3_ratio'] = actions['product_action_4'] / actions[\n# 'product_action_3']\n# actions['product_action_5_ratio'] = actions['product_action_4'] / actions[\n# 'product_action_5']\n# actions['product_action_6_ratio'] = actions['product_action_4'] / actions[\n# 'product_action_6']\n actions['product_action_1_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_1.0'])\n actions['product_action_2_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_2.0'])\n actions['product_action_3_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_3.0'])\n actions['product_action_5_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_5.0'])\n actions['product_action_6_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_6.0'])\n # 计算各种行为的均值\n actions['product_action_1_mean'] = actions[\n 'product_action_1.0'] / days_interal\n actions['product_action_2_mean'] = actions[\n 'product_action_2.0'] / days_interal\n actions['product_action_3_mean'] = actions[\n 'product_action_3.0'] / days_interal\n actions['product_action_4_mean'] = actions[\n 'product_action_4.0'] / days_interal\n actions['product_action_5_mean'] = actions[\n 'product_action_5.0'] / days_interal\n actions['product_action_6_mean'] = actions[\n 'product_action_6.0'] / days_interal\n #actions = pd.merge(actions, actions_date, how='left', on='sku_id')\n #actions = actions[feature]\n return actions\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\nday = 3\n\nstart_date = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=day)\nstart_date = start_date.strftime('%Y-%m-%d')\n\nprint (start_date)\nprint (train_end_date)\n\nactions = get_actions(start_date, train_end_date, all_actions)\ndf = pd.get_dummies(actions['type'], prefix='product_action')\n\nactions['date'] = pd.to_datetime(actions['time']).apply(lambda x: x.date())\nactions = pd.concat([actions[['sku_id', 'date']], df], axis=1)\nprint(actions.head())\n\nactions = actions.groupby(['sku_id'], as_index=False).sum()\nprint(actions.head())\n\ndays_interal = (datetime.strptime(train_end_date, '%Y-%m-%d') - datetime.strptime(start_date, '%Y-%m-%d')).days\nprint(days_interal)\n\nactions['product_action_1_ratio'] = np.log(1 + actions['product_action_4.0']) - np.log(1 + actions['product_action_1.0'])\nprint(actions.head())\n\n\"\"\"\n类别特征\n\n分时间段下各个商品类别的\n •购买转化率\n •标准差\n •均值\n\"\"\"\n\n\ndef get_accumulate_cate_feat(start_date, end_date, all_actions):\n feature = ['cate', 'cate_action_1', 'cate_action_2', 'cate_action_3', 'cate_action_4', 'cate_action_5',\n 'cate_action_6', 'cate_action_1_ratio', 'cate_action_2_ratio',\n 'cate_action_3_ratio', 'cate_action_5_ratio', 'cate_action_6_ratio', 'cate_action_1_mean',\n 'cate_action_2_mean', 'cate_action_3_mean', 'cate_action_4_mean', 'cate_action_5_mean',\n 'cate_action_6_mean', 'cate_action_1_std', 'cate_action_2_std', 'cate_action_3_std',\n 'cate_action_4_std', 'cate_action_5_std', 'cate_action_6_std']\n actions = get_actions(start_date, end_date, all_actions)\n actions['date'] = pd.to_datetime(actions['time']).apply(lambda x: x.date())\n df = pd.get_dummies(actions['type'], prefix='cate_action')\n actions = pd.concat([actions[['cate', 'date']], df], axis=1)\n # 按照类别-日期分组计算针对不同类别的各种行为某段时间的标准差\n # actions_date = actions.groupby(['cate','date']).sum()\n # actions_date = actions_date.unstack()\n # actions_date.fillna(0, inplace=True)\n # action_1 = np.std(actions_date['cate_action_1'], axis=1)\n # action_1 = action_1.to_frame()\n # action_1.columns = ['cate_action_1_std']\n # action_2 = np.std(actions_date['cate_action_2'], axis=1)\n # action_2 = action_2.to_frame()\n # action_2.columns = ['cate_action_2_std']\n # action_3 = np.std(actions_date['cate_action_3'], axis=1)\n # action_3 = action_3.to_frame()\n # action_3.columns = ['cate_action_3_std']\n # action_4 = np.std(actions_date['cate_action_4'], axis=1)\n # action_4 = action_4.to_frame()\n # action_4.columns = ['cate_action_4_std']\n # action_5 = np.std(actions_date['cate_action_5'], axis=1)\n # action_5 = action_5.to_frame()\n # action_5.columns = ['cate_action_5_std']\n # action_6 = np.std(actions_date['cate_action_6'], axis=1)\n # action_6 = action_6.to_frame()\n # action_6.columns = ['cate_action_6_std']\n # actions_date = pd.concat([action_1, action_2, action_3, action_4, action_5, action_6], axis=1)\n # actions_date['cate'] = actions_date.index\n # 按照类别分组,统计各个商品类别下行为的转化率\n actions = actions.groupby(['cate'], as_index=False).sum()\n days_interal = (datetime.strptime(end_date, '%Y-%m-%d') - datetime.strptime(start_date, '%Y-%m-%d')).days\n\n # actions['cate_action_1_ratio'] = actions['cate_action_4'] / actions['cate_action_1']\n # actions['cate_action_2_ratio'] = actions['cate_action_4'] / actions['cate_action_2']\n # actions['cate_action_3_ratio'] = actions['cate_action_4'] / actions['cate_action_3']\n # actions['cate_action_5_ratio'] = actions['cate_action_4'] / actions['cate_action_5']\n # actions['cate_action_6_ratio'] = actions['cate_action_4'] / actions['cate_action_6']\n actions['cate_action_1_ratio'] = (np.log(1 + actions['cate_action_4.0']) - np.log(1 + actions['cate_action_1.0']))\n actions['cate_action_2_ratio'] = (np.log(1 + actions['cate_action_4.0']) - np.log(1 + actions['cate_action_2.0']))\n actions['cate_action_3_ratio'] = (np.log(1 + actions['cate_action_4.0']) - np.log(1 + actions['cate_action_3.0']))\n actions['cate_action_5_ratio'] = (np.log(1 + actions['cate_action_4.0']) - np.log(1 + actions['cate_action_5.0']))\n actions['cate_action_6_ratio'] = (np.log(1 + actions['cate_action_4.0']) - np.log(1 + actions['cate_action_6.0']))\n # 按照类别分组,统计各个商品类别下行为在一段时间的均值\n actions['cate_action_1_mean'] = actions['cate_action_1.0'] / days_interal\n actions['cate_action_2_mean'] = actions['cate_action_2.0'] / days_interal\n actions['cate_action_3_mean'] = actions['cate_action_3.0'] / days_interal\n actions['cate_action_4_mean'] = actions['cate_action_4.0'] / days_interal\n actions['cate_action_5_mean'] = actions['cate_action_5.0'] / days_interal\n actions['cate_action_6_mean'] = actions['cate_action_6.0'] / days_interal\n # actions = pd.merge(actions, actions_date, how ='left',on='cate')\n # actions = actions[feature]\n return actions\n\n\n\"\"\"\n构造训练集/测试集\n 构造训练集/验证集\n •标签,采用滑动窗口的方式,构造训练集的时候针对产生购买的行为标记为1\n •整合特征\n\"\"\"\ndef get_labels(start_date, end_date, all_actions):\n actions = get_actions(start_date, end_date, all_actions)\n # actions = actions[actions['type'] == 4]\n # 修改为预测购买了商品8的用户预测\n actions = actions[(actions['type'] == 4) & (actions['cate'] == 8)]\n\n actions = actions.groupby(['user_id', 'sku_id'], as_index=False).sum()\n actions['label'] = 1\n actions = actions[['user_id', 'sku_id', 'label']]\n return actions\n\ntrain_start_date = '2016-03-01'\ntrain_actions = None\nall_actions = get_all_action()\nprint (\"get all actions!\")\n\nprint(all_actions.head())\nprint(all_actions.info())\nprint(all_actions.shape)\n\nuser = get_basic_user_feat()\nprint ('get_basic_user_feat finsihed')\nprint(user.head())\n\nproduct = get_basic_product_feat()\nprint ('get_basic_product_feat finsihed')\nprint(product.head())\n\ntrain_start_date = '2016-03-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\nprint(train_end_date)\n\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\n# 修正prod_acc,cate_acc的时间跨度\nstart_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=30)\nstart_days = start_days.strftime('%Y-%m-%d')\nprint(train_end_date)\nprint(start_days)\n\nuser_acc = get_recent_user_feat(train_end_date, all_actions)\nprint ('get_recent_user_feat finsihed')\n\n\"\"\"\n构造训练集\n\"\"\"\n\n\ndef make_actions(user, product, all_actions, train_start_date):\n train_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\n train_end_date = train_end_date.strftime('%Y-%m-%d')\n # 修正prod_acc,cate_acc的时间跨度\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=30)\n start_days = start_days.strftime('%Y-%m-%d')\n print(train_end_date)\n user_acc = get_recent_user_feat(train_end_date, all_actions)\n print('get_recent_user_feat finsihed')\n\n user_cate = get_user_cate_feature(train_start_date, train_end_date, all_actions)\n print('get_user_cate_feature finished')\n\n product_acc = get_accumulate_product_feat(start_days, train_end_date, all_actions)\n print('get_accumulate_product_feat finsihed')\n cate_acc = get_accumulate_cate_feat(start_days, train_end_date, all_actions)\n print('get_accumulate_cate_feat finsihed')\n comment_acc = get_comments_product_feat(train_end_date)\n print('get_comments_product_feat finished')\n # 标记\n test_start_date = train_end_date\n test_end_date = datetime.strptime(test_start_date, '%Y-%m-%d') + timedelta(days=5)\n test_end_date = test_end_date.strftime('%Y-%m-%d')\n labels = get_labels(test_start_date, test_end_date, all_actions)\n print(\"get labels\")\n\n actions = None\n for i in (3, 5, 7, 10, 15, 21, 30):\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=i)\n start_days = start_days.strftime('%Y-%m-%d')\n if actions is None:\n actions = get_action_feat(start_days, train_end_date, all_actions, i)\n else:\n # 注意这里的拼接key\n actions = pd.merge(actions, get_action_feat(start_days, train_end_date, all_actions, i), how='left',\n on=['user_id', 'sku_id', 'cate'])\n\n actions = pd.merge(actions, user, how='left', on='user_id')\n actions = pd.merge(actions, user_acc, how='left', on='user_id')\n actions = pd.merge(actions, user_cate, how='left', on='user_id')\n # 注意这里的拼接key\n actions = pd.merge(actions, product, how='left', on=['sku_id', 'cate'])\n actions = pd.merge(actions, product_acc, how='left', on='sku_id')\n actions = pd.merge(actions, cate_acc, how='left', on='cate')\n actions = pd.merge(actions, comment_acc, how='left', on='sku_id')\n actions = pd.merge(actions, labels, how='left', on=['user_id', 'sku_id'])\n # 主要是填充拼接商品基本特征、评论特征、标签之后的空值\n actions = actions.fillna(0)\n # return actions\n # 采样\n action_postive = actions[actions['label'] == 1]\n action_negative = actions[actions['label'] == 0]\n del actions\n neg_len = len(action_postive) * 10\n action_negative = action_negative.sample(n=neg_len)\n action_sample = pd.concat([action_postive, action_negative], ignore_index=True)\n\n return action_sample\n\ndef make_train_set(train_start_date, setNums ,f_path, all_actions):\n train_actions = None\n #all_actions = get_all_action()\n #print (\"get all actions!\")\n user = get_basic_user_feat()\n print ('get_basic_user_feat finsihed')\n product = get_basic_product_feat()\n print ('get_basic_product_feat finsihed')\n # 滑窗,构造多组训练集/验证集\n for i in range(setNums):\n print (train_start_date)\n if train_actions is None:\n train_actions = make_actions(user, product, all_actions, train_start_date)\n else:\n train_actions = pd.concat([train_actions, make_actions(user, product, all_actions, train_start_date)],\n ignore_index=True)\n # 接下来每次移动一天\n train_start_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=1)\n train_start_date = train_start_date.strftime('%Y-%m-%d')\n print (\"round {0}/{1} over!\".format(i+1, setNums))\n\n train_actions.to_csv(f_path, index=False)\n\nall_actions = get_all_action()\nprint (\"get all actions!\")\n\ntrain_start_date = '2016-02-01'\ntrain_end_date = datetime.strptime(train_start_date, '%Y-%m-%d') + timedelta(days=3)\ntrain_end_date\n\ntrain_end_date = train_end_date.strftime('%Y-%m-%d')\n# 修正prod_acc,cate_acc的时间跨度\nstart_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=30)\nstart_days = start_days.strftime('%Y-%m-%d')\nprint (train_end_date)\n\nuser_cate = get_user_cate_feature(train_start_date, train_end_date, all_actions)\nprint ('get_user_cate_feature finished')\n\nproduct_acc = get_accumulate_product_feat(start_days, train_end_date, all_actions)\nprint ('get_accumulate_product_feat finsihed')\n\ncate_acc = get_accumulate_cate_feat(start_days, train_end_date, all_actions)\nprint ('get_accumulate_cate_feat finsihed')\n\ncomment_acc = get_comments_product_feat(train_end_date)\nprint ('get_comments_product_feat finished')\n\n# 训练集\ntrain_start_date = '2016-02-01'\nmake_train_set(train_start_date, 20, 'train_set.csv',all_actions)\n\n\"\"\"\n构造验证集(线下测试集)\n\"\"\"\n\n\ndef make_val_answer(val_start_date, val_end_date, all_actions, label_val_s1_path):\n actions = get_actions(val_start_date, val_end_date, all_actions)\n actions = actions[(actions['type'] == 4) & (actions['cate'] == 8)]\n actions = actions[['user_id', 'sku_id']]\n actions = actions.drop_duplicates()\n actions.to_csv(label_val_s1_path, index=False)\n\n\ndef make_val_set(train_start_date, train_end_date, val_s1_path):\n # 修改时间跨度\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=30)\n start_days = start_days.strftime('%Y-%m-%d')\n all_actions = get_all_action()\n print(\"get all actions!\")\n user = get_basic_user_feat()\n print('get_basic_user_feat finsihed')\n\n product = get_basic_product_feat()\n print('get_basic_product_feat finsihed')\n # user_acc = get_accumulate_user_feat(train_end_date,all_actions,30)\n # print 'get_accumulate_user_feat finished'\n user_acc = get_recent_user_feat(train_end_date, all_actions)\n print('get_recent_user_feat finsihed')\n user_cate = get_user_cate_feature(train_start_date, train_end_date, all_actions)\n print('get_user_cate_feature finished')\n\n product_acc = get_accumulate_product_feat(start_days, train_end_date, all_actions)\n print('get_accumulate_product_feat finsihed')\n cate_acc = get_accumulate_cate_feat(start_days, train_end_date, all_actions)\n print('get_accumulate_cate_feat finsihed')\n comment_acc = get_comments_product_feat(train_end_date)\n print('get_comments_product_feat finished')\n\n actions = None\n for i in (3, 5, 7, 10, 15, 21, 30):\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=i)\n start_days = start_days.strftime('%Y-%m-%d')\n if actions is None:\n actions = get_action_feat(start_days, train_end_date, all_actions, i)\n else:\n actions = pd.merge(actions, get_action_feat(start_days, train_end_date, all_actions, i), how='left',\n on=['user_id', 'sku_id', 'cate'])\n\n actions = pd.merge(actions, user, how='left', on='user_id')\n actions = pd.merge(actions, user_acc, how='left', on='user_id')\n actions = pd.merge(actions, user_cate, how='left', on='user_id')\n # 注意这里的拼接key\n actions = pd.merge(actions, product, how='left', on=['sku_id', 'cate'])\n actions = pd.merge(actions, product_acc, how='left', on='sku_id')\n actions = pd.merge(actions, cate_acc, how='left', on='cate')\n actions = pd.merge(actions, comment_acc, how='left', on='sku_id')\n actions = actions.fillna(0)\n\n # print actions\n # 构造真实用户购买情况作为后续验证\n val_start_date = train_end_date\n val_end_date = datetime.strptime(val_start_date, '%Y-%m-%d') + timedelta(days=5)\n val_end_date = val_end_date.strftime('%Y-%m-%d')\n make_val_answer(val_start_date, val_end_date, all_actions, 'label_' + val_s1_path)\n\n actions.to_csv(val_s1_path, index=False)\n\n# 验证集\n# train_start_date = '2016-04-06'\n# make_train_set(train_start_date, 3, 'val_set.csv')\n#make_val_set('2016-02-21', '2016-02-24', 'val_1.csv')\n#make_val_set('2016-02-22', '2016-02-25', 'val_2.csv')\nmake_val_set('2016-02-23', '2016-02-26', 'val_3.csv')\n\n\"\"\"\n构造测试集\n\"\"\"\n\n\ndef make_test_set(train_start_date, train_end_date):\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=30)\n start_days = start_days.strftime('%Y-%m-%d')\n all_actions = get_all_action()\n print\n \"get all actions!\"\n user = get_basic_user_feat()\n print\n 'get_basic_user_feat finsihed'\n product = get_basic_product_feat()\n print\n 'get_basic_product_feat finsihed'\n\n user_acc = get_recent_user_feat(train_end_date, all_actions)\n print\n 'get_accumulate_user_feat finsihed'\n\n user_cate = get_user_cate_feature(train_start_date, train_end_date, all_actions)\n print\n 'get_user_cate_feature finished'\n\n product_acc = get_accumulate_product_feat(start_days, train_end_date, all_actions)\n print\n 'get_accumulate_product_feat finsihed'\n cate_acc = get_accumulate_cate_feat(start_days, train_end_date, all_actions)\n print\n 'get_accumulate_cate_feat finsihed'\n comment_acc = get_comments_product_feat(train_end_date)\n\n actions = None\n for i in (3, 5, 7, 10, 15, 21, 30):\n start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=i)\n start_days = start_days.strftime('%Y-%m-%d')\n if actions is None:\n actions = get_action_feat(start_days, train_end_date, all_actions, i)\n else:\n actions = pd.merge(actions, get_action_feat(start_days, train_end_date, all_actions, i), how='left',\n on=['user_id', 'sku_id', 'cate'])\n\n actions = pd.merge(actions, user, how='left', on='user_id')\n actions = pd.merge(actions, user_acc, how='left', on='user_id')\n actions = pd.merge(actions, user_cate, how='left', on='user_id')\n # 注意这里的拼接key\n actions = pd.merge(actions, product, how='left', on=['sku_id', 'cate'])\n actions = pd.merge(actions, product_acc, how='left', on='sku_id')\n actions = pd.merge(actions, cate_acc, how='left', on='cate')\n actions = pd.merge(actions, comment_acc, how='left', on='sku_id')\n\n actions = actions.fillna(0)\n\n actions.to_csv(\"test_set.csv\", index=False)\n\n\"\"\"\n4.13~4.16这三天的评论记录似乎并不存在为0的情况,导致构建测试集时出错\nKeyError: \"['comment_num_0'] not in index\"\n\"\"\"\n# 预测结果\nsub_start_date = '2016-04-13'\nsub_end_date = '2016-04-16'\nmake_test_set(sub_start_date, sub_end_date)" }, { "alpha_fraction": 0.6683798432350159, "alphanum_fraction": 0.6858304142951965, "avg_line_length": 28.878570556640625, "blob_id": "5de39984e2f422e36e91fc321bea539491b606fc", "content_id": "c03841facb524a9523b46e052cfdc21332a15874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19629, "license_type": "no_license", "max_line_length": 155, "num_lines": 560, "path": "/房价预测/房价预测.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n房价预测任务\n\n目标:根据房屋属性预测每个房子的最终价格。 FAO\n\n任务流程:\n\n (一):分析数据指标\n •不同指标对结果的影响\n •连续值与离散值的情况\n\n (二):观察数据正太性\n •是否满足正太分布\n •数据变换操作\n\n (三):数据预处理\n •缺失值填充\n •标签转换\n\n (四):集成方法建模对比\n •单模型回归效果\n •平均与堆叠效果对比\n\"\"\"\ndf_train = pd.read_csv('./data/train.csv')\nprint(df_train.columns)\n\"\"\"\n•MSSubClass:建筑类 \n•mszoning:一般的分区分类\n•LotFrontage:街道连接属性线性英尺\n•LotArea:平方英尺批量\n•街道:道路通行方式\n•小巷:通道入口的类型\n•LotShape:财产的形状\n•LandContour:财产的平整度\n•实用程序:可用的实用程序类型\n•LotConfig:很多配置\n•LandSlope:坡的财产\n•邻近:Ames市区范围内的物理位置\n•状态:邻近主要道路或铁路\n•条件:靠近主要道路或铁路(如果第二存在)\n•BldgType:住宅类型\n•housestyle:风格的住宅\n•overallqual:整体材料和完成质量\n•overallcond:总体状况评价\n•yearbuilt:原施工日期\n•yearremodadd:重塑日期\n•RoofStyle:屋顶类型\n•RoofMatl:屋面材料\n•exterior1st:外部覆盖的房子\n•exterior2nd:外部覆盖的房子(如果有一个以上的材料)\n•MasVnrType:砌体饰面型\n•masvnrarea:砌体饰面面积平方英尺\n•exterqual:外部材料质量\n•extercond:在外部的物质条件\n•基金会:基金会的类型\n•BsmtQual:地下室的高度\n•bsmtcond:地下室的一般条件\n•BsmtExposure:罢工或花园层地下室墙\n•bsmtfintype1:质量基底成品区\n•bsmtfinsf1:型完成1平方英尺\n•bsmtfintype2:质量第二成品区(如果有的话)\n•bsmtfinsf2:型完成2平方英尺\n•BsmtUnfSF:未完成的平方英尺的地下室\n•totalbsmtsf:地下室面积总平方英尺\n•加热:加热类型\n•heatingqc:加热质量和条件\n•中央:中央空调\n•电气:电气系统\n•1stflrsf:一楼平方英尺\n•2ndflrsf:二楼平方英尺\n•lowqualfinsf:完成平方英尺Low质量(各楼层)\n•grlivarea:以上等级(地)居住面积平方英尺\n•BsmtFullBath: Basement full bathrooms\n•BsmtHalfBath:地下室半浴室\n•FullBath:完整的浴室级以上\n•HalfBath:半浴室级以上\n•卧室:高于地下室的卧室数\n•厨房:厨房数量\n•kitchenqual:厨房的品质\n•totrmsabvgrd:房间总级以上(不包括卫生间)\n•功能:家庭功能评级\n•一些壁炉壁炉:\n•fireplacequ:壁炉质量\n•GarageType:车库位置\n•GarageYrBlt:建立年车库\n•GarageFinish:车库的室内装修\n•GarageCars:在汽车车库大小的能力\n•GarageArea:在平方英尺的车库规模\n•GarageQual:车库质量\n•garagecond:车库条件\n•paveddrive:铺的车道\n•WoodDeckSF:平方英尺的木甲板面积\n•openporchsf:平方英尺打开阳台的面积\n•enclosedporch:封闭式阳台的面积以平方英尺\n•3ssnporch:平方英尺三季阳台的面积\n•screenporch:平方英尺纱窗门廊区\n•PoolArea:在平方英尺的游泳池\n•poolqc:池质量\n•栅栏:栅栏的质量\n•miscfeature:杂项功能在其他类未包括\n•miscval:$杂特征值\n•MoSold:月销售\n•YrSold:年销售\n•SaleType:销售类型\n•salecondition:销售条件\n\"\"\"\nprint(df_train['SalePrice'].describe())\n\n# 首先来看一下,我们的目标满足正态分布嘛?\nsns.distplot(df_train['SalePrice'])\n# plt.show()\n\"\"\"\n看起来还可以,我们来观察一下它的偏度值\n\"\"\"\n#skewness and kurtosis\nprint(\"Skewness: %f\" % df_train['SalePrice'].skew())\nprint(\"Kurtosis: %f\" % df_train['SalePrice'].kurt())\n\n\"\"\"\n看起来偏度比较大,我们发现了一条大尾巴,一会咱们把解决掉它。\n接下来再看看一些比较重要的属性对结果的影响\n\"\"\"\n#居住面积平方英尺\nvar = 'GrLivArea'\ndata = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000))\nplt.show()\n\"\"\"\n越大的面积,房价肯定也越贵嘛,但是这里出现了一些离群点。是不是得干掉他们!\n\"\"\"\n\n#地下室面积平方英尺\nvar = 'TotalBsmtSF'\ndata = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000))\nplt.show()\n\n\"\"\"\n离散型变量,我们用boxplot来表示\n\"\"\"\n#整体材料和饰面质量\nvar = 'OverallQual'\ndata = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000)\n\n#原施工日期\nvar = 'YearBuilt'\ndata = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 8))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);\nplt.xticks(rotation=90);\n\nvar = 'Neighborhood'\ndata = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\n#fig.axis(ymin=0, ymax=800000)\nplt.xticks(rotation=90)\n\n\"\"\"\n来看看特征之间的相关性吧,看看哪些和价格最相关\n\"\"\"\n#correlation matrix\ncorrmat = df_train.corr()\nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corrmat, square=True,cmap='YlGnBu');\nplt.show()\n\nk = 10 #number of variables for heatmap\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\ncm = np.corrcoef(df_train[cols].values.T)\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values,cmap='YlGnBu')\nplt.show()\n\n#scatterplot\nsns.set()\ncols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\nsns.pairplot(df_train[cols], size = 2.5)\nplt.show()\n\n\"\"\"\n最后再来看一下 缺失值的情况,看起来还蛮多的。。。头疼。。。\n\"\"\"\n#missing data\ntotal = df_train.isnull().sum().sort_values(ascending=False)\npercent = (df_train.isnull().sum()/df_train.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nprint(missing_data.head(20))\n\nimport pandas as pd\n\ntrain = pd.read_csv('./data/train.csv')\ntest = pd.read_csv('./data/test.csv')\n\n#看看数据多大的\nprint(\"The train data size before dropping Id feature is : {} \".format(train.shape))\nprint(\"The test data size before dropping Id feature is : {} \".format(test.shape))\n\n#ID先留着,暂时不用\ntrain_ID = train['Id']\ntest_ID = test['Id']\n\n#去掉ID\ntrain.drop(\"Id\", axis = 1, inplace = True)\ntest.drop(\"Id\", axis = 1, inplace = True)\n\n#看一下现在的数据的shape\nprint(\"\\nThe train data size after dropping Id feature is : {} \".format(train.shape))\nprint(\"The test data size after dropping Id feature is : {} \".format(test.shape))\n\n\n#发现离群点\nfig, ax = plt.subplots()\nax.scatter(x = train['GrLivArea'], y = train['SalePrice'])\nplt.ylabel('SalePrice', fontsize=13)\nplt.xlabel('GrLivArea', fontsize=13)\nplt.show()\n\n#干掉离群点\ntrain = train.drop(train[(train['GrLivArea']>4000) & (train['SalePrice']<300000)].index)\n\n#Check the graphic again\nfig, ax = plt.subplots()\nax.scatter(train['GrLivArea'], train['SalePrice'])\nplt.ylabel('SalePrice', fontsize=13)\nplt.xlabel('GrLivArea', fontsize=13)\nplt.show()\n\n\"\"\"\n样本正太分布变换\n\"\"\"\nsns.distplot(train['SalePrice'] , fit=norm);\n\n(mu, sigma) = norm.fit(train['SalePrice'])\nprint( '\\n mu = {:.2f} and sigma = {:.2f}\\n'.format(mu, sigma))\n\n#分布图\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best')\nplt.ylabel('Frequency')\nplt.title('SalePrice distribution')\n\n#QQ图\nfig = plt.figure()\nres = stats.probplot(train['SalePrice'], plot=plt)\nplt.show()\n\n#对数变换log(1+x)\ntrain[\"SalePrice\"] = np.log1p(train[\"SalePrice\"])\n\n#看看新的分布\nsns.distplot(train['SalePrice'] , fit=norm);\n\n# 参数\n(mu, sigma) = norm.fit(train['SalePrice'])\nprint( '\\n mu = {:.2f} and sigma = {:.2f}\\n'.format(mu, sigma))\n\n#画图\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n loc='best')\nplt.ylabel('Frequency')\nplt.title('SalePrice distribution')\n\n#QQ图\nfig = plt.figure()\nres = stats.probplot(train['SalePrice'], plot=plt)\nplt.show()\n\nntrain = train.shape[0]\nntest = test.shape[0]\ny_train = train.SalePrice.values\nall_data = pd.concat((train, test)).reset_index(drop=True)\nall_data.drop(['SalePrice'], axis=1, inplace=True)\nprint(\"all_data size is : {}\".format(all_data.shape))\n\n\"\"\"\n缺失值得来处理了\n\"\"\"\nall_data_na = (all_data.isnull().sum() / len(all_data)) * 100\nall_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index).sort_values(ascending=False)[:30]\nmissing_data = pd.DataFrame({'Missing Ratio' :all_data_na})\nmissing_data.head(20)\n\nf, ax = plt.subplots(figsize=(15, 12))\nplt.xticks(rotation='90')\nsns.barplot(x=all_data_na.index, y=all_data_na)\nplt.xlabel('Features', fontsize=15)\nplt.ylabel('Percent of missing values', fontsize=15)\nplt.title('Percent missing data by feature', fontsize=15)\n\nall_data[\"PoolQC\"][:5]\n\n#游泳池?上流社会?\nall_data[\"PoolQC\"] = all_data[\"PoolQC\"].fillna(\"None\")\n\nall_data[\"PoolQC\"][:5]\n\n#没有特征。。。\nall_data[\"MiscFeature\"] = all_data[\"MiscFeature\"].fillna(\"None\")\n\n#通道的入口\nall_data[\"Alley\"] = all_data[\"Alley\"].fillna(\"None\")\n\n#栅栏\nall_data[\"Fence\"] = all_data[\"Fence\"].fillna(\"None\")\n\n#壁炉\nall_data[\"FireplaceQu\"] = all_data[\"FireplaceQu\"].fillna(\"None\")\n\n#到街道的距离\nall_data[\"LotFrontage\"] = all_data.groupby(\"Neighborhood\")[\"LotFrontage\"].transform(\n lambda x: x.fillna(x.median()))\n\n#车库的事\nfor col in ('GarageType', 'GarageFinish', 'GarageQual', 'GarageCond'):\n all_data[col] = all_data[col].fillna('None')\n\nfor col in ('GarageYrBlt', 'GarageArea', 'GarageCars'):\n all_data[col] = all_data[col].fillna(0)\n\n#地下室的事\nfor col in ('BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath'):\n all_data[col] = all_data[col].fillna(0)\n\nfor col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):\n all_data[col] = all_data[col].fillna('None')\n\n#砌体\nall_data[\"MasVnrType\"] = all_data[\"MasVnrType\"].fillna(\"None\")\nall_data[\"MasVnrArea\"] = all_data[\"MasVnrArea\"].fillna(0)\nprint(all_data['MSZoning'].mode())\n\n#一般分区分类,用众数来吧\nall_data['MSZoning'] = all_data['MSZoning'].fillna(all_data['MSZoning'].mode()[0])\n\n#Functional家庭功能评定\nall_data[\"Functional\"] = all_data[\"Functional\"].fillna(\"Typ\")\n\n#电力系统\nall_data['Electrical'] = all_data['Electrical'].fillna(all_data['Electrical'].mode()[0])\n\n#厨房的品质\nall_data['KitchenQual'] = all_data['KitchenQual'].fillna(all_data['KitchenQual'].mode()[0])\n\n#外部\nall_data['Exterior1st'] = all_data['Exterior1st'].fillna(all_data['Exterior1st'].mode()[0])\nall_data['Exterior2nd'] = all_data['Exterior2nd'].fillna(all_data['Exterior2nd'].mode()[0])\n\n#销售类型\nall_data['SaleType'] = all_data['SaleType'].fillna(all_data['SaleType'].mode()[0])\n\n#建筑类型\nall_data['MSSubClass'] = all_data['MSSubClass'].fillna(\"None\")\n\nall_data = all_data.drop(['Utilities'], axis=1)\n\nall_data_na = (all_data.isnull().sum() / len(all_data)) * 100\nall_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index).sort_values(ascending=False)\nmissing_data = pd.DataFrame({'Missing Ratio' :all_data_na})\nprint(missing_data.head())\n\n#有些并不是连续值,给他们做成类别值吧\nall_data['MSSubClass'] = all_data['MSSubClass'].apply(str)\n\nall_data['OverallCond'] = all_data['OverallCond'].astype(str)\n\nall_data['YrSold'] = all_data['YrSold'].astype(str)\nall_data['MoSold'] = all_data['MoSold'].astype(str)\n\n\"\"\"\n使用sklearn进行标签映射\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\ncols = ('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond',\n 'ExterQual', 'ExterCond','HeatingQC', 'PoolQC', 'KitchenQual', 'BsmtFinType1',\n 'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope',\n 'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond',\n 'YrSold', 'MoSold')\n# process columns, apply LabelEncoder to categorical features\nfor c in cols:\n lbl = LabelEncoder()\n lbl.fit(list(all_data[c].values))\n all_data[c] = lbl.transform(list(all_data[c].values))\n\n# shape\nprint('Shape all_data: {}'.format(all_data.shape))\n\n#增加一个新特征总面积\nall_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']\n\n\"\"\"\n对于咱的这些特征是不是也得变换下呀\n\"\"\"\nfrom scipy.stats import norm, skew\n\nnumeric_feats = all_data.dtypes[all_data.dtypes != \"object\"].index\n\n# Check the skew of all numerical features\nskewed_feats = all_data[numeric_feats].apply(lambda x: skew(x.dropna())).sort_values(ascending=False)\nprint(\"\\nSkew in numerical features: \\n\")\nskewness = pd.DataFrame({'Skew' :skewed_feats})\nprint(skewness.head(10))\n\n\"\"\"\nBox-Cox变换\nBox-Cox 变换在上世纪六十年代由两位英国统计学家 George E.P. Box 和 David Cox 提出\n假设样本里一共有 n 个数据点,分别是y1 y2...yn,找到一个合适的函数使得数据点经过变换\n之后能整体的正太型能够最好\n关键点在于如何找到一个合适的参数,一般情况下0.15为经验值\n\"\"\"\nskewness = skewness[abs(skewness) > 0.75]\nprint(\"There are {} skewed numerical features to Box Cox transform\".format(skewness.shape[0]))\n\nfrom scipy.special import boxcox1p\nskewed_features = skewness.index\nlam = 0.15\nfor feat in skewed_features:\n all_data[feat] = boxcox1p(all_data[feat], lam)\n\nall_data = pd.get_dummies(all_data)\nprint(all_data.shape)\n\ntrain = all_data[:ntrain]\ntest = all_data[ntrain:]\n\nfrom sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport xgboost as xgb\n\nn_folds = 5\ndef rmsle_cv(model):\n kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(train.values)\n rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring=\"neg_mean_squared_error\", cv = kf))\n return(rmse)\n\n# make_pipeline:级联起来去做事 RobustScaler:更适合处理离群点\nlasso = make_pipeline(RobustScaler(), Lasso(alpha =0.0005, random_state=1))\n# ElasticNet同时使用l1和l2\n\nENet = make_pipeline(RobustScaler(), ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3))\n\n# KernelRidge带有核函数的岭回归\n#KRR = KernelRidge(alpha=0.6, kernel='rbf')\n#http://blog.csdn.net/wsj998689aa/article/details/47027365 核函数介绍\nKRR = KernelRidge(alpha=0.6, kernel='polynomial', degree=2, coef0=2.5)\n\nGBoost = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,\n max_depth=4, max_features='sqrt',\n min_samples_leaf=15, min_samples_split=10,\n loss='huber', random_state =5)\n\nmodel_xgb = xgb.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468,\n learning_rate=0.05, max_depth=3,\n min_child_weight=1.7817, n_estimators=2200,\n reg_alpha=0.4640, reg_lambda=0.8571,\n subsample=0.5213, silent=1,\n nthread = -1)\n\nscore = rmsle_cv(lasso)\nprint(\"\\nLasso score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(ENet)\nprint(\"ElasticNet score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(KRR)\nprint(\"Kernel Ridge score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(GBoost)\nprint(\"Gradient Boosting score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(model_xgb)\nprint(\"Xgboost score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\n\nclass AveragingModels(BaseEstimator, RegressorMixin, TransformerMixin):\n def __init__(self, models):\n self.models = models\n\n # we define clones of the original models to fit the data in\n def fit(self, X, y):\n self.models_ = [clone(x) for x in self.models]\n\n # Train cloned base models\n for model in self.models_:\n model.fit(X, y)\n\n return self\n\n # Now we do the predictions for cloned models and average them\n def predict(self, X):\n predictions = np.column_stack([\n model.predict(X) for model in self.models_\n ])\n return np.mean(predictions, axis=1)\n\naveraged_models = AveragingModels(models = (ENet, GBoost, KRR, lasso))\n\nscore = rmsle_cv(averaged_models)\nprint(\" Averaged base models score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\n\nclass StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin):\n def __init__(self, base_models, meta_model, n_folds=5):\n self.base_models = base_models\n self.meta_model = meta_model\n self.n_folds = n_folds\n\n # We again fit the data on clones of the original models\n def fit(self, X, y):\n self.base_models_ = [list() for x in self.base_models]\n self.meta_model_ = clone(self.meta_model)\n kfold = KFold(n_splits=self.n_folds, shuffle=True, random_state=156)\n\n # Train cloned base models then create out-of-fold predictions\n # that are needed to train the cloned meta-model\n out_of_fold_predictions = np.zeros((X.shape[0], len(self.base_models)))\n for i, model in enumerate(self.base_models):\n for train_index, holdout_index in kfold.split(X, y):\n instance = clone(model)\n self.base_models_[i].append(instance)\n instance.fit(X[train_index], y[train_index])\n y_pred = instance.predict(X[holdout_index])\n out_of_fold_predictions[holdout_index, i] = y_pred\n\n # Now train the cloned meta-model using the out-of-fold predictions as new feature\n self.meta_model_.fit(out_of_fold_predictions, y)\n return self\n\n # Do the predictions of all base models on the test data and use the averaged predictions as\n # meta-features for the final prediction which is done by the meta-model\n def predict(self, X):\n meta_features = np.column_stack([\n np.column_stack([model.predict(X) for model in base_models]).mean(axis=1)\n for base_models in self.base_models_])\n return self.meta_model_.predict(meta_features)\n\nstacked_averaged_models = StackingAveragedModels(base_models = (ENet, GBoost, KRR),\n meta_model = lasso)\n\nscore = rmsle_cv(stacked_averaged_models)\nprint(\"Stacking Averaged models score: {:.4f} ({:.4f})\".format(score.mean(), score.std()))\n" }, { "alpha_fraction": 0.6104088425636292, "alphanum_fraction": 0.6594943404197693, "avg_line_length": 29.231706619262695, "blob_id": "eff6dc6678ff11e7b85020d3391e51e3f74410ce", "content_id": "5d49d809ae2d6d5473473c08a6caf8a6d914d12e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9862, "license_type": "no_license", "max_line_length": 88, "num_lines": 246, "path": "/ss_03_pandas练习.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "import string\nimport pandas as pd\nimport numpy as np\n\n\n# 1. Series练习\n# 1.1 series创建 Series 一维,带标签数组\n# series对象本质有两个数组构成,一个数组构成对象的键(index,索引),一个数组构成对象的值(values)\na = pd.Series(np.arange(10), index=list(string.ascii_uppercase[:10]))\nprint(\"创建的t为:\\n\", a)\nprint(\"查看t的数据类型:\", type(a))\n\n# 1.2字典创建series,其中字典的键就是series的索引\na = {string.ascii_uppercase[i]: i for i in range(10)}\nb = pd.Series(a)\nprint(\"一维Series ,b为:\\n\", b)\n# 对b的索引进行重新赋值\nc = pd.Series(b, index=list(string.ascii_uppercase[5:15]))\nprint(\"一维Series ,c为:\\n\", c)\n\n# 1.3 Series切片操作\nt = pd.Series(np.arange(10), index=list(string.ascii_uppercase[:10]))\nprint(\"从第3个元素开始,到第10个元素,步长是2,t为:\", t[2:10:2])\nprint(\"取第2个元素\", t[1])\nprint(\"取第3个、第4个、第6个元素\", t[[2, 3, 5]])\nprint(\"取出t列表中,值大于4的列表:\\n\", t[t > 4])\n# 1.4 series的索引和值\nprint(\"取series的索引:\", t.index)\nprint(\"取series的值:\", t.values)\n\n# 2. DataFrame练习\n# DataFrame既有行索引也有列索引,行索引叫index,列索引叫columns\n# 2.1 DataFrame创建\ndf = pd.DataFrame(np.arange(12).reshape((3, 4)))\nprint(\"DataFrame创建:\", df)\n\n# 2.2创建自定义行索引和列索引的DataFrame\ndf2 = pd.DataFrame(np.arange((12)).reshape(3, 4), index=list(string.ascii_uppercase[:3])\n , columns=list(string.ascii_uppercase[-4:]))\nprint(\"创建自定义行索引和列索引的DataFrame:\", df2)\n\n# 2.3 DataFrame属性练习\nprint(\"DataFrame的行数和列数:\", df2.shape)\nprint(\"DataFrame列的数据类型:\\n\", df2.dtypes)\nprint(\"DataFrame数据的为维度:\", df2.ndim)\nprint(\"DataFrame行索引:\", df2.index)\nprint(\"DataFrame列索引:\", df2.columns)\nprint(\"DataFrame的对象值:\\n\", df2.values)\nprint(\"DataFrame取头几行,默认前5行:\\n\", df2.head(2))\nprint(\"DataFrame显示尾几行,默认5行:\\n\", df2.tail(2))\n# print(\"DataFrame详细信息:\",df.info())\nprint(\"DataFrame快速查看统计结果,\"\n \"计数、均值、标准差、最大值等:\\n\", df2.describe())\n\n# 2.4 pandas读取外部数据\ndog_df = pd.read_csv(\"../data/dogNames2.csv\")\nprint(dog_df[(800 < dog_df[\"Count_AnimalName\"])\n | (dog_df[\"Count_AnimalName\"] < 1000)])\n\n# 2.5 DataFrame排序\ndog_sorted_df = dog_df\\\n .sort_values(by=\"Count_AnimalName\", ascending=False)\nprint(\"前10个最受欢迎的名字:\", dog_sorted_df.head(10))\nprint(\"前20个名字最受欢迎的名字:\", dog_sorted_df[:20])\nprint(\"Count_AnimalName这一列的前20:\",\n dog_sorted_df[:20][\"Count_AnimalName\"])\n\n# 2.6 pandas loc()通过标签获取行数据\nprint(df2)\n# 冒号在loc里面是闭合的\nprint(\"获取df2中A行W列的数据:\",\n df2.loc[\"A\", \"W\"])\nprint(\"获取df2中A行且 W列、Z列的数据:\",\n df2.loc[\"A\", [\"W\", \"Z\"]])\nprint(\"获取df2中A行、C行 且 W列、Z列的数据:\",\n df2.loc[[\"A\", \"C\"], [\"W\", \"Z\"]])\nprint(\"获取df2中A行以后,且W列、Z列的数据:\",\n df2.loc[\"A\":, [\"W\", \"Z\"]])\nprint(\"获取df2中A行到C行,且W列、Z列的数据:\",\n df2.loc[\"A\":\"C\", [\"W\", \"Z\"]])\n\n# 2.7 panddas iloc()通过位置获取行数据\nprint(df2)\nprint(\"获取df2中第2、3行且第3、4列的数据:\\n\", df2.iloc[1:3, [2, 3]])\nprint(\"获取df2中第2、3行且第2、3列的数据:\\n\", df2.iloc[1:3, 1:3])\n\ndf2.loc[\"A\", \"Y\"] = 100\ndf2.iloc[1:2, 0:2] = 200\nprint(\"赋值更改数据:\\n\", df2)\n\n# 2.8 pandas之布尔索引\nprint(\"使用次数超过800的狗的名字:\\n\",\n dog_df[dog_df[\"Count_AnimalName\"] > 800])\n#\nprint(\"使用次数超过700并且名字的字符串的长度大于4的狗的名字:\\n\",\n dog_df[(dog_df[\"Row_Labels\"].str.len() > 4)\n & (dog_df[\"Count_AnimalName\"] > 700)])\n\n# 3.pandas 缺失值处理\ndf3 = pd.DataFrame(np.arange(12).reshape(3, 4))\n# 人为创造NaN缺失值\ndf3.iloc[0, 1] = np.nan\ndf3.iloc[1, 1] = np.nan\ndf3.iloc[2, 2] = np.nan\nprint(\"判断是否为NaN:\", pd.isnull(df3))\nprint(\"判断是否为NaN:\", pd.notnull(df3))\n# 处理1:填充数据\ndf4 = df3.fillna(df3.mean())\nprint(\"填充平均值数据\", df4)\n# 处理2:删除NaN所在的行列\ndf3.iloc[2, 2] = 4\nprint(df3)\ndf5 = df3.dropna(axis=0, how=\"any\", inplace=False)\nprint(\"删除NaN所在的行列:\", df5)\n\n# 4.pandas常用统计方法\n\"\"\"\n假设现在我们有一组从2006年到2016年1000部最流行的电影数据,\n我们想知道这些电影数据中评分的平均分,导演的人数等信息,我们应该怎么获取\n\"\"\"\nmovie_df = pd.read_csv(\"../data/IMDB-Movie-Data.csv\")\nprint(df.head())\nprint(df.columns)\nprint(\"电影平均分为:\", movie_df[\"Rating\"].mean())\nprint(\"电影时长最大最小值:\",\n movie_df[\"Runtime (Minutes)\"].max(),\n movie_df[\"Runtime (Minutes)\"].min())\n\n# 5.pandas 数据合并\n# 5.1 join:默认情况下他是把行索引相同的数据合并到一起\n# 创建3行4列,数值都为1的DataFrame,\n# 行索引为英文字母前3个,列索引为默认值\nt1 = pd.DataFrame(np.ones(shape=(3, 4)),\n index=list(string.ascii_uppercase[:3]))\n# 创建2行5列的,数值都为0的DataFrame。\n# 行索引为正数前2个英文字母,列索引为倒数后五个英文字母\nt2 = pd.DataFrame(np.zeros(shape=(2, 5)),\n index=list(string.ascii_uppercase[:2]),\n columns=list(string.ascii_uppercase[-5:]))\nprint(\"t1 join t2的值为:\\n\",t1.join(t2))\n\n#5.2 merge按照指定的列把数据按照一定的方式\n# 合并到一起,默认的合并方式inner,交集\n# merge outer,并集,NaN补全\n# merge left,左边为准,NaN补全\n# merge right,右边为准,NaN补全\nt3 = pd.DataFrame([[1,1,\"a\",1],[1,1,\"b\",1],[1,1,\"c\",1]],\n index=[\"A\",\"B\",\"C\"],columns=[\"M\",\"N\",\"O\",\"P\"])\nprint(\"t3:\\n\",t3)\nt4 = pd.DataFrame([[0,0,\"c\",0,0],[0,0,\"d\",0,0]],\n index=[\"A\",\"B\"],columns=[\"V\",\"W\",\"X\",\"Y\",\"Z\"])\nprint(\"t4:\\n\",t4)\nprint(\"t3.merge(t4)的结果为:\\n\",t3.merge(t4,left_on=\"O\",right_on=\"X\"))\nprint(\"t3.merge(t4),how='inner'的结果为:\\n\",\n t3.merge(t4,left_on=\"O\",right_on=\"X\",how=\"inner\"))\nprint(\"t3.merge(t4),how='outer'的的结果为:\\n\",\n t3.merge(t4,left_on=\"O\",right_on=\"X\",how=\"outer\"))\nprint(\"t3.merge(t4),how='left'的的结果为:\\n\",\n t3.merge(t4,left_on=\"O\",right_on=\"X\",how=\"left\"))\nprint(\"t3.merge(t4),how='right'的的结果为:\\n\",\n t3.merge(t4,left_on=\"O\",right_on=\"X\",how=\"right\"))\n\n#6 pandas 分组和聚合\n\"\"\"\n现在我们有一组关于全球星巴克店铺的统计数据,如果\n我想知道美国的星巴克数量和中国的哪个多,或者我想\n知道中国每个省份星巴克的数量的情况,那么应该怎么办?\n语法:\ngrouped = df.groupby(by=\"columns_name\") grouped是一个DataFrameGroupBy对象,是可迭代的。\n\"\"\"\nstarbucks_df = pd.read_csv(\"../data/starbucks_store_worldwide.csv\")\n#6.1统计中美两国星巴克店铺的数量\ngrouped = starbucks_df.groupby(by=\"Country\")\ncountry_count = grouped[\"Brand\"].count()\nprint(\"美国星巴克店铺数量:\",country_count[\"US\"])\nprint(\"中国星巴克店铺数量:\",country_count[\"CN\"])\n\n#6.2统计中国每个省店铺的数量\nchina_data = starbucks_df[starbucks_df[\"Country\"]==\"CN\"]\ngrouped = china_data.groupby(by=\"State/Province\").count()[\"Brand\"]\nprint(grouped)\n\n# 6.3统计每个国家每个省店铺的数量,数据按照多个条件进行分组,返回Series\ngrouped = starbucks_df.groupby(\n by=[starbucks_df[\"Country\"],\n starbucks_df[\"State/Province\"]]).count()[\"Brand\"]\nprint(grouped)\n\n#7 pandas 时间序列\n\"\"\"\n语法:\npd.date_range(start=None, end=None, periods=None, freq='D')\nstart和end以及freq配合能够生成start和end范围内以频率freq的一组时间索引\nstart和periods以及freq配合能够生成从start开始的频率为freq的periods个时间索引\n\"\"\"\nday_time = pd.date_range(start='20200307',end='20200418',freq=\"D\")\nprint(\"生成一段时间内的每天日期:\\n\",day_time)\nmonth_time = pd.date_range(start='20200307',end='20200918',freq=\"M\")\nprint(\"生成一段时间内的每月最后一个日历日:\\n\",month_time)\nindex = pd.date_range(\"20200307\",periods=10)\nprint(\"periods默认按天生成日期:\\n\",index)\n#时间序列应用于DataFrame\ndf = pd.DataFrame(np.random.rand(10),index=index)\nprint(\"时间序列应用于DataFrame:\",df)\n\n#8 空气质量问题\n\"\"\"\n现在我们有北上广、深圳、和沈阳5个城市空气质量数据,\n请绘制出5个城市的PM2.5随时间的变化情况观察这组数据\n中的时间结构,并不是字符串,这个时候我们应该怎么办?\n\"\"\"\nimport matplotlib.pyplot as plt\n\nfile_path = \"../data/BeijingPM20100101_20151231.csv\"\ndf =pd.read_csv(file_path)\n\n#把分开的时间字符串通过periodIndex的方法转化为pandas的时间类型\nperiod = pd.PeriodIndex(year=df[\"year\"],\n month=df[\"month\"],\n day=df[\"day\"],\n hour=df[\"hour\"],\n freq=\"H\")\ndf[\"datetime\"]=period\n#把datetime设置为索引\ndf.set_index(\"datetime\",inplace=True)\n\n#进行降维采样\ndf = df.resample(\"7D\").mean()\ndata =df[\"PM_US Post\"]\ndata_china = df[\"PM_Nongzhanguan\"]\n\n#画图\n_x = data.index\n_x = [i.strftime(\"%Y%m%d\") for i in _x]\n_x_china = [i.strftime(\"%Y%m%d\") for i in data_china.index]\nprint(len(_x_china),len(_x_china))\n_y = data.values\n_y_china = data_china.values\n\nplt.figure(figsize=(20,8),dpi=90)\nplt.plot(range(len(_x)),_y,label=\"US_POST\",alpha=0.7)\nplt.plot(range(len(_x_china)),_y_china,label=\"CN_POST\",alpha=0.8)\n\nplt.xticks(range(0,len(_x_china),10),list(_x_china)[::10],rotation=45)\nplt.legend(loc=\"best\")\nplt.show()" }, { "alpha_fraction": 0.6392002701759338, "alphanum_fraction": 0.6496516466140747, "avg_line_length": 29.279815673828125, "blob_id": "5942f0446a498b5a662790440e5c41a372c510ae", "content_id": "85430973846fb5c0db3e49959c00bcd11b2fa4e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8460, "license_type": "no_license", "max_line_length": 134, "num_lines": 218, "path": "/ss_07_回归算法.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\n\ndef linear_regression_boston():\n \"\"\"\n 线性回归\n 波士顿房价预测。包含13个特征,506条记录。\n 处理流程:\n 1.加载数据\n 2.数据分割\n 3.数据标准化\n 4.LinearRegression回归模型估计器预估房价\n :return:\n \"\"\"\n # 导包\n from sklearn.datasets import load_boston\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.linear_model import LinearRegression\n import matplotlib.pyplot as plt\n from matplotlib import rcParams\n from sklearn.externals import joblib\n from sklearn.metrics import mean_squared_error\n\n # 加载数据\n data_boston = load_boston()\n #分割数据\n # x_train训练集特征值,x_test测试集特征值,y_train训练集目标值,y_test测试集目标值\n x_train,x_test,y_train,y_test = train_test_split(data_boston[\"data\"],data_boston[\"target\"],test_size=0.25)\n # 特征工程-标准化处理。特征值和目标值都需要标准化\n # 特征值标准化\n standard_x = StandardScaler()\n x_train = standard_x.fit_transform(x_train)\n x_test = standard_x.transform(x_test)\n\n # 目标值标准化\n standard_y = StandardScaler()\n y_train = standard_y.fit_transform(y_train.reshape(-1,1))\n y_test = standard_y.transform(y_test.reshape(-1,1))\n\n #实例化估计器,估计房价\n lr_model = LinearRegression()\n #训练模型\n lr_model.fit(x_train,y_train)\n print(\"特征系数为:\\n\",lr_model.coef_)\n\n #房价预测\n print(\"预测的房价为:\\n\",standard_y.inverse_transform(lr_model.predict(x_test)))\n print(\"预测的分数为:\\n\",lr_model.score(x_test,y_test))\n print(\"均方误差为:\\n\", mean_squared_error(standard_y.inverse_transform(y_test),\n standard_y.inverse_transform(lr_model.predict(x_test))))\n\n #预测值和真实值的折线图\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n fig = plt.figure(figsize=(20,8))\n\n y_pred = lr_model.predict(x_test)\n plt.plot(range(y_test.shape[0]),y_test,color=\"blue\",linewidth=1.5,linestyle=\"-\")\n plt.plot(range(y_test.shape[0]),y_pred,color=\"red\",linewidth=1.5)\n plt.legend([\"真实值\",\"预测值\"])\n plt.show()\n\n # # 模型保存\n # joblib.dump(lr_model,\"./re.pkl\")\n #\n # # 测试保存的模型\n # model = joblib.load(\"./re.pkl\")\n # predict_result = standard_y.inverse_transform(model.predict(x_test))\n # print(predict_result)\n\n\ndef SGDRegressor_boston():\n \"\"\"\n 线性回归之梯度下降\n 波士顿房价预测。包含13个特征,506条记录。\n 处理流程:\n 1.加载数据\n 2.数据分割\n 3.数据标准化\n 4.LinearRegression回归模型估计器预估房价\n :return:\n \"\"\"\n #导包\n from sklearn.datasets import load_boston\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.linear_model import SGDRegressor\n import matplotlib.pyplot as plt\n from matplotlib import rcParams\n from sklearn.externals import joblib\n from sklearn.metrics import mean_squared_error\n\n #加载数据\n data_boston = load_boston()\n #分割数据,训练集和测试机\n x_train,x_test,y_train,y_test = train_test_split(data_boston[\"data\"],data_boston[\"target\"],test_size=0.25)\n\n #特征工程-标准化处理。\n standard_x = StandardScaler()\n x_train = standard_x.fit_transform(x_train)\n x_test = standard_x.transform(x_test)\n\n standard_y = StandardScaler()\n y_train = standard_y.fit_transform(y_train.reshape(-1,1))\n y_test = standard_y.transform(y_test.reshape(-1,1))\n\n #实例化估计器,估计房价\n sgd_model = SGDRegressor()\n #训练模型\n sgd_model.fit(x_train,y_train)\n print(\"特征系数为:\\n\",sgd_model.coef_)\n\n #预估房价\n print(\"预估的房价为:\\n\",standard_y.inverse_transform(sgd_model.predict(x_test))[:2])\n print(\"预测的分数为:\\n\",sgd_model.score(x_test,y_test))\n print(\"均方误差为:\\n\",mean_squared_error(standard_y.inverse_transform(y_test),\n standard_y.inverse_transform(sgd_model.predict(x_test))))\n\n #预测房价与真实房价的折线图\n rcParams[\"font.sans-serif\"] = \"SimHei\"\n fig = plt.figure(figsize=(20,8))\n\n y_pred = sgd_model.predict(x_test)\n #真实值\n plt.plot(range(y_test.shape[0]),y_test,color=\"blue\",linewidth=1.5,linestyle=\"-\")\n #预测值\n plt.plot(range(y_test.shape[0]),y_pred,color=\"red\",linewidth=1.5)\n plt.legend([\"真实值\",\"预测值\"])\n plt.show()\n\n #模型保存\n # joblib.dump(sgd_model,\"./sgd.pkl\")\n\n #测试保存的模型\n # model = joblib.load(\"./sgd.pkl\")\n # predict_result = standard_y.inverse_transform(model.predict(x_test))\n # print(predict_result)\n\ndef ridge():\n \"\"\"\n 岭回归\n 波士顿房价预测。包含13个特征,506条记录。\n :return:\n \"\"\"\n #导包\n from sklearn.datasets import load_boston\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import StandardScaler\n from sklearn.linear_model import Ridge\n from sklearn.metrics import mean_squared_error\n #加载数据\n boston = load_boston()\n #分割数据集,分割为训练集和测试机\n x_train,x_test,y_train,y_test = train_test_split(boston[\"data\"],boston[\"target\"],test_size=0.25)\n\n #标准化处理特征值和目标值\n standard_x = StandardScaler()\n x_train = standard_x.fit_transform(x_train)\n x_test= standard_x.transform(x_test)\n\n standard_y = StandardScaler()\n y_train = standard_y.fit_transform(y_train.reshape(-1,1))\n y_test = standard_y.transform(y_test.reshape(-1,1))\n\n #岭回归估计器模型训练\n ridge_model = Ridge(alpha=1.0)\n ridge_model.fit(x_train,y_train)\n\n #预测房价\n print(\"预测的房价为:\", standard_y.inverse_transform(ridge_model.predict(x_test))[:3])\n print(\"预测评分为:\",ridge_model.score(x_test,y_test))\n print(\"均方误差为:\",mean_squared_error(standard_y.inverse_transform(y_test),standard_y.inverse_transform(ridge_model.predict(x_test))))\n\n\n\n\n\n\nif __name__==\"__main__\":\n\n \"\"\"\n 回归算法1:线性回归(最小二乘回归)\n 概念:通过一个或者多个自变量与因变量之间进行建模的回归分析。 \n 如何判断拟合函数好坏?损失函数。通过最小化每个数据点到线的垂直偏差平方和来判断损失大小,进而确定损失函数。\n API:\n sklearn.linear_model.LinearRegression 最小二乘之正规方程\n 特征比较复杂时,求解速度慢。\n sklearn.linear_model.SGDRegressor 最小二乘之梯度下降\n 可以处理数据规模比较大的任务\n 回归评估:均方误差\n API:sklearn.metrics.mean_squared_error\n mean_squared_error(y_ture,y_perd),输入真实值与预测值\n 注意:如果使用了标准化,需要转换到原始的数据进行回归评估\n \"\"\"\n # linear_regression_boston()\n\n\n \"\"\"\n 回归算法2: 线性回归(梯度下降)\n 概念:通过一个或者多个自变量与因变量之间进行建模的回归分析。 \n 如何判断拟合函数好坏?损失函数。通过最小化每个数据点到线的垂直偏差平方和来判断损失大小,进而确定损失函数。\n API:\n sklearn.linear_model.LinearRegression 最小二乘之正规方程\n 特征比较复杂时,求解速度慢。\n sklearn.linear_model.SGDRegressor 最小二乘之梯度下降\n 可以处理数据规模比较大的任务\n 回归评估:均方误差\n API:sklearn.metrics.mean_squared_error\n mean_squared_error(y_ture,y_perd),输入真实值与预测值\n 注意:如果使用了标准化,需要转换到原始的数据进行回归评估\n \"\"\"\n # SGDRegressor_boston()\n\n \"\"\"\n 回归算法3:岭回归\n 概念:带有正则化的回归,解决线性回归过拟合问题\n API:sklearn.linear_model.Ridge \n 岭回归回归得到的回归系数更符合实际,更可靠。另外,能让估计参数的波动范围变小,\n 变的更稳定。在存在病态数据偏多的研究中有较大的实用价值。\n \"\"\"\n ridge()" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 17.5, "blob_id": "0287816b27873d4943c66354ffa8a6e64b4e142e", "content_id": "0df3724bd70f682ccf3d5b1ad588972117d1ce4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/a.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "\n\nprint(\"sdfsfd\\\"dsd\")\nprint('sdfs\"d')" }, { "alpha_fraction": 0.4896378517150879, "alphanum_fraction": 0.5063847899436951, "avg_line_length": 32.39860153198242, "blob_id": "33e84b4126ac3ccc8d6102e58e3c922a1dd1f713", "content_id": "b7899b68488c4b30385e8d9ec640e3958462a705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5721, "license_type": "no_license", "max_line_length": 113, "num_lines": 143, "path": "/商品零售购物篮分析/demo/code/03_Apriori.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# 代码8-6 构建关联规则模型\n\nfrom numpy import *\n \ndef loadDataSet():\n return [['a', 'c', 'e'], ['b', 'd'], ['b', 'c'], ['a', 'b', 'c', 'd'], ['a', 'b'], ['b', 'c'], ['a', 'b'],\n ['a', 'b', 'c', 'e'], ['a', 'b', 'c'], ['a', 'c', 'e']]\n \ndef createC1(dataSet):\n C1 = []\n for transaction in dataSet:\n for item in transaction:\n if not [item] in C1:\n C1.append([item])\n C1.sort()\n # 映射为frozenset唯一性的,可使用其构造字典\n return list(map(frozenset, C1)) \n \n# 从候选K项集到频繁K项集(支持度计算)\ndef scanD(D, Ck, minSupport):\n ssCnt = {}\n for tid in D: # 遍历数据集\n for can in Ck: # 遍历候选项\n if can.issubset(tid): # 判断候选项中是否含数据集的各项\n if not can in ssCnt:\n ssCnt[can] = 1 # 不含设为1\n else:\n ssCnt[can] += 1 # 有则计数加1\n numItems = float(len(D)) # 数据集大小\n retList = [] # L1初始化\n supportData = {} # 记录候选项中各个数据的支持度\n for key in ssCnt:\n support = ssCnt[key] / numItems # 计算支持度\n if support >= minSupport:\n retList.insert(0, key) # 满足条件加入L1中\n supportData[key] = support \n return retList, supportData\n \ndef calSupport(D, Ck, min_support):\n dict_sup = {}\n for i in D:\n for j in Ck:\n if j.issubset(i):\n if not j in dict_sup:\n dict_sup[j] = 1\n else:\n dict_sup[j] += 1\n sumCount = float(len(D))\n supportData = {}\n relist = []\n for i in dict_sup:\n temp_sup = dict_sup[i] / sumCount\n if temp_sup >= min_support:\n relist.append(i)\n# 此处可设置返回全部的支持度数据(或者频繁项集的支持度数据)\n supportData[i] = temp_sup\n return relist, supportData\n \n# 改进剪枝算法\ndef aprioriGen(Lk, k):\n retList = []\n lenLk = len(Lk)\n for i in range(lenLk):\n for j in range(i + 1, lenLk): # 两两组合遍历\n L1 = list(Lk[i])[:k - 2]\n L2 = list(Lk[j])[:k - 2]\n L1.sort()\n L2.sort()\n if L1 == L2: # 前k-1项相等,则可相乘,这样可防止重复项出现\n # 进行剪枝(a1为k项集中的一个元素,b为它的所有k-1项子集)\n a = Lk[i] | Lk[j] # a为frozenset()集合\n a1 = list(a)\n b = []\n # 遍历取出每一个元素,转换为set,依次从a1中剔除该元素,并加入到b中\n for q in range(len(a1)):\n t = [a1[q]]\n tt = frozenset(set(a1) - set(t))\n b.append(tt)\n t = 0\n for w in b:\n # 当b(即所有k-1项子集)都是Lk(频繁的)的子集,则保留,否则删除。\n if w in Lk:\n t += 1\n if t == len(b):\n retList.append(b[0] | b[1])\n return retList\n\ndef apriori(dataSet, minSupport=0.2):\n# 前3条语句是对计算查找单个元素中的频繁项集\n C1 = createC1(dataSet)\n D = list(map(set, dataSet)) # 使用list()转换为列表\n L1, supportData = calSupport(D, C1, minSupport)\n L = [L1] # 加列表框,使得1项集为一个单独元素\n k = 2\n while (len(L[k - 2]) > 0): # 是否还有候选集\n Ck = aprioriGen(L[k - 2], k)\n Lk, supK = scanD(D, Ck, minSupport) # scan DB to get Lk\n supportData.update(supK) # 把supk的键值对添加到supportData里\n L.append(Lk) # L最后一个值为空集\n k += 1\n del L[-1] # 删除最后一个空集\n return L, supportData # L为频繁项集,为一个列表,1,2,3项集分别为一个元素\n\n# 生成集合的所有子集\ndef getSubset(fromList, toList):\n for i in range(len(fromList)):\n t = [fromList[i]]\n tt = frozenset(set(fromList) - set(t))\n if not tt in toList:\n toList.append(tt)\n tt = list(tt)\n if len(tt) > 1:\n getSubset(tt, toList)\n \ndef calcConf(freqSet, H, supportData, ruleList, minConf=0.7):\n for conseq in H: #遍历H中的所有项集并计算它们的可信度值\n conf = supportData[freqSet] / supportData[freqSet - conseq] # 可信度计算,结合支持度数据\n # 提升度lift计算lift = p(a & b) / p(a)*p(b)\n lift = supportData[freqSet] / (supportData[conseq] * supportData[freqSet - conseq])\n \n if conf >= minConf and lift > 1:\n print(freqSet - conseq, '-->', conseq, '支持度', round(supportData[freqSet], 6), '置信度:', round(conf, 6),\n 'lift值为:', round(lift, 6))\n ruleList.append((freqSet - conseq, conseq, conf))\n \n# 生成规则\ndef gen_rule(L, supportData, minConf = 0.7):\n bigRuleList = []\n for i in range(1, len(L)): # 从二项集开始计算\n for freqSet in L[i]: # freqSet为所有的k项集\n # 求该三项集的所有非空子集,1项集,2项集,直到k-1项集,用H1表示,为list类型,里面为frozenset类型,\n H1 = list(freqSet)\n all_subset = []\n getSubset(H1, all_subset) # 生成所有的子集\n calcConf(freqSet, all_subset, supportData, bigRuleList, minConf)\n return bigRuleList\n \nif __name__ == '__main__':\n dataSet = data_translation\n L, supportData = apriori(dataSet, minSupport = 0.02)\n rule = gen_rule(L, supportData, minConf = 0.35)\n\n" }, { "alpha_fraction": 0.6477272510528564, "alphanum_fraction": 0.6534090638160706, "avg_line_length": 24.14285659790039, "blob_id": "a58494a76d8fe88920bb029bc272a51e2c435646", "content_id": "dfac4ec8e6d234cc49d7ba871cff43a1573cc021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/商品零售购物篮分析/test/02_data_clean.py", "repo_name": "hanjie1992/python_machine_learning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\ninputfile='../data/GoodsOrder.csv'\ndata = pd.read_csv(inputfile,encoding = 'gbk')\n\n# 根据id对“Goods”列合并,并使用“,”将各商品隔开\ndata['Goods'] = data['Goods'].apply(lambda x:','+x)\ndata = data.groupby('id').sum().reset_index()\n\n# 对合并的商品列转换数据格式\ndata['Goods'] = data['Goods'].apply(lambda x :[x[1:]])\ndata_list = list(data['Goods'])\n\n# 分割商品名为每个元素\ndata_translation = []\nfor i in data_list:\n p = i[0].split(',')\n data_translation.append(p)\nprint('数据转换结果:\\n', data_translation)\n" } ]
31
rohitnair11/Dijkstra-Shortest-Path
https://github.com/rohitnair11/Dijkstra-Shortest-Path
cff286357047c5e7fd80e21949c8b1966863c10b
160684bf9f15a632b6bd7816b69fba25fecee5ff
d962b91f6dffc179036febb132d52dd0fd7d5f7d
refs/heads/master
2020-12-15T02:54:08.093156
2020-01-19T22:11:56
2020-01-19T22:11:56
234,971,903
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.813829779624939, "alphanum_fraction": 0.813829779624939, "avg_line_length": 93, "blob_id": "48ffe3b77838c4cdcaa3b13d127f494155d9db08", "content_id": "5dc066f2ab1fb123050ea2c039aec40a45666933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 188, "license_type": "no_license", "max_line_length": 144, "num_lines": 2, "path": "/README.md", "repo_name": "rohitnair11/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "# Dijkstra's Shortest Path First algorithm\nThis algorithm is a modification of Dijkstra's SPF to check if there exists a unique shortest path from the source vertex to every other vertex.\n" }, { "alpha_fraction": 0.4763757586479187, "alphanum_fraction": 0.48693719506263733, "avg_line_length": 29.30434799194336, "blob_id": "3ecf8e95136d8f69c91981783cb109f740932570", "content_id": "1bff25fb86309eb00d83e37641b2ff93efc944db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3598, "license_type": "no_license", "max_line_length": 97, "num_lines": 115, "path": "/Dijkstra.py", "repo_name": "rohitnair11/Dijkstra-Shortest-Path", "src_encoding": "UTF-8", "text": "# Dijkstra's Shortest Path First algorithm with priority queue implementation using heap\r\nclass Dijkstra: \r\n\r\n # Priority Queue\r\n Q = []\r\n\r\n # Find index of left child of a node in the priority queue\r\n def left(self,i):\r\n return (2*i +1)\r\n \r\n # Find index of right child of a node in the priority queue\r\n def right(self,i):\r\n return (2*(i+1))\r\n\r\n # Find index of parent of a node in the priority queue\r\n def parent(self,i):\r\n return ((i-1)//2)\r\n\r\n # Decrease the key of a node in the priority queue\r\n def decrease_key(self,vertex, newWeight):\r\n index = -1\r\n for i in range(len(self.Q)):\r\n if self.Q[i].v == vertex:\r\n index = i\r\n break\r\n self.Q[index].w = newWeight\r\n while(index > 0 and self.Q[self.parent(index)].w > self.Q[index].w):\r\n self.Q[self.parent(index)], self.Q[index] = self.Q[index], self.Q[self.parent(index)]\r\n index = self.parent(index)\r\n\r\n # Builds a priority queue/ min-heap\r\n def build_min_heap(self,n):\r\n for i in range((len(self.Q)/2)-1,-1,-1):\r\n self.min_heapify(i,n)\r\n\r\n # Places a node in its appropriate position in the priority queue\r\n def min_heapify(self,i,n):\r\n l = self.left(i)\r\n r = self.right(i)\r\n if(l<n and self.Q[l].w<self.Q[i].w):\r\n smallest = l\r\n else:\r\n smallest = i\r\n if(r<n and self.Q[r].w<self.Q[smallest].w):\r\n smallest = r\r\n if smallest != i:\r\n temp = self.Q[i]\r\n self.Q[i] = self.Q[smallest]\r\n self.Q[smallest] = temp\r\n self.min_heapify(smallest,n)\r\n \r\n # Returns and removes the minimum element from the priority queue\r\n def extract_min(self):\r\n minim = self.Q[0].v\r\n self.Q[0] = self.Q[len(self.Q)-1]\r\n self.Q = self.Q[:-1]\r\n self.min_heapify(0, len(self.Q))\r\n return minim\r\n\r\n # Updates the distance between nodes if shorter path is found\r\n def relax(self, u, v, w, d, p ,usp):\r\n if ((d[u] + w)<d[v]):\r\n d[v] = d[u] + w\r\n p[v] = u\r\n usp[v] = usp[u]\r\n self.decrease_key(v, d[v])\r\n elif ((d[u] + w) == d[v]):\r\n usp[v]=0\r\n\r\n # Dijkstra's algorithm\r\n # See test case file for detailed information on inputs\r\n def Dijkstra_alg(self, n, e, mat, s):\r\n\r\n d = {} # Stores shortest distance\r\n p = {} # Stores the parent of a node\r\n usp = {} # Stores the number of unique shortest paths\r\n self.Q = []\r\n\r\n # Initialize\r\n for i in range(1, n+1):\r\n d[i] = float(\"inf\")\r\n p[i] = None\r\n usp[i] = 1\r\n\r\n # Set distance of source vertex to 0\r\n d[s] = 0\r\n\r\n # Insert all the vertices in the queue\r\n for i in range(1, n+1):\r\n self.Q.append(Node(i, d[i]))\r\n\r\n # Build a min heap/ priority-queue\r\n self.build_min_heap(len(self.Q))\r\n \r\n while len(self.Q)>0:\r\n u = self.extract_min()\r\n for i in range(e):\r\n if mat[i][0] == u:\r\n self.relax(mat[i][0], mat[i][1], mat[i][2], d, p, usp)\r\n elif mat[i][1] == u:\r\n self.relax(mat[i][1], mat[i][0], mat[i][2], d, p, usp)\r\n ans = []\r\n i=1\r\n for key,val in usp.items():\r\n ans.append([d[i],val])\r\n i=i+1\r\n return ans\r\n\r\n\r\nclass Node:\r\n v, w = 0, 0\r\n\r\n def __init__(self, a, b):\r\n self.v = a\r\n self.w = b" } ]
2
valexandersaulys/flask-ladder
https://github.com/valexandersaulys/flask-ladder
ecab3b6332bb5263eab443d753dba4f93ed6024a
719be21014cf37b2b0c80a142889a6f395b19825
c2e1e28e0cad6aaba48018950d64a269525193ff
refs/heads/master
2021-01-20T19:59:55.853571
2017-07-29T21:31:39
2017-07-29T21:31:39
63,025,119
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6297070980072021, "alphanum_fraction": 0.6401673555374146, "avg_line_length": 28.875, "blob_id": "3bbfe8299732e35196528f0655dd6e7eaef6049a", "content_id": "e4319213e32eccf330bbf581053a4422f4ee5931", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/app/csrf_protect.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "from . import app\nfrom .utils import hash_generator\n\[email protected]_request\ndef csrf_protect():\n if request.method == \"POST\":\n token = session.pop(\"_csrf_token\", None);\n if not token or token != request.form.get(\"_csrf_token\"):\n abort(403);\n\ndef generate_csrf_token():\n if \"_csrf_token\" not in session:\n session[\"_csrf_token\"] = hash_generator(30);\n return session[\"_csrf_token\"];\n\napp.jinja_env.globals['csrf_token'] = generate_csrf_token\n" }, { "alpha_fraction": 0.5360230803489685, "alphanum_fraction": 0.7118155360221863, "avg_line_length": 16.350000381469727, "blob_id": "66bba5d36490510a3751e2dc7d12f67b3f179d73", "content_id": "a633eba6b5e55d05af677c2a1bf5f24475e9bb89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 347, "license_type": "no_license", "max_line_length": 22, "num_lines": 20, "path": "/requirements.txt", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "alembic==0.8.8\nclick==6.6\nFlask==0.11.1\nFlask-Migrate==2.0.0\nflask-mongoengine==0.8\nFlask-MongoKit==0.6\nFlask-Script==2.0.5\nFlask-SQLAlchemy==2.1\nFlask-WTF==0.13.1\nitsdangerous==0.24\nJinja2==2.8\nMako==1.0.4\nMarkupSafe==0.23\nmongoengine==0.10.6\nmongokit==0.9.1.1\npymongo==3.3.0\npython-editor==1.0.1\nSQLAlchemy==1.1.1\nWerkzeug==0.11.11\nWTForms==2.1\n" }, { "alpha_fraction": 0.7354037165641785, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 43.77777862548828, "blob_id": "7e7ae101d658a2eb802c282f4edcc429ccd14b47", "content_id": "586f81131bb3166a37b1c546b26f159a10acb7c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 805, "license_type": "no_license", "max_line_length": 90, "num_lines": 18, "path": "/app/static/download_statics.sh", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Bash script to download the different javascript and css files\n# Updated as of 10 - 17 - 2016\n\n# Minified & Zipped Downloads\nwget https://code.jquery.com/jquery-3.1.1.min.js\nwget http://backbonejs.org/backbone-min.js\nwget https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\nwget https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css #optional\nwget https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js #optional\nwget http://underscorejs.org/underscore-min.js\n\n# Also, the non-min versions for development (if useful)\n#wget https://code.jquery.com/jquery-3.1.1.js\n#wget http://backbonejs.org/backbone.js\n#wget https://github.com/twbs/bootstrap/releases/download/v3.3.7/bootstrap-3.3.7-dist.zip\n#wget http://underscorejs.org/underscore.js" }, { "alpha_fraction": 0.4852941036224365, "alphanum_fraction": 0.4852941036224365, "avg_line_length": 12.199999809265137, "blob_id": "bc39cc322599ee04d78a0e3d80aee3b58951bca5", "content_id": "dbfc94aaec7c1a7b3935d8d3a5104331c7a3dbc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 23, "num_lines": 5, "path": "/app/forms.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "\n\n# def?\nclass LoginForm():\n \"\"\"\n For the login forms\n \"\"\"\n" }, { "alpha_fraction": 0.7291311621665955, "alphanum_fraction": 0.7376490831375122, "avg_line_length": 29.102563858032227, "blob_id": "66530e8f9c61c23af99a2173a4da99d0ab00b8a7", "content_id": "3c21fb711c549e66fe36c8b26e28ea835eb19afa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 83, "num_lines": 39, "path": "/app/__init__.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n# alternatively, from flask_mongoengine import MongoEngine\nimport os\nfrom config import BASEDIR\n\napp = Flask(__name__)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\n# db = MongoEngine(app) \n\n# User Authentication Dictionary (would be Redis-cache in production)\nauthhashes = {};\n\n# --------------------- Logging Errors\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfile_handler = RotatingFileHandler(\"activities.log\",maxBytes=100000,backupCount=1);\nfile_handler.setLevel(10);\napp.logger.addHandler(file_handler);\napp.logger.setLevel(level=0);\nlogger = app.logger\n\n\n# ==================== Start the App !\n\"\"\"\nblueprints live just below the app/ folder as subfolders with a similar \nlayout to the BASEDIR/app/ folder. \n>>> from app.simple_page import simple_page\n\n>>> app.register_blueprint(simple_page)\nand within BASEDIR/app/simple_page/__init__.py\n\n>>> simple_page = Blueprint('simple_page, __name__, template_folder=\"templates\")\nThen add simple_page routing like in the BASEDIR/app/\n\"\"\"\n# I though below was >>> from app import views, models\nimport csrf_protect\nimport views, models\n" }, { "alpha_fraction": 0.6240063309669495, "alphanum_fraction": 0.6263911128044128, "avg_line_length": 30.450000762939453, "blob_id": "00e017b03ef8ff9c1b31fe53bce11af5cb404e3c", "content_id": "d5460683bacd53a38fa31f3860a7ae65cec0c058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2516, "license_type": "no_license", "max_line_length": 71, "num_lines": 80, "path": "/app/accounts.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "# 'User' Model (for MySQL)\nfrom app import app, db\nfrom werkzeug.security import generate_password_hash, \\\n check_password_hash\n\nclass User(db.Model):\n # All models should have an 'id' \n id = db.Column(db.Integer, index=True, primary_key=True)\n \n # Standard user stuff\n username = db.Column(db.String(128), unique=True)\n password = db.Column(db.String(128), unique=True) \n\n def set_password(self, password):\n self.password = generate_password_hash(password)\n\n def check_password(self, password):\n return check_password_hash(self.password, password)\n \n def __repr__(self):\n # what gets printed in the console during debugging\n return \"<User %r>\" % (self.username)\n\n\n# login_required decorator\nfrom functools import wraps\nfrom flask import g, request, redirect, url_for\n\ndef login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if g[\"user\"] is None:\n return redirect( url_for(\"login_page\") );\n return f(*args, **kwargs)\n return decorated_function\n\n\n# login pages\[email protected](\"/login_page\",methods=[\"GET\"])\ndef login_page():\n return render_template(\"login_page.html\")\n\[email protected](\"/login\",methods=[\"POST\"])\ndef login():\n\n if request.headers['Content-Type'] == \"application/json\":\n name_of_user = request.json['username']\n pass_check = request.json['password']\n \"\"\"\n Store & then return some random hash as a key for\n authentication. Then check for it as a login in a \n RESTful authentication.\n\n from flask import jsonify\n from app import authhashes\n from app.utils import hash_generator\n \n hashname = hash_generator();\n authhashes[hashname] = name_of_user;\n return jsonify(authkey=hashname);\n \"\"\"\n else:\n name_of_user = request.form[\"username\"]\n pass_check = request.form[\"password\"]\n \n u = db.session.query(User).\\\n filter_by(username=request.form['username']).first()\n if u is not None:\n verification = u.check_password(pass_check)\n if verification==True:\n g[\"user\"] = u.username;\n logger.info(\"User %s Has Logged in\" % str(session['user']))\n return redirect( url_for(\"homepage\") );\n return render_template(\"error.html\");\n\[email protected](\"/logout\",methods=['GET','POST'])\ndef logout():\n g[\"user\"] = None;\n logger.info(\"User %s Has Logged Out\" % str(session['user']));\n return redirect( url_for(\"homepage\") )\n" }, { "alpha_fraction": 0.6266549229621887, "alphanum_fraction": 0.6366578340530396, "avg_line_length": 34.77894592285156, "blob_id": "57f4c0e69806ee1adeb0c72f90a204f01727e765", "content_id": "7ebdc0bf4ab784d1c7332b3c65ced57f8039ecde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3399, "license_type": "no_license", "max_line_length": 97, "num_lines": 95, "path": "/fabric_scripts/setup_server.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "from fabric.api import *\nimport string,random\n\ndef update_upgrade():\n \"\"\"Updates & Upgrades the server\"\"\"\n sudo(\"apt-get update\");\n sudo(\"apt-get -y upgrade\");\n\n\ndef install_nginx():\n \"\"\"Install nginx\"\"\"\n sudo(\"apt-get install nginx\");\n\ndef install_python():\n \"\"\"Install python, dev, etc.\"\"\"\n sudo(\"apt-get install python python-dev python-pip libssl-dev \"\\\n \"libffi-dev htop munin\");\n\ndef create_deploy_user():\n \"\"\"creates a user for deploying a website & copy a git template over\"\"\"\n sudo(\"adduser deploy\");\n run(\"git clone http://github.com/valexandersaulys/flask-ladder\");\n run(\"virtualenv .venv\");\n sudo(\"chown deploy:deploy .venv/\");\n sudo(\"chown deploy:deploy flask-ladder/\");\n run(\".venv/bin/pip install -r flask-ladder/requirements.txt\");\n\ndef install_mysql():\n \"\"\" Installs and configures MySQL for 'deploy' user \"\"\"\n sudo(\"apt-get install mysql-server mysql-client\");\n password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(12));\n sudo(\"mysql --execute=\\\"CREATE USER 'deploy'@'localhost' IDENTIFIED BY '\"+password+\"';\\\"\");\n\n # Run some mysql commands for setup\n sudo(\"mysql --execute=\\\"CREATE DATABASE deployment;\\\"\");\n sudo(\"mysql --execute=\\\"CREATE DATABASE development;\\\"\");\n sudo(\"mysql --execute=\\\"GRANT ALL PRIVILEGES ON deployment.* to 'deploy'@'localhost';\\\"\");\n sudo(\"mysql --execute=\\\"GRANT ALL PRIVILEGES ON development.* to 'deploy'@'localhost';\\\"\");\n\n # Then add the mysql URI to the bashrc for deploy user\n bash_insert_string = \"deploy:\"+password+\"@localhost\"; # uri for flask\n sudo(\"echo 'DATABASE_URI=x\"+bash_insert_string+\"' >> /home/deploy/.bashrc\"); \n\ndef install_mongodb():\n \"\"\" Installs and configures mongodb for 'deploy' user \"\"\"\n # Install MongoDB\n sudo(\"apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927\");\n run(\"echo \"\\\n + \"'deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse'\"\\\n + \"| sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list\");\n sudo(\"apt-get update\");\n sudo(\"apt-get install -y mongodb-org\");\n\n # Unfortuantely, creating and configuring a user will not be a one liner...\n \"\"\"\n db.createUser({ username:\"\",\n password:\"\", \n roles:[ { role:\"dbAdmin or readWrite\",\n db: \"<name_of_database>\" }, ... ]\n } );\n db.getUsers(); # to get users\n show dbs # to show users\n db.updateUser(\"name_of_user\", { roles: [ {role: '', db: '' },... ] });\n \"\"\"\n\n\ndef install_redis():\n \"\"\"\n Installs Redis\n Run as main user\n \"\"\"\n print \"Installing some base dependencies\"\n sudo(\"apt-get update\");\n sudo(\"apt-get install -y build-essential tcl8.5\");\n\n print \"Download with wget the redis installers for ubuntu\";\n run(\"wget http://download.redis.io/releases/redis-stable.tar.gz\");\n run(\"tar xzf redis-stable.tar.gz\");\n\n print \"Download and run make for redis\";\n run(\"cd redis-stable\");\n run(\"make\");\n run(\"make test\");\n sudo(\"make install\");\n\n print \"Run the included script to install\"\n with cd(\"utils\"):\n sudo(\"./install_server.sh\");\n sudo(\"service redis_6379 start\");\n\n print \"Run setup at startup\"\n sudo(\"update-rc.d redis_6379 defaults\");\n\n print \"then setup security so that _only_ the localhost can access\"\n sudo(\"echo 'bind 127.0.0.1' >> /etc/redis/6379.conf\");\n" }, { "alpha_fraction": 0.66015625, "alphanum_fraction": 0.66015625, "avg_line_length": 27.22222137451172, "blob_id": "da0bc0894fde4dee74926b1c5b64416c53a941ba", "content_id": "526026b8cd0f71371f4fe7cc3f5c6d342f01c485", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 60, "num_lines": 9, "path": "/app/models.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "from app import db\nfrom werkzeug.security import generate_password_hash, \\\n check_password_hash\n\nclass SimpleModel(db.Model):\n id = db.Column(db.Integer, index=True, primary_key=True)\n\n def __repr__(self):\n return \"<ID #%r>\" % (self.id);\n\n\n" }, { "alpha_fraction": 0.6356107592582703, "alphanum_fraction": 0.6542443037033081, "avg_line_length": 27.41176414489746, "blob_id": "8243af43dc6d06d3afbbea1ea9ba003c692daafa", "content_id": "ab5dafa2b6fc27ab7fa4cac89df81e87f9d5aeef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/app/views.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "import os, datetime\nfrom app import app, db, logger\nfrom flask import render_template, flash, redirect, session, url_for, \\\n request, g, send_from_directory\n\n# - - - - - - - Custom Routing\[email protected](404)\ndef error_404():\n # Haven't actually tried this yet\n return render_template(\"404.html\")\n \n# - - - - - - - Main Routes\[email protected](\"/\")\[email protected](\"/index\",methods=['GET'])\ndef main_page():\n # Display main login page\n return render_template(\"index.html\")\n" }, { "alpha_fraction": 0.6746411323547363, "alphanum_fraction": 0.6925837397575378, "avg_line_length": 28.85714340209961, "blob_id": "b74c4534eb7341ae14668704e04774cd54510bff", "content_id": "3709f8c05e13a2537c0c2f13468d54676581efb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 836, "license_type": "no_license", "max_line_length": 77, "num_lines": 28, "path": "/config.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "import os\n\nSECRET_KEY = \"beautiful_little_world_is_mine\"\nBASEDIR = os.path.abspath(os.path.dirname(__file__))\n\n# = = = = = = = For the Database Configuration\n# Separate out into a 'db_config.py' for larger projects\nif os.environ.get('DATABASE_URI') is None:\n DATABASE_URL = 'sqlite:///' + os.path.join(BASEDIR, 'app.db')\n SQLALCHEMY_MIGRATE_REPO = os.path.join(BASEDIR, 'db_repository')\n SQLALCHEMY_TRACK_MODIFICATIONS = True;\nelse:\n DATABASE_URL = os.environ['DATABASE_URI']; # could be mongodb\n\n\"\"\"\nSample MongoDB Setup, if the URL is not specified as an environement variable\n\nMONGODB_DB = 'project1'\nMONGODB_HOST = '192.168.1.35'\nMONGODB_PORT = 12345\nMONGODB_USERNAME = 'webapp'\nMONGODB_PASSWORD = 'pwd123'\n\"\"\"\n\n# - - - - - - - Put Constants here\n\"\"\"\nExamples can include bits like constants for folder storage\n\"\"\"\n" }, { "alpha_fraction": 0.6759259104728699, "alphanum_fraction": 0.6805555820465088, "avg_line_length": 35, "blob_id": "a2a2a669b10f4059655d15158967ad7c47d560cf", "content_id": "65f64a29235e51a765a1852f65cf03718cf7846e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 65, "num_lines": 6, "path": "/app/utils.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "# Any utility functions would go here\nimport string, random\n\ndef hash_generator(size=8,\n chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n" }, { "alpha_fraction": 0.6355932354927063, "alphanum_fraction": 0.6694915294647217, "avg_line_length": 38, "blob_id": "d26e39316ab22e982a8f482e783b050ce2e3099f", "content_id": "3b486b478bf50445e29ee0602fdd9a82fd955398", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 77, "num_lines": 3, "path": "/run.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "#!.venv/bin/python\nfrom app import app\napp.run(host='0.0.0.0') # Does __not__ run as a debug! For use with gunicorn\n\n" }, { "alpha_fraction": 0.6870967745780945, "alphanum_fraction": 0.6870967745780945, "avg_line_length": 26.909090042114258, "blob_id": "25907536c45de6729cb5e1bd3fb22c0211d6c234", "content_id": "fa6b81af9afb61e6f51e5cf9dcfecdc4767d35d3", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/fabric_scripts/fabfile.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "# Python script: run with `$ fab ___command___`\n\n# Imports from nearby files\nfrom fabric.api import *\nfrom setup_server import *\n\n# Environmental Stuff\nenv.hosts = [\n 'server.domaind.tld', # name or ip address of server\n]\nenv.user = 'root' # name of user, you'll have to supply password at execution\n\n\n\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7184466123580933, "avg_line_length": 21.071428298950195, "blob_id": "a9016ce37d31be5e71e0dd3c9fbf2994e8d9688f", "content_id": "e65a87e0fc4583f3d5352fb88c30703afb099557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/manage.py", "repo_name": "valexandersaulys/flask-ladder", "src_encoding": "UTF-8", "text": "#!.venv/bin/python\n\"\"\"\nThis can be pretty much kept straight\n\"\"\"\nfrom app import db, app\nfrom flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\n\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\nif __name__==\"__main__\":\n manager.run()\n" } ]
14
ing-ivan-31/django-tutorial
https://github.com/ing-ivan-31/django-tutorial
7c37934e45cd8c7dbf1ca1a179518e4edcddd8e2
03ac27d41bcc2d50c013a85888582f2fc8134148
6b81712ecffb976ee01b7b09f0fed19006e58e6b
refs/heads/master
2020-05-21T11:57:26.347193
2019-05-14T19:48:05
2019-05-14T19:48:05
186,043,813
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7540193200111389, "alphanum_fraction": 0.7540193200111389, "avg_line_length": 30.100000381469727, "blob_id": "f67118a416befb6a5279756db6f76623949adb57", "content_id": "bb441c98f25d82ae38675a944a467db4c37d5666", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "permissive", "max_line_length": 80, "num_lines": 20, "path": "/app/articles/views.py", "repo_name": "ing-ivan-31/django-tutorial", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nfrom django.shortcuts import render\nfrom .models import Article\nfrom django.contrib.auth.decorators import login_required\n\n\ndef article_list(request):\n articles = Article.objects.all().order_by('date')\n return render(request, 'articles/article_list.html', {'articles': articles})\n\n\ndef article_details(request, slug):\n article = Article.objects.get(slug=slug)\n return render(request, 'articles/article_detail.html', {'article': article})\n\n\n@login_required(login_url=\"accounts:login\")\ndef article_create(request):\n return render(request, 'articles/article_create.html')\n" }, { "alpha_fraction": 0.720695972442627, "alphanum_fraction": 0.721611738204956, "avg_line_length": 21.72916603088379, "blob_id": "7abde2736f9c8742fc1db42a9bab678c40dd2791", "content_id": "73eda26dc382c7ce27ca517437b4ab479eface38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1092, "license_type": "permissive", "max_line_length": 99, "num_lines": 48, "path": "/README.md", "repo_name": "ing-ivan-31/django-tutorial", "src_encoding": "UTF-8", "text": "# recipe-app\npython django rest framework\n\n**Instruction for Build image**\n\ndocker-compose build\n\n**Start Project to app folder**\n\n docker-compose run web sh -c \"django-admin.py startproject djangonautic .\"\n \n**Add modules to project**\n\ndocker-compose run web sh -c \"django-admin.py startapp djangonautic .\"\n\n**or**\n\nPreviously you need create the folder _articles_ inside api\n\ndocker-compose run web sh -c \"django-admin.py startapp articles ./articles\"\n\n**Make new Migrations**\n \n docker-compose run web sh -c \"python manage.py makemigrations\"\n\n**Run Migrations**\n \n docker-compose run web sh -c \"python manage.py migrate\"\n \n **Interactive Shell for ORM (like thinker)**\n \n docker-compose run web sh -c \"python manage.py shell\"\n \n**Add Super User Password: secret1234**\n \n docker-compose run web sh -c \"python manage.py createsuperuser --email [email protected] --username admin\"\n\n**Up docker container**\n\ndocker-compose up web\n\n**Run tests**\n \n docker-compose run web sh -c \"python manage.py test\"\n\n**Run tests And Linting**\n \n docker-compose run web sh -c \"python manage.py test && flake8\"\n\n" }, { "alpha_fraction": 0.522580623626709, "alphanum_fraction": 0.7032257914543152, "avg_line_length": 16.33333396911621, "blob_id": "8ab378d15bdb3801fece14e83899b939d6c16ea2", "content_id": "a3db03bfb29539e8519104292059cf155c13997e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 155, "license_type": "permissive", "max_line_length": 27, "num_lines": 9, "path": "/requirements.txt", "repo_name": "ing-ivan-31/django-tutorial", "src_encoding": "UTF-8", "text": "Django==2.2.0\ndjangorestframework==3.9.3\npsycopg2==2.8.2\nmarkdown==3.1\ndjango-filter==2.1.0\ndjango-oauth-toolkit==1.2.0\nPillow==6.0.0\n\nflake8>=3.6.0,<3.7.0" }, { "alpha_fraction": 0.7530120611190796, "alphanum_fraction": 0.759036123752594, "avg_line_length": 25.520000457763672, "blob_id": "9514a243d7f7bd0a4850d5de87f4671b0b4855c5", "content_id": "8bf5849c435f3c1a060bb213eced723f35a2b815", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 664, "license_type": "permissive", "max_line_length": 78, "num_lines": 25, "path": "/Dockerfile", "repo_name": "ing-ivan-31/django-tutorial", "src_encoding": "UTF-8", "text": "# base image\nFROM python:3.7-alpine\nMAINTAINER Ivan Sanchez\n\n# postgres extension needed it psycopg2 extension\nRUN apk add --update --no-cache postgresql-client\nRUN apk add --update --no-cache --virtual .tmp-build-deps \\\n gcc libc-dev linux-headers postgresql-dev\n# z-lib needed for Pillow extension\nRUN apk add --update --no-cache build-base python-dev py-pip jpeg-dev zlib-dev\n\n#show logs in docker\nENV PYTHONUNBUFFERED 1\n\n# add and install requirements\nCOPY ./requirements.txt /requirements.txt\nRUN pip install -r requirements.txt\nRUN apk del .tmp-build-deps\n\n# set working directory\nRUN mkdir -p /app\nWORKDIR /app\n\n# Copy app to docker container\nCOPY ./app /app\n\n" } ]
4
HolyCaonima/MDZZProject
https://github.com/HolyCaonima/MDZZProject
b6fa45fb6535a0810c7f47b1bc1a5ed1f378fce4
2b5d1ae76b4727e0763d1acc910fae5b66a29b4e
c6b3024ae0345b0adf15ad4a22b8841651dbdf9a
refs/heads/master
2020-03-17T16:23:40.588558
2018-05-20T14:32:08
2018-05-20T14:32:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 26.058822631835938, "blob_id": "a6f042e919848828c2e8145741c2c57a508dad13", "content_id": "8d0109062795306bd43bc74a8eba06e40bf0c855", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 43, "num_lines": 17, "path": "/Server/Server/Server/backend/request.py", "repo_name": "HolyCaonima/MDZZProject", "src_encoding": "UTF-8", "text": "\nfrom django.shortcuts import render\nfrom django.http import HttpRequest\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\nfrom datetime import datetime\n\nfrom app.models import TestTable\n\ndef fuckme(request):\n \"\"\"api example.\"\"\"\n assert isinstance(request, HttpRequest)\n test = TestTable(name = 'caonima')\n test.save()\n for li in TestTable.objects.all():\n print str(li.name)\n \n return HttpResponse(\"mdzz\")" }, { "alpha_fraction": 0.5862069129943848, "alphanum_fraction": 0.5862069129943848, "avg_line_length": 8.666666984558105, "blob_id": "79c4463ff5affe351899ced8a269aa2154db3caa", "content_id": "1115fdf639ad722eeda34323dc2e43386bcfa890", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "permissive", "max_line_length": 20, "num_lines": 3, "path": "/Server/Server/Server/backend/__init__.py", "repo_name": "HolyCaonima/MDZZProject", "src_encoding": "UTF-8", "text": "\"\"\"\nPackage for Backend.\n\"\"\"\n" }, { "alpha_fraction": 0.7012194991111755, "alphanum_fraction": 0.7195122241973877, "avg_line_length": 17.33333396911621, "blob_id": "60e2d94b6cd9962ce9678a1d871da2d08f9b639c", "content_id": "a6948d2a33388b757a5c037a1a02c66011124cb1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "permissive", "max_line_length": 45, "num_lines": 9, "path": "/Server/Server/app/models.py", "repo_name": "HolyCaonima/MDZZProject", "src_encoding": "UTF-8", "text": "\"\"\"\nDefinition of models.\n\"\"\"\n\nfrom django.db import models\n\n# Create your models here.\nclass TestTable(models.Model):\n name = models.CharField(max_length = 123)" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 8.333333015441895, "blob_id": "16f40927cc2df01b9cffd9668df114d6a5f8b51f", "content_id": "5206c03a8f9d0eed6ea9e81da2bb1b9ac88b7c7d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28, "license_type": "permissive", "max_line_length": 19, "num_lines": 3, "path": "/Server/Server/Server/__init__.py", "repo_name": "HolyCaonima/MDZZProject", "src_encoding": "UTF-8", "text": "\"\"\"\nPackage for Server.\n\"\"\"\n" } ]
4
hongmendalao/DaDaNiao2
https://github.com/hongmendalao/DaDaNiao2
8994abf9c13e90d2dce7d086b3043f72693fbef1
f45752062c5235ff27a688fcc37cbd034b94c969
4a4c1cdd70899dfe3712ee5b169701e804b3a0cb
refs/heads/master
2020-03-17T13:11:56.775913
2018-05-17T03:34:52
2018-05-17T03:34:52
133,621,380
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5961538553237915, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 5.857142925262451, "blob_id": "b3ed8c5ffbc677b73413c6aa93fef30f0debdf48", "content_id": "d04614884f2531c05b76e1f92b2d0df257ccf705", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "permissive", "max_line_length": 12, "num_lines": 7, "path": "/README.md", "repo_name": "hongmendalao/DaDaNiao2", "src_encoding": "UTF-8", "text": "# DaDaNiao2\n\n\n\n## gitignore\n- 忽略规则文件\n- 哪些文件被忽略掉\n\n\n\n\n" }, { "alpha_fraction": 0.6714285612106323, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 7.07692289352417, "blob_id": "40871cacb63b82d9b03542b322a22aeedeeea848", "content_id": "d99af44e558f99c4e9508457e22c4309685c00ac", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "permissive", "max_line_length": 22, "num_lines": 26, "path": "/Hello.py", "repo_name": "hongmendalao/DaDaNiao2", "src_encoding": "UTF-8", "text": "\nprint('你真是一个小天才')\n\nprint('听说你是个棒槌')\n\nprint('sadasdsadsd')\n\n\nprint('jijijijijij')\n\n\nhello = 'dig'\n\n\nprint(hello)\n\n\nprint('liweiguo')\n\nprint('这只是个开始')\n\nprint('后面还会有无数的挫折和考验')\n\nprint('漂亮的小姐姐')\n\n\nprint('需要我们解放她们')" } ]
2
JDCha/NaverAdBid
https://github.com/JDCha/NaverAdBid
e4bf93e87edd07a686e5d9cb8afa1ec1e45e9b37
bdee6b96e5261845f794ab94d1f6f606854d1cf3
773118c5e39759bbc9b9d3ab107c8923da4b65e6
refs/heads/master
2020-12-20T16:52:57.733270
2018-12-11T01:16:13
2018-12-11T01:16:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5895627737045288, "alphanum_fraction": 0.6050775647163391, "avg_line_length": 19.764705657958984, "blob_id": "3995cc835a617da8faf8088dce6b0adc4944fbe9", "content_id": "9e36ba7503f86dd97daef25842d1701c1b174b32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 97, "num_lines": 34, "path": "/gui_test.py", "repo_name": "JDCha/NaverAdBid", "src_encoding": "UTF-8", "text": "import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QInputDialog, QPushButton\nfrom PyQt5.QtCore import Qt\n\nclass TestApp(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle('Test')\n self.resize(400,400)\n\n label1 = QLabel('안녕하세요',self)\n label1.setAlignment(Qt.AlignCenter)\n\n button = QPushButton('test')\n\n\n layout = QVBoxLayout()\n layout.addWidget(label1)\n layout.addWidget(button)\n\n\n self.setLayout(layout)\n\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = TestApp()\n sys.exit(app.exec_())\n\n\n\n" }, { "alpha_fraction": 0.542859673500061, "alphanum_fraction": 0.5560199022293091, "avg_line_length": 36.365447998046875, "blob_id": "b4b6abede9e9c2c7b2e3454cdefd488bb3e4a680", "content_id": "a1a76c1dede43e46b73871e9904c2e250c947d7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12248, "license_type": "no_license", "max_line_length": 329, "num_lines": 301, "path": "/main.py", "repo_name": "JDCha/NaverAdBid", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport pandas\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0\nfrom selenium.webdriver.support import expected_conditions as EC # available since 2.26.\n\nfrom datetime import datetime\nfrom datetime import timedelta\nimport os, sys, time\n\n\nclass NaverAdSystem(object):\n\n # 생성자\n def __init__(self, webdriver_path, data_file_path, id, pw):\n self.browser = webdriver.Chrome(webdriver_path)\n\n self.df = pandas.read_excel(data_file_path)\n self.df = self.df.to_dict('records')\n\n self.id = id\n self.pw = pw\n\n self.start_hour = None\n self.end_time = None\n self.repeat = None\n\n def set_repeat(self, repeat):\n self.repeat = repeat\n\n def restart(self):\n executable = sys.executable\n args = sys.argv[:]\n args.insert(0, sys.executable)\n self.browser.quit()\n\n time.sleep(1)\n\n print(\"메모리 에러 방지를 위한 프로그램 재실행\")\n os.execvp(executable, args)\n\n\n def set_time(self, start_hour, duration_hour):\n\n start_time = datetime.strptime(start_hour, \"%H:%M\")\n after_h = timedelta(hours=duration_hour)\n end_hour = start_time + after_h\n\n self.start_hour = start_hour\n self.end_time = end_hour.hour\n\n return self.end_time\n\n # html 코드를 Beautifulsoup을 이용해 파싱한 결과로 반환하는 함수\n def return_html(self, browser_page_source):\n html = BeautifulSoup(browser_page_source, \"html.parser\")\n return html\n\n # 딜레이 함수\n def wait(self, code, division, delay_second):\n if division == \"xpath\":\n my_division = By.XPATH\n elif division == \"css\":\n my_division = By.CSS_SELECTOR\n else:\n my_division = By.CLASS_NAME\n\n try:\n element = WebDriverWait(self.browser, delay_second).until(EC.presence_of_element_located((my_division, code)))\n except:\n return -1\n\n # 홈페이지 접속 및 로그인, 광고시스템 클릭 함수\n def naver_login(self, id, pw):\n\n # 홈페이지 접속 및, 로그인화면이 뜰때까지 wait\n self.browser.get(\"https://searchad.naver.com\")\n self.wait('//*[@id=\"uid\"]', \"xpath\", 10)\n\n # 아이디와 비밀번호 입력 후 로그인, 광고 시스템창이 뜰때까지 wait\n self.browser.find_element_by_xpath('//*[@id=\"uid\"]').send_keys(id)\n self.browser.find_element_by_xpath('//*[@id=\"upw\"]').send_keys(pw)\n self.browser.find_element_by_xpath(\n '//*[@id=\"container\"]/main/div/div[1]/home-login/div/fieldset/span/button').click()\n self.wait('//*[@id=\"container\"]/my-screen/div/div[1]/div/my-screen-board/div/div[1]/ul/li[1]/a', \"xpath\", 10)\n\n # 광고 시스템창 클릭 후 혹시모를 에러를 대비해 1초 wait\n self.browser.find_element_by_xpath(\n '//*[@id=\"container\"]/my-screen/div/div[1]/div/my-screen-board/div/div[1]/ul/li[1]/a').click()\n self.browser.implicitly_wait(1000)\n\n # 광고 시스템창으로 탭 이동\n self.browser.switch_to.window(self.browser.window_handles[1])\n\n # 키워드 검색, 노출현황보기 클릭 후 html 코드 반환 함수\n def search_keyword(self, keyword_id):\n # 키워드를 검색하고, 노출현황보기창이 뜰떄까지 wait\n self.browser.find_element_by_xpath(\n '//*[@id=\"wrap\"]/div/div/div[1]/div[2]/div/div[2]/div/div/div/form/div/input').send_keys(keyword_id)\n self.wait('//*[@id=\"wrap\"]/div/div/div[1]/div[2]/div/div[2]/div/div/div/form/ul/div/div/div/div/ul/li/a',\n \"xpath\", 10)\n self.browser.find_element_by_xpath(\n '//*[@id=\"wrap\"]/div/div/div[1]/div[2]/div/div[2]/div/div/div/form/ul/div/div/div/div/ul/li/a').click()\n self.wait('#wgt-{keyword} > td:nth-child(10) > a'.format(keyword=keyword_id), \"css\", 10)\n\n # 노출 현황보기 클릭\n self.browser.execute_script(\n \"document.querySelector('#wgt-{keyword} > td:nth-child(10) > a').click();\".format(keyword=keyword_id))\n self.browser.find_element_by_xpath('//*[@id=\"wrap\"]/div[1]/div/div/div/div[2]/div[2]/div[3]')\n\n # 노출현황보기창의 코드를 반환\n html = self.return_html(self.browser.page_source)\n return html\n\n # pc 순위 체크 및, 현재 순위 반영 함수\n def pc_rank(self, html, item):\n rank_html = html.find('div', {\"class\": \"scroll-wrap\"})\n\n # PC 광고 개수 크롤링\n pc_rank_list = rank_html.find_all(\"div\", {\"class\": \"content ng-scope\"})\n item['pc_ad_count'] = len(pc_rank_list)\n\n if item['pc_ad_count'] == 0:\n return \"0 error\"\n\n # 현재 pc 광고 순위 체크\n flag = False\n for i, pc_rank in enumerate(pc_rank_list):\n if item['pc_url'] == pc_rank.find('a', {'class': 'lnk_url ng-binding'}).text:\n item['pc_current_rank'] = i + 1\n flag = True\n\n if flag is False:\n item['pc_current_rank'] = -1\n\n self.browser.implicitly_wait(300)\n\n # mobile 순위 체크 및, 현재 순위 반영 함수\n def mobile_rank(self, item):\n\n self.browser.find_element_by_xpath('//*[@id=\"wrap\"]/div[1]/div/div/div/div[2]/div[1]/ul/li[2]/a').click()\n html = self.return_html(self.browser.page_source)\n\n mobile_rank_html = html.find('div', {\"class\": \"scroll-wrap\"})\n mobile_rank_list = mobile_rank_html.find_all(\"div\", {\"class\": \"content ng-scope\"})\n\n # mobile 광고 개수 크롤링\n item['mobile_ad_count'] = len(mobile_rank_list)\n\n # 현재 mobile 광고 순위 체크\n flag = False\n for i, mobile_rank in enumerate(mobile_rank_list):\n if item['mobile_url'] == mobile_rank.find('cite', {'class': 'url'}).find('a', {'class': 'ng-binding'}).text:\n item['mobile_current_rank'] = i + 1\n flag = True\n\n if flag is False:\n item['mobile_current_rank'] = -1\n\n time.sleep(3)\n self.browser.implicitly_wait(1000)\n\n self.wait('//*[@id=\"wrap\"]/div[1]/div/div/div/div[3]/button',\"xpath\",10)\n\n # 닫기버튼 클릭\n self.browser.find_element_by_xpath('//*[@id=\"wrap\"]/div[1]/div/div/div/div[3]/button').click()\n\n # 입찰금액 변경 및 적용 함수\n def bid_change(self, item):\n keyword_id = item['keyword_id']\n\n # 입찰금액 변경\n self.browser.execute_script(\n \"document.querySelector('#wgt-{keyword} > td.cell-bid-amt.text-right.txt-r > a').click();\".format(\n keyword=keyword_id))\n\n bid_input_box = self.browser.find_element_by_xpath(\n '//*[@id=\"wgt-{keyword}\"]/td[5]/a/div/div/div[2]/div[1]/div/span/input'.format(keyword=keyword_id))\n\n # 현재 입찰 금액 받아오기\n item['current_bid'] = int(bid_input_box.get_attribute('value'))\n\n # 순위체크 후 새로운 금액 반영\n new_bid = item['current_bid']\n if item['pc_current_rank'] < item['hope_rank'] and item['pc_current_rank'] != -1: # 순위가 높다면\n new_bid = new_bid - item['minus_money']\n elif item['pc_current_rank'] > item['hope_rank'] or item['pc_current_rank'] == -1:\n new_bid = new_bid + item['plus_money']\n\n # 순위 같으면 변경 안함\n if item['pc_current_rank'] == item['hope_rank']:\n item['check'] = 'rank success'\n return \"same\"\n\n # 입찰금액보다 오버 됫을 경우 변경 안하고 check 항목을 fail로 변경\n if new_bid > item['max_bid']:\n item['check'] = 'max bid over'\n new_bid = item['max_bid']\n elif new_bid < 70:\n item['check'] = '70 이하로 내려갈 수 없습니다'\n new_bid = 70\n else:\n item['check'] = 'bid changing'\n\n bid_input_box.clear()\n bid_input_box.send_keys(str(new_bid))\n\n # 최종 변경 버튼 클릭\n self.browser.execute_script(\n \"document.querySelector('#wgt-{keyword} > td.cell-bid-amt.text-right.txt-r > a > div > div > div.popover-content > div.form-inline > div > button.btn.btn-primary.editable-submit').click();\".format(\n keyword=keyword_id))\n\n time.sleep(3)\n self.browser.implicitly_wait(1500)\n\n self.wait('//*[@id=\"wrap\"]/div[1]/div/div/div/div[3]/button', \"xpath\", 10) # code add\n\n # 변경 알림사항 닫기\n self.browser.find_element_by_xpath('//*[@id=\"wrap\"]/div[1]/div/div/div/div[3]/button').click()\n item['current_bid'] = new_bid\n\n def process(self):\n\n # 홈페이지 접속 및 로그인, 광고시스템 클릭\n self.naver_login(self.id, self.pw)\n repeat_count = 1\n\n while True:\n\n # 끝나는 시간되면 프로그램 반복 종료\n now = int(datetime.now().hour)\n if now == int(self.end_time):\n fp = open('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp21/Data/r.txt', 'w', encoding='utf-8')\n fp.write('1')\n exit(0)\n break\n\n\n fp = open('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/r.txt','r',encoding='utf-8')\n repeat = int(fp.read().replace('\\n',''))\n fp.close()\n\n\n for i in range(repeat, len(self.df)):\n\n # 끝나는 시간되면 프로그램 반복 종료\n now = int(datetime.now().hour)\n if now == int(self.end_time):\n fp = open('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp21/Data/r.txt', 'w',\n encoding='utf-8')\n fp.write('1')\n exit(0)\n\n\n item = self.df[i]\n\n # pass 는 키워드 검색 안함\n if item['pass'] == 'pass':\n continue\n\n keyword_id = item['keyword_id']\n\n try:\n html = self.search_keyword(keyword_id) # 키워드 검색\n self.pc_rank(html, item) # pc 광고 개수 및 현재 순위 파악\n time.sleep(5)\n\n self.mobile_rank(item) # mobile 광고 개수 및 현재 순위 파악\n self.bid_change(item) # 입찰 금액 변경\n\n item['time'] = datetime.now()\n\n df = pandas.DataFrame(self.df,columns=['pc_url','mobile_url','group_name','keyword_id','keyword_name','hope_rank','plus_money','minus_money','max_bid','current_bid','check','pc_ad_count','pc_current_rank','mobile_ad_count','mobile_current_rank','pass','time']) # pandas 사용 l의 데이터프레임화) # pandas 사용 l의 데이터프레임화\n df.to_excel('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/Pm_Tp_Data.xlsx', encoding='utf-8-sig', index=False)\n except:\n item['check'] = 'error 발생'\n print(item['keyword_id'] + ' 에서 에러 발생')\n\n repeat_count = repeat_count + 1\n\n if self.repeat%repeat_count == 0: # 프로그램을 재실행\n fp = open('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/r.txt','w',encoding='utf-8')\n fp.write(str(i + 1))\n fp.close()\n self.restart()\n\n fp = open('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/r.txt', 'w', encoding='utf-8')\n fp.write('1')\n fp.close()\n\n\nnaver_ad_system = NaverAdSystem('/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/chromedriver', # 웹 드라이버 경로\n '/Users/pro.123/PycharmProjects/Python/A_Naver_Ad_Selenium_Pm_Tp/Data/Pm_Tp_Data.xlsx', # 데이터 엑셀파일\n 'tourtopping','xndjxhvld11')\n\nnaver_ad_system.set_time(\"18:00\",4)\nnaver_ad_system.set_repeat(101)\n\nnaver_ad_system.process()" }, { "alpha_fraction": 0.6096625924110413, "alphanum_fraction": 0.620398759841919, "avg_line_length": 30.780487060546875, "blob_id": "e5d557cba73ea4c76633123c1e825627cacf3d85", "content_id": "1716a99b60e7cb83a74eb0cf856f66bb08fe9702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1534, "license_type": "no_license", "max_line_length": 116, "num_lines": 41, "path": "/test.py", "repo_name": "JDCha/NaverAdBid", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport time\n\n#해당 트위터 링크, 사진이 있다면 사진, 트위터안의 링크, 리트윗은 배제\n\n# 12 -> 트위터링크, 사진, 텍스트, 리트윗 배제\n# 13 -> 프로그램화(DB에다가 데이터를 저장) + selenium, request(트위터크롤링 도전), 프록시를 설정\n# 14 -> Slack 으로 전송(Atoms 참고해서 Slack에 데이터를 전송)\n# 15 -> 전체 마무리\n# 16 -> 추가적으로 넣고싶은 기능, 메모리오류(24, 프로그램을 재실행)\n\nkeywords=['New Balance','bag']\n\nbrowser=webdriver.Chrome('/Users/itaegyeong/PycharmProjects/NaverAd/data/chromedriver')\nsite_list=open('site_list.txt', 'r')\n\n\nfor site in site_list.readlines():\n\n browser.get(site)\n html=BeautifulSoup(browser.page_source, 'html.parser')\n\n tweets = html.find_all('li',{'class':'js-stream-item stream-item stream-item '})\n\n for tw in tweets:\n tw_text = tw.find('p',{'class':'TweetTextSize TweetTextSize--normal js-tweet-text tweet-text'}).text\n tw_medias = tw.find_all('div',{'class':'AdaptiveMedia-container'})\n\n tw_link = 'https://twitter.com/{id}/status/{tw_id}'.format(id=site.split('/')[-1], tw_id=tw['data-item-id'])\n print(tw_link)\n\n tw_retweet = tw.find('span',{'class':'js-retweet-text'})\n\n if tw_retweet is None:\n for tw_m in tw_medias:\n imgs = tw_m.find_all('img')\n for img in imgs:\n print(img['src'])\n\n print()\n\n" } ]
3
pickettj/jupyter_notebooks
https://github.com/pickettj/jupyter_notebooks
f4bac7dd8d1688ec259e2f13f180ddaee031dc5c
2fcabdd5eb4990549f93f6cd25e5af6c33ea5e38
964b4289603bec6b24e016cf2946d05f95a2cd1b
refs/heads/master
2023-08-22T13:12:33.882933
2023-08-10T19:44:05
2023-08-10T19:44:05
167,718,102
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7559322118759155, "alphanum_fraction": 0.7649717330932617, "avg_line_length": 87.30000305175781, "blob_id": "8fe8d5d72e511f67cedfd591e5bff37f5bce3410", "content_id": "625e4607b85557c2a4b1e3823365d8c71a28857f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1433, "license_type": "no_license", "max_line_length": 167, "num_lines": 10, "path": "/ser626.md", "repo_name": "pickettj/jupyter_notebooks", "src_encoding": "UTF-8", "text": "\n---- \n\n> (First glance) Statement that ulama are in agreement that the vocal Zikr of Ahmad Yasawi is legitimate, based on a gathering of them. Seal marks this from 1284/1866.\n\n- درینمسئله که جماعۀ از مسلمین که ممتمسکین بسلسلۀ شریفه حضرت سلطان العافین قدوة المسلاکین برهان الشریفه و الحق و الدین قطب\n- الاولیاء و صفوة الاصفیاء *اعنی* حضرت خواجه احمد قدس الله تعالی روحه العزیز بطهارت *بادم* تمام در مساجد و زوایای در مکان طاهر جمع شده\n- از سر صمیمی صدق و ا اخلاص بنیت صحیحه خالیاً عن الریا و الاعواض بجهت طالبین و تعمیلی و آداب *مسترسدین* و ترغیب سائر ایشان علی وجه الاعتبار حثا\n- علی طاعة الله و ابتغاء علی مرضات الله که از جملۀ اعظم اسماء الله هوست و بفارسیه ذکر آرّه میگویند بر سبیل چهره علانیه بر ان استغال مینمایند کما طریقه\n- شرعاً و دلرا نرم گردانند زنگ و داغ و حجابهای آنرا بر دارد و وساوس دیو از حواسی سینه بعد سازد و سینه را *انسراحی* و دلرا انفتاحی و غافلانرا انتباهی\n- \n" }, { "alpha_fraction": 0.7442845106124878, "alphanum_fraction": 0.7442845106124878, "avg_line_length": 30.105262756347656, "blob_id": "b40f976d4db0ae5d120afb205991b80c5da2581e", "content_id": "99610f6b5eb97a45d48f5cdfa97c5c76231b79a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1939, "license_type": "no_license", "max_line_length": 89, "num_lines": 38, "path": "/ser560.md", "repo_name": "pickettj/jupyter_notebooks", "src_encoding": "UTF-8", "text": "---- \n\n> Model MarkDown document with new schema.\n\n# \n\n\\#\\# \n> top marginalia\n\n- جناب *عالیحضرتمولایم* الله ظله\n- جناب شریعت و شرافت امارت و وزارتپناهان\n- دام عافیتکم\n\n\\#\\# \n> vertical section\n> beginning of honorific section\n\n- روزی و نصیب آنشریعت و شرافت و وزارتپناهان\n- رفعت و منزلت جایگاهان دولت و حکومت و دستگاهان\n- بوده باد بعد از اظهار مراهم دعا بوده میدارت که\n- الله الحمد و المنه بمهربانی و شرفدولت خداداد ؟ مراتب حالات\n- قرین شکر و رضا بوده همواره سلامتی و تعالی\n- و عافیت مندی آنمرحمت پناهان مراعات\n\n\\#\\# \n> diagonal right section\n\n- بقیه السلام آنکه \n - آصف *مقامانا* چنانچه مهربانی خداندی\n- در کف های دعای از تحت رکوبی چیزی برامده همرنگ بدن ورم کرده \n> beginning of content\n- مدت دوازده روز میشود که از پای ما مانده است که جنبانیده تا بواسته خواب گردیم\n - چندین حکیمها آمده دیده *پاسخ* علاجی کرده نتوانستند عین وقت خدمت دولتخانه عالی\n- میباشد بنابران بخذمت ذی شفرها شان ؟ ؟ ؟ شد که اگر مهربانی نموده\n- دختور را فرستانند آمده بیند شاید که خداوند عالی او را بشرف دعا و توجه جنابهاشان\n - ؟ گردانیده دعای از ایندرو عافیت یافته زود تر در بالالی خذمت دولتخانه برایم\n- دیگر بدعا بوده از دعای اجابت قرینها شان امیدواریست زیاده آیام بکام ؟ دولت مدام باد باقی\n- السلام و الاکرام" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 50.25, "blob_id": "7550f6a0b9ed4953d8580047892e7b9f1d2cf171", "content_id": "008afb15fcaf47f0efb46ece4c0bd25ef8448d06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1820, "license_type": "no_license", "max_line_length": 91, "num_lines": 20, "path": "/ser596.md", "repo_name": "pickettj/jupyter_notebooks", "src_encoding": "UTF-8", "text": "\n---- \n\n- جناب عالیحضرت صاحبم مولایم سلمه الله\n- عرضه داشت کمترین دعاگویان رضاجوی *بیمقدار*\n- و ذرّه فروترین غلامان جانسپار فرمان بردار میرزا عبد *الباقی* رئیس\n- بجناب مستطاب بصد هزار عجز و آداب بامید کرم قبول اینکه بنده نوازا\n- غیجدوان بعرض عالی رسانده بوده اند که از روی تعامل *اشتر کیها*\n- انگشت ها شان را فروخته اشتر های خالی خود ها را بجایهای\n- کناره نگاه میداشتند الحال بعضی بدر سرای و دوکانیان\n- چوکانیده راه تنگ کرده فقرای راهگذارا تشویش میدهند\n----\n- امیدمیکنم ازینوجه مبارکنامه همایون عالیمولایم بنام اینغلام نادان\n- سراسر نقصان شرف صدور یافته بوده است که تحقیق نموده بینید چنین باشد\n- منع نموده بجایهای بیضرر تعین نموده میشود جهان پناها مبارکنامهً\n- عالیمولایم را دیده بوسیده بچشمان خود مالیده موافق مرحمت مولایم\n- بسر بازار مذکور بر آمده کلان خورد اهل بازار را جمع کرده پرسیدم که \n- واقعاً اشترهای خالی را به پیش دوکان های خالی را به پیش دوکانها نگاهداشته مسلمانان را تنگ\n- میکرده اند که از روی تعامل قدیم *بجا پهای* بیضرر مقرری تعین نموده از همه\n- اهل بازار بجنابملایم دعا گرفته از روی\n- نادانی عرض بندگی نمودم\n\n" }, { "alpha_fraction": 0.6323907375335693, "alphanum_fraction": 0.6491002440452576, "avg_line_length": 21.735294342041016, "blob_id": "113b54c12f066022227ac3faf186b8320ea31a45", "content_id": "01d0af7f8bb8c0bffb7b045c6fb07261e44cb7ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 84, "num_lines": 34, "path": "/archive/markdown_xml_parser.py", "repo_name": "pickettj/jupyter_notebooks", "src_encoding": "UTF-8", "text": "\n#Parser, Mark 1: XML conversion for custom mark-down used for document transcription\n\n\n\n#Use Regex to recognize patterns\n## There is an RE module for Regex expressions\n## to put what you are subbing inside what you are matching: \n### re.sub(r'^\\- (.*)$', r'<li>\\1</li>', '- qaaaaabcq')\n#### How does the regex \\1 work?\n\n\nimport re\n\n\nfile_name = 'ser560.md'\n\nf = open(file_name)\ntext_lines = f.readlines()\nf.close()\n\n\ntext_lines.insert(0, '<document>\\n')\ntext_lines.insert(1, '\\t<metadata>\\n')\ntext_lines.insert(2, '\\t\\t<unique_id>' + file_name + '</unique_id>\\n')\n\n\n#<unique_id>ser561</unique_id>\n\ntext_lines = [re.sub (r'^\\- (.*)$', r'<li>\\1</li>', x.lstrip()) for x in text_lines]\n\n\noutfile = open('parser_output.txt', 'w')\noutfile.writelines(text_lines)\noutfile.close()\n\n\n\n\n" }, { "alpha_fraction": 0.7326416373252869, "alphanum_fraction": 0.7693535685539246, "avg_line_length": 68.61111450195312, "blob_id": "11f49d34d789a5dc96deff90277a9006128de8cf", "content_id": "8fba06142981045e4952f443fe3df87a73bd789e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 199, "num_lines": 18, "path": "/README.md", "repo_name": "pickettj/jupyter_notebooks", "src_encoding": "UTF-8", "text": "# Python Lab\n\nTesting out various Python routines.\n\nUseful links:\n\n- [Guide to Pandas for Humanists](https://pandas.pythonhumanities.com/intro.html).\n- [Binder](https://mybinder.org/): Free site for using Git to host Jupyter notebooks for outside users (i.e. great for demoing).\n- Web scraping:\n - Mat Lavin [slides](https://docs.google.com/presentation/d/1JnMZbl7434RrzAHluKOT4OyUxCpln3B_7QYoSa01X0M/edit#slide=id.p) & [repo](https://github.com/mjlavin80/advanced-webscraping-pitt-february-2020)\n - [Method for mapping website lacking an index](https://www.freecodecamp.org/news/how-to-build-a-url-crawler-to-map-a-website-using-python-6a287be1da11/)\n- [Online Jupyter Notebooks for teaching purposes](https://github.com/iamlemec/data_science)\n\nPython3.8 is necessary for a number of new functions (notably the walrus operator), but it's a bit of a challenge to get it working with Jupyter:\n\n- First [create a new conda environment](https://stackoverflow.com/questions/58568175/upgrade-to-python-3-8-using-conda): `conda create -n python38 python=3.8`\n- Then install the new Python into the kernel: `python3.8 -m ipykernel install --user --name python38 --display-name \"Python 3.8\"`\n- It will be necessary to reinstall packages for the new environment.\n" } ]
5
aegena/fonts
https://github.com/aegena/fonts
b896929597e99aa71e8257a39614629308fce4f2
c723d2f04bc475384badd26954e4a31d8cd77634
5b0e2081f6c814c4db572094095d143897996bbb
refs/heads/master
2020-05-16T15:48:55.447640
2019-04-29T02:10:07
2019-04-29T02:10:07
183,143,880
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5820895433425903, "alphanum_fraction": 0.6328358054161072, "avg_line_length": 20, "blob_id": "19d677db748ee78c34c81018af62fc9f5a50491f", "content_id": "1a2efa50f95c70d6096dae1ce461a773f964a2c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/Python/chapter5/Python1.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "alien_0 = {'color': 'green', 'points': 5}\nprint(alien_0['color'])\nprint(alien_0['points'])\n\nalien_1 = {\"color\": \"green\", \"points\": 5}\nprint(alien_1['color'])\nprint(alien_1['points'])\n\nalien_0['x_position'] = 0\nalien_0['y_position'] = 2\nprint(alien_0)\nalien_0['color'] = 'Yellow'\nprint(alien_0)\n\ndel alien_0['y_position']\nprint(alien_0)" }, { "alpha_fraction": 0.6015037298202515, "alphanum_fraction": 0.7218044996261597, "avg_line_length": 18, "blob_id": "6fd2afab9ddff71ee33977bc9efd7b751330f8dc", "content_id": "ea8342b20e598a69de9a8276b4ab4f68e1e46a30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 23, "num_lines": 7, "path": "/Python/chapter3/Python2.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "dimensions = (200, 500)\nprint(dimensions[0])\nprint(dimensions[1])\n\ndimensions = (400, 500)\nprint(dimensions[0])\nprint(dimensions[1])\n" }, { "alpha_fraction": 0.5395188927650452, "alphanum_fraction": 0.5395188927650452, "avg_line_length": 21.384614944458008, "blob_id": "5a8cfaf982d57c3de5a00f99b50ebce1d1fc6f05", "content_id": "39fb32df2ad97b0e756858ef8cd2c1e05d0eb125", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 79, "num_lines": 13, "path": "/Python/chapter5/Python2.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "languages = {'jen': 'Python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}\n\nfor k, v in languages.items():\n print(str(k).title() + \" \" + str(v))\n\nfor k in languages.keys():\n print(k)\n\nprint(\"======= values =======\")\nfor v in languages.values():\n print(v)\n\n# set(values) 去重\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5880101919174194, "avg_line_length": 20.80555534362793, "blob_id": "4ec4cac9bfaeb80ca889e09153af18f41f10baa9", "content_id": "191b3cee5fe433a249347ee6a829754d669190f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 61, "num_lines": 36, "path": "/Python/chapter3/Python1.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "magicians = [\"alice\", \"david\", \"carolina\"]\nfor magicaian in magicians:\n print(magicaian)\nprint(\"--------------------\")\n\nfor item in magicians:\n print(item)\nprint(item.title())\n\nprint(\"==========number==========\")\n\nfor number in range(1, 5):\n print(number)\n\nprint(\"======number list=========\")\n\nnumbers = list(range(1, 5))\nprint(numbers)\nprint(len(numbers))\n\nprint(\"===== list 方差 =====\")\nsquares = [value**2 for value in range(1, 11)]\nprint(squares)\n\nprint(\"======= list 切片 =======\")\nplayers = ['charls', 'martina', 'michael', 'florence', 'eli']\nprint(players[0:3])\nprint(players[1:4])\nprint(players[-3:])\n\nprint(\"====== copy list ======\")\nmy_foods = ['pizza', 'falafel', 'carrot cake']\nfriend_foods = my_foods[:]\nmy_foods.append(\"hot dog\")\nprint(my_foods)\nprint(friend_foods)" }, { "alpha_fraction": 0.5854700803756714, "alphanum_fraction": 0.5854700803756714, "avg_line_length": 22.450000762939453, "blob_id": "cde8d4165a81c777371ab0c21f08b1191831636e", "content_id": "5fccc1059a7f89141de693873ef098cdd8d2c983", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/Python/chapter4/Python1.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "cars = ['audi', 'bmw', 'subaru', 'toyota']\nfor car in cars:\n if car == 'bmw':\n print(car.upper())\n else:\n print(car.title())\n\n# 多条件检查 and 和 or\n# 是否存在 in\n# 是否不存在 not in\n# if - elif - else\n\nprint(\"===== list empty ======\")\nrequested_topping = []\nif requested_topping:\n for requested in requested_topping:\n print(\"Adding \" + requested + \".\")\n print(\"\\n Finished making your pizza!\")\nelse:\n print(\"Are you sure you want a plain pizza?\")" }, { "alpha_fraction": 0.6835442781448364, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 17.230770111083984, "blob_id": "694796905a793c795bff6dbaef4cb066fab8c9ac", "content_id": "9dff718a466d86401949a679d5d953ecada61d7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 43, "num_lines": 13, "path": "/Python/chapter1/Python1.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "message = 'Aegena'\nprint(message)\nprint('Hello World')\n\nmessage = \"Hello Python Crash Course world\"\nprint(message)\n\nname = 'aegena cAmpanula'\nprint(name.title())\n\nfavorite_language = ' python '\nprint(favorite_language.lstrip())\nprint(4 * (2 + 3))\n" }, { "alpha_fraction": 0.7172414064407349, "alphanum_fraction": 0.7448275685310364, "avg_line_length": 18.772727966308594, "blob_id": "f3e250696d07ce8161204ddd170c5a6928ae6962", "content_id": "df7bccf6acbcc9cfae9a0c5f60070a7c0a47c35f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 53, "num_lines": 22, "path": "/Python/chapter2/Python1.py", "repo_name": "aegena/fonts", "src_encoding": "UTF-8", "text": "bicycles = ['trek', 'connondale', 1, 'redline', 23.3]\nprint(bicycles)\n\nbicycles[0] = 'waxberry4625'\nprint(bicycles)\nbicycles.append(\"Aegena\")\nprint(bicycles)\nbicycles.insert(1, \"campanula\")\nprint(bicycles)\n\ndel bicycles[2]\nprint(bicycles)\n\n\nmotorcycles = [\"honda\", \"yamaha\", \"suzuki\"]\nprint(motorcycles)\npoped_motorycles = motorcycles.pop(0)\nprint(poped_motorycles)\nprint(motorcycles)\n\nmotorcycles.remove(\"yamaha\")\nprint(motorcycles)\n" } ]
7
zakk196/sparta
https://github.com/zakk196/sparta
3c2df5af8d03cbc17a6a39aa63a72beb9a40934b
802a09bf720ff1ff3963241a0f499f017c7744c3
85f5130115eefeeee73c9a19965ea894eb9a1f8b
refs/heads/master
2023-08-14T00:17:49.044152
2021-09-15T18:15:17
2021-09-15T18:15:17
401,792,482
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6069767475128174, "alphanum_fraction": 0.6069767475128174, "avg_line_length": 27.66666603088379, "blob_id": "fbb67777263cb83f37fb057dec7abe65751c8bb4", "content_id": "acb513f688c21b706d7bb53fc6f0c4bb13e7b25c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 48, "num_lines": 15, "path": "/multiops.py", "repo_name": "zakk196/sparta", "src_encoding": "UTF-8", "text": "first_num = input(\"enter a number: \")\nsecond_num = input(\"enter a second number: \")\n\nfirst_num = int(first_num)\nsecond_num= int(second_num)\n\na = first_num + second_num\nb =first_num - second_num\nc = first_num * second_num\nd = first_num / second_num\n\nprint(first_num, \"+\", second_num, \"=\", a)\nprint(first_num, \"-\", second_num, \"=\", b)\nprint(first_num, \"*\", second_num, \"=\", c)\nprint(first_num, \"/\", second_num, \"=\", d)\n" }, { "alpha_fraction": 0.6268980503082275, "alphanum_fraction": 0.6339479684829712, "avg_line_length": 19.954545974731445, "blob_id": "56f35e6a28ae10a6f99edd52e100ab5354935020", "content_id": "9dc22bc6252be86768ade22754201edf69090820", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1844, "license_type": "no_license", "max_line_length": 91, "num_lines": 88, "path": "/hi.py", "repo_name": "zakk196/sparta", "src_encoding": "UTF-8", "text": "#import sys\n#import math\nimport re\n#from string import printable\npassword = (input(\" Enter your password: \"))\n\nlength = str(len(password))\npassword_length_good = False\n#working\nif len (password) < 8:\n print(\"[!] Password should be atleast 8 characters long\")\n print(\"[!] Password is only\", length, \"characters long\" )\n password_length_good = False;\n\nelse:\n print(\"(*) Your password is\", length, \"characters :) \")\n password_length_good = True;\n#\n\n# working\nUpperLength = len(re.findall(r'[A-Z]', password))\nprint(\"(*) Your password contains\", UpperLength, \"uppercase characters\")\n\nif UpperLength == 0:\n print(\"[!] Your password should have atleast 1 uppercase character!\")\n#\n\n#working\ndigits = len(re.findall(r'[0-9]', password))\nprint(\"(*) Your password contains\", digits, \"numeric digits\")\n\nif digits == 0:\n print(\"[!] Your password should have atleast 1 Number!\")\n#\n#working\ndef count_special_character(password):\n\n special_char= 0\n for i in range(0, len(password)):\n if (password[i].isalpha()):\n continue\n elif (password[i].isdigit()):\n continue\n else:\n special_char += 1\n if special_char >= 1:\n print(\"(*) You have {} Special Character/s in your password \".format(special_char))\n else:\n print(\"[!] Your password should have atleast 1 special character!\")\n\nif __name__ == '__main__' :\n string = password\n count_special_character(string)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#add common password code under here\n\n#matchedPass = False\n#commonPasswords = ['password','letmein','lemon']\n\n#for commonPass in commonPasswords:\n# if commonPass == password:\n# matchedPass == True\n# print(matchedPass)\n#\n# if matchedPass == True:\n# print(\"Your password is common !\")\n# else:\n# print(\"your password is not common\")\n" } ]
2
dmodena/projetoextensao
https://github.com/dmodena/projetoextensao
3beca1abd6ed798122ebeb9ab6d759280f152bf8
fbb44489ff95a51fc2205fa24ff016f07bf148c7
1e577f3b972d37617094bb44392ff19b2f60f38e
refs/heads/main
2021-08-15T22:12:09.821711
2018-03-22T16:55:34
2018-03-22T16:55:34
123,218,133
0
0
MIT
2018-02-28T02:35:44
2021-04-16T13:32:12
2021-06-10T18:56:00
Python
[ { "alpha_fraction": 0.6802859902381897, "alphanum_fraction": 0.6971399188041687, "avg_line_length": 38.95918273925781, "blob_id": "ca52075f3de0cc52806d8191a09f140a611d246c", "content_id": "2da09c3fff7d11fca45d3392ef8a529776f1f875", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1958, "license_type": "permissive", "max_line_length": 82, "num_lines": 49, "path": "/core/models.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\nclass Edital(models.Model):\n titulo = models.CharField(max_length = 100)\n descricao = models.TextField()\n inicio_inscricoes = models.DateField()\n fim_inscricoes = models.DateField()\n inicio_curso = models.DateField()\n fim_curso = models.DateField()\n vagas = models.IntegerField()\n pre_requisitos = models.TextField()\n edital_link = models.CharField(max_length = 100)\n carga_horaria = models.IntegerField(default = 1)\n cidade = models.CharField(max_length = 100)\n ativo = models.BooleanField(default = True)\n\n def __str__(self):\n return self.titulo\n\nclass Aluno(models.Model):\n nome = models.CharField(max_length = 100)\n logradouro = models.CharField(max_length = 100)\n numero = models.CharField(max_length = 10)\n complemento = models.TextField(blank = True, default = '')\n cep = models.CharField(max_length = 10)\n cidade = models.CharField(max_length = 100)\n estado = models.CharField(max_length = 2)\n rg = models.CharField(max_length = 20)\n cpf = models.CharField(unique = True, max_length = 20)\n email = models.CharField(max_length = 30)\n telefone = models.CharField(max_length = 20)\n nascimento = models.DateField()\n created_by = models.ForeignKey(User, null = True, on_delete = models.SET_NULL)\n ativo = models.BooleanField(default = True)\n\n def __str__(self):\n return self.nome\n\nclass Inscrito(models.Model):\n inscrito_em = models.DateTimeField(default = timezone.now)\n matriculado_em = models.DateTimeField(null = True)\n aprovado_em = models.DateTimeField(null = True)\n reprovado_em = models.DateTimeField(null = True)\n aluno = models.ForeignKey(Aluno, on_delete = models.CASCADE)\n edital = models.ForeignKey(Edital, on_delete = models.CASCADE)\n status = models.IntegerField(default = 0)\n observacoes = models.TextField()\n" }, { "alpha_fraction": 0.5379812717437744, "alphanum_fraction": 0.5535899996757507, "avg_line_length": 23.64102554321289, "blob_id": "40cda5bcfc2f9b586965d9430b752ee33f16dff1", "content_id": "d8c94b4e0823c1fe8e21d6c9cb6edf58c101c4d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "permissive", "max_line_length": 73, "num_lines": 39, "path": "/core/templatetags/custom_filters.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django import template\nregister = template.Library()\n\[email protected]\ndef date_mask(value):\n return value.strftime('%d/%m/%Y')\n\[email protected]\ndef datefull_mask(value):\n mes = \"\"\n if value.month == 1:\n mes = \"Janeiro\"\n elif value.month == 2:\n mes = \"Fevereiro\"\n elif value.month == 3:\n mes = \"Março\"\n elif value.month == 4:\n mes = \"Abril\"\n elif value.month == 5:\n mes = \"Maio\"\n elif value.month == 6:\n mes = \"Junho\"\n elif value.month == 7:\n mes = \"Julho\"\n elif value.month == 8:\n mes = \"Agosto\"\n elif value.month == 9:\n mes = \"Setembro\"\n elif value.month == 10:\n mes = \"Outubro\"\n elif value.month == 11:\n mes = \"Novembro\"\n elif value.month == 12:\n mes = \"Dezembro\"\n return value.strftime('%d de ') + str(mes) + value.strftime(' de %Y')\n\[email protected]\ndef datetime_mask(value):\n return value.strftime('%d/%m/%Y %H:%M')\n" }, { "alpha_fraction": 0.5450682640075684, "alphanum_fraction": 0.5596358180046082, "avg_line_length": 46.07143020629883, "blob_id": "4c147835bc5afa3348fa8d639497c5caac37f328", "content_id": "fa8b8f21a22d7cf090747ee0ffd034e3f2c6d3b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3295, "license_type": "permissive", "max_line_length": 136, "num_lines": 70, "path": "/core/migrations/0001_initial.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-03-15 16:16\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Aluno',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nome', models.CharField(max_length=100)),\n ('logradouro', models.CharField(max_length=100)),\n ('numero', models.CharField(max_length=10)),\n ('complemento', models.TextField(blank=True, default='')),\n ('cep', models.CharField(max_length=10)),\n ('cidade', models.CharField(max_length=100)),\n ('estado', models.CharField(max_length=2)),\n ('rg', models.CharField(max_length=20)),\n ('cpf', models.CharField(max_length=20, unique=True)),\n ('email', models.CharField(max_length=30)),\n ('telefone', models.CharField(max_length=20)),\n ('nascimento', models.DateField()),\n ('ativo', models.BooleanField(default=True)),\n ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Edital',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('titulo', models.CharField(max_length=100)),\n ('descricao', models.TextField()),\n ('inicio_inscricoes', models.DateField()),\n ('fim_inscricoes', models.DateField()),\n ('inicio_curso', models.DateField()),\n ('fim_curso', models.DateField()),\n ('vagas', models.IntegerField()),\n ('pre_requisitos', models.TextField()),\n ('edital_link', models.CharField(max_length=100)),\n ('carga_horaria', models.IntegerField(default=1)),\n ('cidade', models.CharField(max_length=100)),\n ('ativo', models.BooleanField(default=True)),\n ],\n ),\n migrations.CreateModel(\n name='Inscrito',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('inscrito_em', models.DateTimeField(default=django.utils.timezone.now)),\n ('matriculado_em', models.DateTimeField(null=True)),\n ('aprovado_em', models.DateTimeField(null=True)),\n ('reprovado_em', models.DateTimeField(null=True)),\n ('status', models.IntegerField(default=0)),\n ('observacoes', models.TextField()),\n ('aluno', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Aluno')),\n ('edital', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Edital')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5070422291755676, "alphanum_fraction": 0.7014084458351135, "avg_line_length": 15.904762268066406, "blob_id": "93261dd0d729e9e4fd6a640baf3c27b6501a5f27", "content_id": "387de42b5a6356a042e151f37d9309279a95ce05", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 355, "license_type": "permissive", "max_line_length": 29, "num_lines": 21, "path": "/requirements.txt", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "click==6.7\ndj-database-url==0.4.2\nDjango==2.0.2\ndjango-excel-response2==2.0.8\ndjango-six==1.0.4\ngunicorn==19.7.1\nJinja2==2.10\nlivereload==2.5.1\nMarkdown==2.6.9\nMarkupSafe==1.0\nmkdocs==0.17.2\npsycopg2==2.7.4\npython-decouple==3.1\npytz==2018.3\nPyYAML==3.12\nscreen==1.0.1\nsix==1.11.0\ntornado==4.5.2\nvirtualenv==15.1.0\nvirtualenvwrapper-win==1.2.1\nxlwt==1.3.0\n" }, { "alpha_fraction": 0.7014925479888916, "alphanum_fraction": 0.7014925479888916, "avg_line_length": 49.82758712768555, "blob_id": "0c9d4c73bd829f40c77602eaa10ef2a90c0efe0d", "content_id": "f3d1db8244b843c9c4f9dad6fe08cf74b6e40946", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "permissive", "max_line_length": 97, "num_lines": 29, "path": "/core/urls.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom core import views\n\nurlpatterns = [\n path('', views.r_editais),\n\n path('editais/', views.editais, name='editais'),\n path('editais/novo/', views.edital_create, name='editais/novo'),\n path('editais/editar/<id>', views.edital_edit, name='editais/editar'),\n path('editais/excluir/<id>', views.edital_remove, name='editais/excluir'),\n\n path('alunos/', views.alunos, name='alunos'),\n path('alunos/novo/', views.aluno_create, name='alunos/novo'),\n path('alunos/editar/<id>', views.aluno_edit, name='alunos/editar'),\n\n path('inscricoes/', views.inscricoes, name='inscricoes'),\n path('inscricoes/edital/<id>', views.inscricoes_edital, name='inscricoes/edital'),\n path('inscricoes/aluno/', views.inscricoes_aluno, name='inscricoes/aluno'),\n path('inscricoes/edital/novo/<id>', views.inscricoes_create, name='inscricao/nova'),\n path('inscricoes/matricular/<id>', views.inscricoes_matricular, name='inscricao/matricular'),\n path('inscricoes/cancelar/<id>', views.inscricoes_cancelar, name='inscricao/cancelar'),\n path('inscricoes/aprovar/<id>', views.inscricoes_aprovar, name='inscricao/aprovar'),\n path('inscricoes/reprovar/<id>', views.inscricoes_reprovar, name='inscricao/reprovar'),\n path('inscricoes/excluir/<id>', views.inscricoes_remove, name='inscricao/excluir'),\n\n path('certificados/<id>', views.certificado, name='certificado'),\n\n path('registrar/', views.signup, name='registrar'),\n]\n" }, { "alpha_fraction": 0.6817840337753296, "alphanum_fraction": 0.6826850771903992, "avg_line_length": 40.10493850708008, "blob_id": "5b70260637278e05c6b5d2936f1df96bf3268510", "content_id": "b49a29bca201adb3a79737d18de5565d40be6cf6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6673, "license_type": "permissive", "max_line_length": 198, "num_lines": 162, "path": "/core/views.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom core.models import Edital, Aluno, Inscrito\nfrom core.forms import EditalForm, AlunoForm\nfrom core.utils import static_files_url\nfrom django.utils import timezone\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.forms import UserCreationForm\n# from django.core.email import send_email\n\ndef home(request):\n return render(request, 'core/index.html')\n\ndef editais(request, mensagem = None):\n editais = Edital.objects.all().order_by('-id')\n return render(request, 'core/editais/lista.html', {'editais': editais, 'mensagem': mensagem, 'static_url': static_files_url})\n\ndef r_editais(request):\n return redirect(editais)\n\ndef edital_create(request):\n form = EditalForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid() and request.user.is_staff:\n form.save()\n return redirect(editais)\n return render(request, 'core/editais/novo.html', {'form': form, 'static_url': static_files_url})\n\ndef edital_edit(request, id):\n edital = Edital.objects.get(id=id)\n form = EditalForm(request.POST or None, instance = edital)\n if form.is_valid() and request.user.is_staff:\n form.save()\n return redirect(editais)\n return render(request, 'core/editais/novo.html', {'form': form, 'static_url': static_files_url})\n\ndef edital_remove(request, id):\n edital = Edital.objects.get(id=id)\n if request.user.is_staff:\n edital.delete()\n return redirect(editais)\n\ndef alunos(request):\n if request.user.is_authenticated:\n if request.user.is_staff:\n alunos = Aluno.objects.all().order_by('nome')\n else:\n alunos = Aluno.objects.all().filter(created_by=request.user)\n return render(request, 'core/alunos/lista.html', {'alunos':alunos, 'static_url': static_files_url})\n return redirect(editais)\n\ndef aluno_create(request):\n form = AlunoForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid() and request.user.is_authenticated:\n aluno = form.save()\n aluno.created_by = request.user\n aluno.save()\n return redirect(alunos)\n return render(request, 'core/alunos/novo.html', {'form': form, 'static_url': static_files_url})\n\ndef aluno_edit(request, id):\n aluno = Aluno.objects.get(id=id)\n form = AlunoForm(request.POST or None, instance = aluno)\n if form.is_valid() and request.user.is_authenticated:\n form.save()\n return redirect(alunos)\n return render(request, 'core/alunos/novo.html', {'form': form, 'static_url': static_files_url})\n\ndef inscricoes(request):\n editais = Edital.objects.all().order_by('titulo')\n return render(request, 'core/inscricoes/lista.html', {'editais': editais, 'static_url': static_files_url})\n\ndef inscricoes_edital(request, id):\n edital = Edital.objects.get(id=id)\n inscritos = Inscrito.objects.filter(edital=edital).order_by('inscrito_em')\n return render(request, 'core/inscricoes/edital.html', {'inscritos': inscritos, 'static_url': static_files_url})\n\ndef inscricoes_aluno(request):\n aluno = Aluno.objects.get(created_by=request.user)\n inscritos = Inscrito.objects.filter(aluno=aluno).order_by('inscrito_em')\n return render(request, 'core/inscricoes/aluno.html', {'inscritos': inscritos, 'static_url': static_files_url})\n\ndef inscricoes_create(request, id):\n edital = Edital.objects.get(id=id)\n aluno = Aluno.objects.get(created_by=request.user)\n if aluno == None:\n return redirect(editais)\n qtd_inscricoes = Inscrito.objects.filter(aluno=aluno, edital=edital).count()\n if qtd_inscricoes > 0:\n mensagem = \"Aluno já inscrito!\"\n return editais(request, mensagem)\n inscrito = Inscrito()\n inscrito.aluno = aluno\n inscrito.edital = edital\n inscrito.status = 1\n inscrito.save()\n mensagem = \"Inscrição realizada com sucesso!\"\n # send_email('SisExtensão - Inscrição em curso', 'Obrigado por se inscrever em um de nosso cursos! Aguarde a confirmação de sua matrícula.', '[email protected]', [inscrito.email])\n return editais(request, mensagem)\n\ndef inscricoes_matricular(request, id):\n inscrito = Inscrito.objects.get(id=id)\n edital = inscrito.edital\n inscrito.status = 2\n inscrito.matriculado_em = timezone.now()\n inscrito.save()\n # send_email('SisExtensão - Matrícula em curso', 'Parabéns! Você foi selecionado para iniciar seu curso! Entre em contato com o Campus para realizar sua matrícula.', '[email protected]', [inscrito.email])\n return redirect('inscricoes/edital', id=edital.id)\n\ndef inscricoes_cancelar(request, id):\n inscrito = Inscrito.objects.get(id=id)\n edital = inscrito.edital\n inscrito.status = 1\n inscrito.matriculado_em = None\n inscrito.save()\n return redirect('inscricoes/edital', id=edital.id)\n\ndef inscricoes_aprovar(request, id):\n inscrito = Inscrito.objects.get(id=id)\n edital = inscrito.edital\n inscrito.status = 3\n inscrito.aprovado_em = timezone.now()\n inscrito.save()\n return redirect('inscricoes/edital', id=edital.id)\n\ndef inscricoes_reprovar(request, id):\n inscrito = Inscrito.objects.get(id=id)\n edital = inscrito.edital\n inscrito.status = 4\n inscrito.reprovado_em = timezone.now()\n inscrito.save()\n return redirect('inscricoes/edital', id=edital.id)\n\ndef inscricoes_remove(request, id):\n inscrito = Inscrito.objects.get(id=id)\n inscrito.delete()\n return redirect('inscricoes/aluno')\n\ndef certificado(request, id):\n inscrito = Inscrito.objects.get(id=id)\n edital = Edital.objects.get(id=inscrito.edital.id)\n aluno = Aluno.objects.get(id=inscrito.aluno.id)\n return render(request, 'core/certificados/certificado.html', {'inscrito': inscrito, 'edital': edital, 'aluno': aluno, 'static_url': static_files_url})\n\ndef signup(request):\n if request.method == 'POST':\n form_user = UserCreationForm(request.POST)\n form_aluno = AlunoForm(request.POST)\n if form_user.is_valid() and form_aluno.is_valid():\n usuario = form_user.save()\n aluno = form_aluno.save()\n aluno.created_by = usuario\n aluno.save()\n username = form_user.cleaned_data.get('username')\n raw_password = form_user.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect(editais)\n else:\n form_user = UserCreationForm()\n form_aluno = AlunoForm()\n return render(request, 'core/signup.html', {'form_user': form_user, 'form_aluno': form_aluno, 'static_url': static_files_url})\n" }, { "alpha_fraction": 0.7523364424705505, "alphanum_fraction": 0.7523364424705505, "avg_line_length": 22.77777862548828, "blob_id": "405a58d18b68bf40dd1ec02647a33d92d6d317b1", "content_id": "c55b7fe42f41c9314a758c9a1f087e5b19aa67c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "permissive", "max_line_length": 45, "num_lines": 9, "path": "/projetoextensao/settings/dev.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from projetoextensao.settings.base import *\nfrom decouple import config\n\nDEBUG = True\nALLOWED_HOSTS = []\nSECRET_KEY = config('SECRET_KEY')\n\n# Base url for static files\nSTATIC_FILES_URL = config('STATIC_FILES_URL')\n" }, { "alpha_fraction": 0.7684210538864136, "alphanum_fraction": 0.7684210538864136, "avg_line_length": 22.75, "blob_id": "c45d4367cd0ae24cc5e158b39d8ae45b0602cb5e", "content_id": "6e4e8e64ea6a83b1fbc6aa7a78acc58741254bef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/core/utils.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\ndef static_files_url():\n return settings.STATIC_FILES_URL\n" }, { "alpha_fraction": 0.7575757503509521, "alphanum_fraction": 0.7575757503509521, "avg_line_length": 28.700000762939453, "blob_id": "02d900226a6093606898470f58468482c86744c0", "content_id": "600153cbbf4076a80babe9bd46e5df54c06e852f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "permissive", "max_line_length": 49, "num_lines": 10, "path": "/projetoextensao/settings/prod.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from projetoextensao.settings.base import *\nimport dj_database_url\n\nDEBUG = False\nALLOWED_HOSTS = ['projetoextensao.herokuapp.com']\nSECRET_KEY = os.environ['DJANGO_KEY']\nDATABASES['default'] = dj_database_url.config()\n\n# Base url for static files\nSTATIC_FILES_URL = os.environ['STATIC_FILES_URL']\n" }, { "alpha_fraction": 0.5649867653846741, "alphanum_fraction": 0.5921750664710999, "avg_line_length": 26.418182373046875, "blob_id": "40ac50fca9f01b29f425c24eb5d116ec43c33914", "content_id": "8932a573a305c73da287482c47c0279146b1410e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1512, "license_type": "permissive", "max_line_length": 296, "num_lines": 55, "path": "/core/templates/core/certificados/certificado.html", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "{% load custom_filters %}\n\n<!doctype html>\n<html>\n<head>\n <title></title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css\" integrity=\"sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">\n <style>\n img {\n display: block;\n margin: 2em auto;\n }\n\n p {\n margin: 2em 0;\n }\n\n h1 {\n margin-top: 1em;\n text-align: center;\n }\n\n h2 {\n text-align: center;\n color: #A0BBB5;\n }\n </style>\n</head>\n<body>\n <main class=\"container\" style=\"max-width: 880px;\">\n <div>\n <img src=\"{{static_url}}img/logo_ifsp.jpg\" width=\"150\" height=\"100\" />\n </div>\n <div>\n <h1>CERTIFICADO</h1>\n </div>\n <div>\n <h2>{{ aluno.nome }}</h2>\n </div>\n <div>\n <p>\n Concluiu o curso de Extensão <strong>{{edital.titulo}}</strong>, com carga horária total de <strong>{{edital.carga_horaria}} horas</strong>, oferecido pelo IFSP no Câmpus {{edital.cidade}}, no período de <strong>{{edital.inicio_curso|date_mask}} a {{edital.fim_curso|date_mask}}</strong>.\n </p>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <img src=\"https://dms-space.ams3.digitaloceanspaces.com/web-assets/projetoextensao/static/img/assinatura1.png\" width=\"350\" height=\"200\" />\n </div>\n <div class=\"col\">\n <img src=\"https://dms-space.ams3.digitaloceanspaces.com/web-assets/projetoextensao/static/img/assinatura2.png\" width=\"350\" height=\"200\" />\n </div>\n </div>\n </main>\n</body>\n</html>\n" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 45, "blob_id": "4c61cf56e9b1010ac24cdfe9dde32f505779c2a9", "content_id": "fc687a7310b368676b19d3a7034f85a5e3ded707", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "permissive", "max_line_length": 186, "num_lines": 14, "path": "/core/forms.py", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\nfrom core.models import Edital, Aluno\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass EditalForm(ModelForm):\n class Meta:\n model = Edital\n fields = ['titulo', 'descricao', 'inicio_inscricoes', 'fim_inscricoes', 'inicio_curso', 'fim_curso', 'vagas', 'pre_requisitos', 'edital_link', 'carga_horaria', 'cidade', 'ativo']\n\nclass AlunoForm(ModelForm):\n class Meta:\n model = Aluno\n fields = ['nome', 'logradouro', 'numero', 'complemento', 'cep', 'cidade', 'estado', 'rg', 'cpf', 'email', 'telefone', 'nascimento', 'ativo']\n" }, { "alpha_fraction": 0.735029935836792, "alphanum_fraction": 0.779940128326416, "avg_line_length": 50.38461685180664, "blob_id": "9e24ae51824066202ce64e26d52067d5dbd1e3d9", "content_id": "d22734aa74987e47deba1230b60fc87fd55e2f4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 676, "license_type": "permissive", "max_line_length": 220, "num_lines": 13, "path": "/README.md", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "projetoextensao\n===============\n![version](https://img.shields.io/github/tag/dmodena/projetoextensao.svg)\n![license](https://img.shields.io/github/license/dmodena/projetoextensao.svg)\n![build](https://travis-ci.org/dmodena/projetoextensao.svg?branch=master)\n\nSistema de Gerenciamento de Cursos de Extensão, submetido como Trabalho de Conclusão de Curso no ano de 2017 para graduação em Tecnlogia em Análise e Desenvolvimento de Sistemas pelo Instituto Federal, campus Araraquara.\n\nA documentação do projeto de pesquisa pode ser acessado através [deste link](https://drive.ifsp.edu.br/s/b2cbfce106d941f9e6859e67ab759bfb?path=%2F2017).\n\n---\n\nDouglas Modena - 2018 - MIT License\n" }, { "alpha_fraction": 0.5055288076400757, "alphanum_fraction": 0.5083640217781067, "avg_line_length": 30.491071701049805, "blob_id": "04f06a44603969d03deae0bbee95502b0da2e11e", "content_id": "ca37b6618fd42eaab4959eda080353236b92de4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3532, "license_type": "permissive", "max_line_length": 183, "num_lines": 112, "path": "/core/templates/core/editais/lista.html", "repo_name": "dmodena/projetoextensao", "src_encoding": "UTF-8", "text": "{% extends 'core/base.html' %}\n{% load custom_filters %}\n\n{% block content %}\n\n{% if mensagem != None %}\n<div class=\"alert alert-dark alert-dismissible fade show\" role=\"alert\">\n {{mensagem}}\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n</div>\n{% endif %}\n\n{% if request.user.is_superuser%}\n<span>Loading time: </span><span>{{tempo}}</span>\n{% endif %}\n\n <nav aria-label=\"breadcrumb\" role=\"navigation\">\n <ol class=\"breadcrumb breadcrumb-dark\">\n <li class=\"breadcrumb-item\"><a href=\"{% url 'editais' %}\">SisExtensão</a></li>\n <li class=\"breadcrumb-item active\" aria-current=\"page\">Editais</li>\n </ol>\n </nav>\n\n <h2>Editais</h2>\n <div class=\"input-group\">\n <span class=\"input-group-addon\" id=\"buscalbl\">Busca</span>\n <input id=\"busca\" type=\"text\" onkeyup=\"buscaEditais()\" class=\"form-control\" placeholder=\"Digite para filtrar\" autofocus=\"autofocus\" aria-label=\"busca\" aria-describedby=\"buscalbl\">\n </div>\n <hr />\n\n {% if request.user.is_staff %}\n <a href=\"{% url 'editais/novo' %}\" class=\"btn btn-primary\">Novo Edital</a>\n {% endif %}\n <br />\n\n\n {% for edital in editais %}\n <div class=\"card\" style=\"margin-top: 1em; margin-bottom: 1em;\">\n {% if edital.ativo %}\n <div class=\"card-body\">\n {% else %}\n <div class=\"card-body text-dark\">\n {% endif %}\n <h2>{{edital.titulo}}</h2>\n\n <div class=\"row\">\n <div class=\"col\">\n <p class=\"lead\">\n {{edital.descricao}}\n </p>\n </div>\n </div>\n <br />\n <div class=\"row\">\n <div class=\"col\">\n <p>\n <strong>Inscrições: </strong>\n <span>de {{edital.inicio_inscricoes|date_mask}} a {{edital.fim_inscricoes|date_mask}}</span>\n </p>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <p>\n <strong>Período de curso: </strong>\n <span>de {{edital.inicio_curso|date_mask}} a {{edital.fim_curso|date_mask}}</span>\n </p>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <p>\n <strong>Quantidade de vagas: </strong><span>{{edital.vagas}}</span>\n </p>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <strong>Pré-requisitos: </strong>\n <blockquote>{{edital.pre_requisitos}}</blockquote>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col\">\n <p>\n <strong>Ver edital completo: </strong><span><a href=\"{{edital.edital_link}}\" target=\"_blank\">Link para edital</a></span>\n </p>\n </div>\n </div>\n\n {% if request.user.is_authenticated %}\n <div class=\"row\">\n {% if request.user.is_staff %}\n <div class=\"col-sm-4 offset-sm-8\">\n <a href=\"{% url 'editais/editar' edital.id %}\" class=\"btn btn-info\">Editar</a>\n <a href=\"{% url 'editais/excluir' edital.id %}\" class=\"btn btn-danger\">Excluir</a>\n </div>\n {% else %}\n {% if edital.ativo %}\n <div class=\"col-sm-3 offset-sm-9\">\n <a href=\"{% url 'inscricao/nova' edital.id %}\" class=\"btn btn-secondary\">Inscrever-se</a>\n </div>\n {% endif %}\n {% endif %}\n </div>\n {% endif %}\n </div>\n </div>\n {% endfor %}\n{% endblock %}\n" } ]
13
cramshaw/twunfollowr
https://github.com/cramshaw/twunfollowr
ea880c055208d974877d3cc2e85606f37c17bd7b
b44c7f36ab4cffba65548e10a6ce1df999dcdb73
15164c4952ec7c347d737d59cd699fe289fe7e94
refs/heads/master
2021-01-10T13:18:26.041295
2016-02-09T15:59:28
2016-02-09T15:59:28
49,969,421
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.573610246181488, "alphanum_fraction": 0.5784972310066223, "avg_line_length": 33.84042739868164, "blob_id": "4a58e8a0f1102ac795a595261278f859ca11761c", "content_id": "2e573f14da3d422eb0c9cd1e15fe77085e5cb425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3274, "license_type": "no_license", "max_line_length": 195, "num_lines": 94, "path": "/main.py", "repo_name": "cramshaw/twunfollowr", "src_encoding": "UTF-8", "text": "import sys, os\nimport pickle\n\nfrom time import sleep, ctime\nfrom random import randint\n\nimport tweepy\n\nTWITTER_CONSUMER_KEY = os.environ['TWITTER_CONSUMER_KEY']\nTWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']\nTWITTER_ACCESS_TOKEN = os.environ['TWITTER_ACCESS_TOKEN']\nTWITTER_ACCESS_TOKEN_SECRET = os.environ['TWITTER_ACCESS_TOKEN_SECRET']\n\nclass Followr:\n\n def __init__(self, target):\n self.target = target\n self.auth = self.make_auth()\n self.api = tweepy.API(self.auth)\n print(self.api.rate_limit_status())\n self.followers = list()\n self.following = list()\n self.followed = list()\n self.failed_follows = list()\n self.recently_followed = list()\n self.count = 0\n\n def make_auth(self):\n auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)\n auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)\n return auth\n\n def run(self):\n self.load_last_followed()\n self.get_current_followers()\n self.get_current_following()\n self.remove_useless()\n self.follow()\n self.save_changes()\n\n def get_current_followers(self):\n self.followers = self.api.followers_ids()\n print(self.followers)\n\n def get_current_following(self):\n self.following = self.api.friends_ids()\n print(self.following)\n\n def follow(self):\n try:\n for target in self.api.followers_ids(screen_name=self.target):\n if self.count < 75:\n if target not in self.followers and target not in self.following and target not in self.recently_followed and target not in self.failed_follows and target != self.api.me().id:\n print('Following', target)\n self.api.create_friendship(target)\n sleep(randint(0,50))\n self.followed.append(target)\n print(\"FOLLOWED\", target)\n self.count += 1\n print(self.count)\n else:\n return\n except:\n print(\"rate limit hit, sleeping for 900 seconds\", ctime())\n sleep(900)\n\n def save_changes(self):\n with open('follow.txt', 'wb') as fhand:\n pickle.dump(self.followed, fhand)\n print('saved follows')\n with open('failed_follows.txt', 'wb') as fhand:\n pickle.dump(self.failed_follows, fhand)\n print('saved failed follows')\n\n\n def load_last_followed(self):\n with open('follow.txt', 'rb') as fhand:\n self.recently_followed = pickle.load(fhand)\n with open('failed_follows.txt', 'rb') as fhand:\n self.failed_follows = pickle.load(fhand)\n\n def remove_useless(self):\n for user in self.recently_followed:\n if user not in self.followers:\n self.failed_follows.append(user)\n sleep(randint(0,30))\n try:\n self.api.destroy_friendship(user)\n print('unfollowed', user)\n except:\n print(user, \"couldn't be unfollowed - CHECK IT OUT\")\n\nif __name__ == \"__main__\":\n Followr(\"RUFC_FanApp\").run()" }, { "alpha_fraction": 0.7834274768829346, "alphanum_fraction": 0.7834274768829346, "avg_line_length": 28.55555534362793, "blob_id": "d3a65936ac6ecb5fef3a305cd742486b88a3958c", "content_id": "5360a8ec332660637af1c4baeb006ed4ccdaf52f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 531, "license_type": "no_license", "max_line_length": 103, "num_lines": 18, "path": "/README.md", "repo_name": "cramshaw/twunfollowr", "src_encoding": "UTF-8", "text": "# twunfollowr\n\nA short program designed to help build Twitter followings.\n\nEnter the username or id of a user who has followers you'd like to target.\n\nRun the program.\n\nNumber of users to follow at one time can be altered, as can number of days to wait before an unfollow.\n\nSet your Twitter API keys as environment variables in a file called export-keys.\n\nSomething like this:\n\nexport TWITTER_CONSUMER_KEY=\"xx-yy\"\nexport TWITTER_CONSUMER_SECRET=\"xx-yy\"\nexport TWITTER_ACCESS_TOKEN=\"xx-yy\"\nexport TWITTER_ACCESS_TOKEN_SECRET=\"xx-yy\"" } ]
2
Zuoway/redfin_crawler
https://github.com/Zuoway/redfin_crawler
3481dc95baa02f3e8e23b2f0c8ceab2fd0220b6f
a24bf49fcfb854f7a14d72915c222ee12a02f12c
57e80762fe83b6f783940147b70adcc082206368
refs/heads/master
2020-04-28T02:56:57.921852
2019-03-11T03:18:46
2019-03-11T03:18:46
174,917,403
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6602563858032227, "alphanum_fraction": 0.6618589758872986, "avg_line_length": 31.0256404876709, "blob_id": "35e40fc9df505d028d7024125e797bb1b0d7ba76", "content_id": "eebcc480a6f0688001e695c79e82f63b2e3006e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 91, "num_lines": 39, "path": "/Redfin/pipelines.py", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n'''Can use pymysql client to upload item directly to MySQL DB.\nOr simply take stored json file into mysql within mysql shell\nAs a proof of concept project, not implemented yet.\n\nFor coding challenge purposes, currently exporting file into .csv format\n'''\n\n# from scrapy.exporters import JsonItemExporter\nfrom scrapy.exporters import CsvItemExporter\n\nclass RedfinPipeline(object):\n # def __init__(self):\n # self.file = open('data.json', 'wb')\n # self.exporter = JsonItemExporter(self.file, encoding='utf-8', ensure_ascii=False)\n # self.exporter.start_exporting()\n\n # def close_spider(self, spider):\n # self.exporter.finish_exporting()\n # self.file.close()\n\n # def process_item(self, item, spider):\n # self.exporter.export_item(item)\n # return item\n\n def __init__(self):\n #Write csv to Result folder\n self.file = open(\"Result/redfin_zhuowei.csv\", 'wb')\n self.exporter = CsvItemExporter(self.file)\n self.exporter.start_exporting()\n\n def close_spider(self, spider):\n self.exporter.finish_exporting()\n self.file.close()\n\n def process_item(self, item, spider):\n self.exporter.export_item(item)\n return item" }, { "alpha_fraction": 0.5436144471168518, "alphanum_fraction": 0.5595180988311768, "avg_line_length": 42.25, "blob_id": "46b303bb15670b689581f82a6f77a5f8ccdfd162", "content_id": "33637590ae2bc1db0d09f56a9a633650629018a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2075, "license_type": "no_license", "max_line_length": 156, "num_lines": 48, "path": "/Redfin/spiders/redfin_crawler.py", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nimport csv\nimport re\nimport random\nfrom Redfin.items import RedfinItem\n\nclass RedfinCrawlerSpider(scrapy.Spider):\n name = 'redfin_crawler'\n allowed_domains = ['redfin.com']\n\n '''start requests by looping through all valid zipcodes on redfin,\n generate links by zipcode'''\n def start_requests(self):\n with open(\"all_postal_codes.txt\") as f:\n for zipcode in f:\n zipcode = zipcode.rstrip('\\n')\n url = 'https://www.redfin.com/zipcode/' + zipcode\n yield scrapy.Request(url=url, callback=self.get_csv_url)\n\n '''parse and go to download_csv link. Some zipcode may not have it visible,\n use manual link construction can still find it'''\n def get_csv_url(self, response):\n regionId = re.search(r\"regionId=(.+?)&\",response.text).group(1)\n csv_url = 'https://www.redfin.com/stingray/api/gis-csv?al=1&region_id='+regionId+'&region_type=2&sold_within_days=180&status=9&uipt=1,2,3,4,5,6&v=8'\n return scrapy.Request(url=csv_url,callback=self.parse_csv) \n\n '''parse the result csv to item pipeline'''\n def parse_csv(self, response):\n all_items = response.body.decode().split('\\n')\n for index, line in enumerate(all_items): \n if index != 0 and line:\n fields = next(csv.reader(line.splitlines(), skipinitialspace=True))\n item = RedfinItem()\n item['sold_date'] = fields[1]\n item['property_type'] = fields[2]\n item['address'] = fields[3] \n item['city'] = fields[4]\n item['state'] = fields[5] \n item['zipcode'] = fields[6] \n item['price'] = fields[7] \n item['beds'] = fields[8]\n item['baths'] = fields[9]\n item['square_feet'] = fields[11]\n item['lot_size'] = fields[12]\n item['year_built'] = fields[13]\n item['days_on_market'] = fields[14]\n yield item" }, { "alpha_fraction": 0.5871056318283081, "alphanum_fraction": 0.588477373123169, "avg_line_length": 27.076923370361328, "blob_id": "c077c81254277c59f7481ed37560c746af621394", "content_id": "10d4adc4b5827c461bd590b32851c877f0a0e403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 51, "num_lines": 26, "path": "/Redfin/items.py", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass RedfinItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n sold_date = scrapy.Field()\n property_type = scrapy.Field()\n address = scrapy.Field() \n city = scrapy.Field() \n state = scrapy.Field() \n zipcode = scrapy.Field() \n price = scrapy.Field() \n beds = scrapy.Field() \n baths = scrapy.Field()\n square_feet = scrapy.Field()\n lot_size = scrapy.Field()\n year_built = scrapy.Field()\n days_on_market = scrapy.Field()" }, { "alpha_fraction": 0.7512908577919006, "alphanum_fraction": 0.7564544081687927, "avg_line_length": 37.733333587646484, "blob_id": "4cfb5b37a35ca0f69ced8171a461839fff756795", "content_id": "8a6ef556087825363eb740977c6fbff85941f440", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 362, "num_lines": 30, "path": "/README.md", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "# Redfin Crawler\n\nThis is a python3 and Scrapy based crawler on Redfin.com. It automatically gather information of properties sold within last 6 months across the US. The information includes:\n - Address\n - City\n - State\n - Zipcode\n - Sold Date\n - Property Type\n - Price\n - Year Built\n - Square ft.\n - Lot Size\n - Bath\n - Beds\n - Days on Market\n\n### Implementation\n\nComments are available in source code. A couple approaches is used for anti-banning, including limiting concurrent request per domain, delaying downloading for 1 sec, and disabling cookies. Rotating ip-proxy, and rotating user agent modules are used. The ip proxy module is not activated in this build due to limited reliability and availability of free proxies.\n\n### To Run The Crawler (for Lofty)\n\n```sh\n$ docker run -v /home/LoftyCode/InternResults:/usr/src/app/Result zhuang02/redfin:1\n```\n\nAfter initiating, the console outputs crawler information and running states. A .csv file will be generated within a desired folder during crawling. \n\nOne can type <kbd>CTRL</kbd>+<kbd>C</kbd> to abort crawling prematurely and still be able to see partial .csv file for testing purposes.\n" }, { "alpha_fraction": 0.8947368264198303, "alphanum_fraction": 0.8947368264198303, "avg_line_length": 13.5, "blob_id": "c4d747d0af690b63ee202aeea1d88e2f5d1dfe36", "content_id": "86041bc79b24698002c32c588b41627afc034fe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 57, "license_type": "no_license", "max_line_length": 23, "num_lines": 4, "path": "/requirements.txt", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "Scrapy\nscrapy-useragents\nscrapy-rotating-proxies\nrequests" }, { "alpha_fraction": 0.621052622795105, "alphanum_fraction": 0.6421052813529968, "avg_line_length": 23, "blob_id": "e3b2d619a881f98f8141893ca355f907b0e91870", "content_id": "9429220cb2371e4637b5a3cf1441f99d47be87db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 95, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/Dockerfile", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "FROM python:3-onbuild\nWORKDIR /usr/src/app\nCOPY . .\nCMD [ \"python3\", \"-u\", \"./Redfin/main.py\" ]" }, { "alpha_fraction": 0.6244634985923767, "alphanum_fraction": 0.6319742202758789, "avg_line_length": 33.55555725097656, "blob_id": "f9e0ab17621da097da3442dda58602899dea709f", "content_id": "5a174eed4b496d274f1d4b4829d02d6d10922108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 932, "license_type": "no_license", "max_line_length": 96, "num_lines": 27, "path": "/Redfin/main.py", "repo_name": "Zuoway/redfin_crawler", "src_encoding": "UTF-8", "text": "import scrapy.cmdline\nimport requests\nfrom lxml.html import fromstring\n\n'''\nA method to scrape free publicly available proxies used to crawl. Unutilized at the moment due\nto unreliability of public proxies sources (retrying dead proxies and abandoning them slows down\ncrawling speed drastically) \n'''\n\ndef get_proxies():\n url = 'https://free-proxy-list.net/'\n response = requests.get(url)\n parser = fromstring(response.text)\n proxies = []\n for i in parser.xpath('//tbody/tr')[:10]:\n if i.xpath('.//td[5][contains(text(),\"elite proxy\")]'):\n proxy = \":\".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]])\n proxies.append(proxy)\n with open('proxies.txt', 'w') as f:\n for proxy in proxies:\n f.write(proxy+'\\n')\n\nif __name__ == '__main__':\n # generate proxy list\n # get_proxies()\n scrapy.cmdline.execute(argv=['scrapy','crawl','redfin_crawler'])" } ]
7
michoemad/Tenner-sudoko-variation-Solver
https://github.com/michoemad/Tenner-sudoko-variation-Solver
cedc8a9bc0761dd11e81c909c5fae80fec20be9c
35ccde60be42a08e3137ce32f4705ee6e2cb3bef
31a33a7345ce110acf50613f0dbb27bd4de1bc29
refs/heads/master
2021-01-19T14:46:07.263468
2017-03-29T23:54:12
2017-03-29T23:54:12
86,639,017
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49984291195869446, "alphanum_fraction": 0.5213111042976379, "avg_line_length": 36.2578125, "blob_id": "f0a6b558b2d8a373ddabcb27687a6a4d429eb1f8", "content_id": "685a36614b0ee452b513619e15b77d8ea2808f2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9549, "license_type": "no_license", "max_line_length": 88, "num_lines": 256, "path": "/tenner_csp.py", "repo_name": "michoemad/Tenner-sudoko-variation-Solver", "src_encoding": "UTF-8", "text": "#Look for #IMPLEMENT tags in this file. These tags indicate what has\n#to be implemented to complete the warehouse domain. \n\n'''\nConstruct and return Tenner Grid CSP models.\n'''\n\nfrom cspbase import *\nimport itertools\n\n\n\n# this creates an array of tuples\ndef all_pairs(V1,V2):\n out = [] # will be array of tuples\n for d1 in V1.domain():\n for d2 in V2.domain():\n if (d1 != d2):\n out.append((d1,d2))\n return out\n\ndef tenner_csp_model_1(initial_tenner_board):\n '''Return a CSP object representing a Tenner Grid CSP problem along \n with an array of variables for the problem. That is return\n\n tenner_csp, variable_array\n\n where tenner_csp is a csp representing tenner grid using model_1\n and variable_array is a list of lists\n\n [ [ ]\n [ ]\n .\n .\n .\n [ ] ]\n\n such that variable_array[i][j] is the Variable (object) that\n you built to represent the value to be placed in cell i,j of\n the Tenner Grid (only including the first n rows, indexed from \n (0,0) to (n,9)) where n can be 3 to 8.\n \n \n The input board is specified as a pair (n_grid, last_row). \n The first element in the pair is a list of n length-10 lists.\n Each of the n lists represents a row of the grid. \n If a -1 is in the list it represents an empty cell. \n Otherwise if a number between 0--9 is in the list then this represents a \n pre-set board position. E.g., the board\n \n --------------------- \n |6| |1|5|7| | | |3| |\n | |9|7| | |2|1| | | |\n | | | | | |0| | | |1|\n | |9| |0|7| |3|5|4| |\n |6| | |5| |0| | | | |\n ---------------------\n would be represented by the list of lists\n \n [[6, -1, 1, 5, 7, -1, -1, -1, 3, -1],\n [-1, 9, 7, -1, -1, 2, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, 0, -1, -1, -1, 1],\n [-1, 9, -1, 0, 7, -1, 3, 5, 4, -1],\n [6, -1, -1, 5, -1, 0, -1, -1, -1,-1]]\n \n \n This routine returns model_1 which consists of a variable for\n each cell of the board, with domain equal to {0-9} if the board\n has a -1 at that position, and domain equal {i} if the board has\n a fixed number i at that cell.\n \n model_1 contains BINARY CONSTRAINTS OF NOT-EQUAL between\n all relevant variables (e.g., all pairs of variables in the\n same row, etc.).\n model_1 also constains n-nary constraints of sum constraints for each \n column.\n '''\n \n #INITIALIZE VARS\n G,LR = initial_tenner_board\n #print(\"LR \",LR)\n V_array = [[0 for x in range(10)] for j in range(len(G))] # N of rows\n #print(V_array)\n #V_array[3][0] = 2000\n for i in range(len(G)):\n for j in range(10):\n if G[i][j] == -1: # domain should be 0-9\n V = Variable(str(i) + ' '+str(j),[x for x in range(10)])\n V_array[i][j] = V\n else:\n # print(i,j)\n V = Variable(str(i) + ' '+str(j),[G[i][j]]) #Domain is what's there\n V.assign(G[i][j])\n V_array[i][j] = V\n CS = CSP(\"Tenner Model 1\",[V_array[z][y] for z in range(len(G)) for y in range(10)])\n # DO constraints\n #Start with differences\n N = len(G)\n for i in range(N):\n for j in range(10):\n #ADJ VER\n if i!= (N-1):\n C = Constraint(\"ADJ_VERT\",[V_array[i][j],V_array[i+1][j]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j]))\n CS.add_constraint(C)\n # ADJ DIAG\n if ((i!= (N-1)) and (j!= 9)):\n C = Constraint(\"DIAG\",[V_array[i][j],V_array[i+1][j+1]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j+1]))\n CS.add_constraint(C)\n #DIAG OTHER SIDE\n if ( (i!= (N-1)) and (j!= 0)):\n C = Constraint(\"DIAG\",[V_array[i][j],V_array[i+1][j-1]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j-1]))\n CS.add_constraint(C)\n #THIS DEALS WITH ROW CONSTRAINTS\n for k in range(j+1,10):\n C = Constraint(\"ROWS\",[V_array[i][j],V_array[i][k]])\n # ADD ALL POSSIBLE VALUES\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i][k]))\n CS.add_constraint(C)\n #SUM CONSTRAINT\n #GEN FUNCTION\n\n for I in range(10): # I Is column number\n #GEN_ALL(LR[I],[],0)\n L= [V_array[x][I].cur_domain() for x in range(N)]\n #print(L)\n C = Constraint(\"Sum of Col \" + str(I),[V_array[i][I] for i in range(N)])\n for P in itertools.product(*L):\n if sum(P) == LR[I]:\n #print(P,LR[I])\n C.add_satisfying_tuples([P])\n CS.add_constraint(C)\n \n #print(\"mamatsh\")\n # Now we have all the possibilityes\n return CS,V_array\n \n \n##############################\n\ndef tenner_csp_model_2(initial_tenner_board):\n \n '''Return a CSP object representing a Tenner Grid CSP problem along \n with an array of variables for the problem. That is return\n\n tenner_csp, variable_array\n\n where tenner_csp is a csp representing tenner using model_1\n and variable_array is a list of lists\n\n [ [ ]\n [ ]\n .\n .\n .\n [ ] ]\n\n such that variable_array[i][j] is the Variable (object) that\n you built to represent the value to be placed in cell i,j of\n the Tenner Grid (only including the first n rows, indexed from \n (0,0) to (n,9)) where n can be 3 to 8.\n\n The input board takes the same input format (a list of n length-10 lists\n specifying the board as tenner_csp_model_1.\n \n The variables of model_2 are the same as for model_1: a variable\n for each cell of the board, with domain equal to {0-9} if the\n board has a -1 at that position, and domain equal {i} if the board\n has a fixed number i at that cell.\n\n However, model_2 has different constraints. In particular,\n model_2 has a combination of n-nary \n all-different constraints and binary not-equal constraints: all-different \n constraints for the variables in each row, binary constraints for \n contiguous cells (including diagonally contiguous cells), and n-nary sum \n constraints for each column. \n Each n-ary all-different constraint has more than two variables (some of \n these variables will have a single value in their domain). \n model_2 should create these all-different constraints between the relevant \n variables.\n '''\n #INITIALIZE VARS\n G,LR = initial_tenner_board\n #print(\"LR \",LR)\n V_array = [[0 for x in range(10)] for j in range(len(G))] # N of rows\n #print(V_array)\n #V_array[3][0] = 2000\n for i in range(len(G)):\n for j in range(10):\n if G[i][j] == -1: # domain should be 0-9\n V = Variable(str(i) + ' '+str(j),[x for x in range(10)])\n V_array[i][j] = V\n else:\n # print(i,j)\n V = Variable(str(i) + ' '+str(j),[G[i][j]]) #Domain is what's there\n V.assign(G[i][j])\n V_array[i][j] = V\n CS = CSP(\"Tenner Model 2\",[V_array[z][y] for z in range(len(G)) for y in range(10)])\n # DO constraints\n #Start with differences\n N = len(G)\n # function that generates all possible rows given domains, j specifies column\n # i=0, I may uncomment this\n POSSIB = []\n def all_rows(j,L):\n #print(j,L)\n if (j==10):\n POSSIB.append(tuple(L))\n return\n for d in V_array[i][j].domain():\n if ((d not in L) and (j<=9)): # check that the domain is not in row already\n L.append(d)\n all_rows(j+1,L)\n L.pop()\n return\n for i in range(N):\n all_rows(0,[]) # GENERATE ALL POSSIBLE ROWS (N-ARY)\n C = Constraint(\"ROW_N-ARY of \" + str(i),[V_array[i][k] for k in range(10)])\n C.add_satisfying_tuples(POSSIB)\n #print(POSSIB)\n CS.add_constraint(C)\n POSSIB = []\n for j in range(10):\n #ADJ VER\n if i!= (N-1):\n C = Constraint(\"ADJ_VERT\",[V_array[i][j],V_array[i+1][j]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j]))\n CS.add_constraint(C)\n # ADJ DIAG\n if ((i!= (N-1)) and (j!= 9)):\n C = Constraint(\"DIAG\",[V_array[i][j],V_array[i+1][j+1]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j+1]))\n CS.add_constraint(C)\n #DIAG OTHER SIDE\n if ( (i!= (N-1)) and (j!= 0)):\n C = Constraint(\"DIAG\",[V_array[i][j],V_array[i+1][j-1]])\n C.add_satisfying_tuples(all_pairs(V_array[i][j],V_array[i+1][j-1]))\n CS.add_constraint(C)\n \n #SUM CONSTRAINT\n #GEN FUNCTION\n for I in range(10): # I Is column number\n #GEN_ALL(LR[I],[],0)\n L= [V_array[x][I].cur_domain() for x in range(N)]\n #print(L)\n C = Constraint(\"Sum of Col \" + str(I),[V_array[i][I] for i in range(N)])\n for P in itertools.product(*L):\n if sum(P) == LR[I]:\n #print(P,LR[I])\n C.add_satisfying_tuples([P])\n CS.add_constraint(C)\n \n \n return CS,V_array\n \n\n\n" }, { "alpha_fraction": 0.7814207673072815, "alphanum_fraction": 0.7978141903877258, "avg_line_length": 60, "blob_id": "fdae312690539f09365901ccffeca8235951f12c", "content_id": "6496b053e228d4c7bcb04b4f8325468e25d85b7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 183, "license_type": "no_license", "max_line_length": 118, "num_lines": 3, "path": "/README.md", "repo_name": "michoemad/Tenner-sudoko-variation-Solver", "src_encoding": "UTF-8", "text": "# Tenner\n* The project main focal points are implementing constraint propagation algorithms along with CSP models for the game \n* This program is a part of the CSC 384 course at UofT\n" } ]
2
wbolster/earnest
https://github.com/wbolster/earnest
a4ac972202fdb49229fcab1e9f1baad6cfacd426
51b8d4cb05313e5a929b4753114fb63bdb5fbb12
b8e81fc4ba49c73f9ede62a912ea9606608c90c3
refs/heads/master
2023-06-20T12:15:26.795108
2017-10-25T16:08:31
2017-10-25T16:08:31
32,686,094
0
3
null
null
null
null
null
[ { "alpha_fraction": 0.6556291580200195, "alphanum_fraction": 0.6887417435646057, "avg_line_length": 15.777777671813965, "blob_id": "41acd260a51b0daab6b46b4f773f633bc5e77b26", "content_id": "fccc31a42b0f8422fb4ac7d981be98f874cd1740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 151, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/tox.ini", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "[tox]\nenvlist = py27,py34\n\n[testenv]\ndeps =\n -rrequirements-test.txt\ncommands =\n py.test --cov {envsitepackagesdir}/earnest {posargs}\n flake8\n" }, { "alpha_fraction": 0.7126436829566956, "alphanum_fraction": 0.7126436829566956, "avg_line_length": 23.85714340209961, "blob_id": "c6fc29af1a39d3cad882359c0ec1c3c402ef6d6b", "content_id": "6e774df05787262ecb3d0dd921ae243c73d7b56b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 174, "license_type": "no_license", "max_line_length": 89, "num_lines": 7, "path": "/README.rst", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "=======\nearnest\n=======\n\nPython utilities for working with nested data structures.\n\nNote: *this repo is obsolete!* Have a look at https://github.com/wbolster/sanest instead.\n" }, { "alpha_fraction": 0.6233766078948975, "alphanum_fraction": 0.6233766078948975, "avg_line_length": 18, "blob_id": "54132ac0034702f4b2401c6bdb454e560899ecb0", "content_id": "fd7103728dbf1f7bb104a898dad955e40448b574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "no_license", "max_line_length": 46, "num_lines": 4, "path": "/earnest/__init__.py", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "\nfrom .earnest import ( # noqa: unused imports\n lookup_path,\n walk,\n)\n" }, { "alpha_fraction": 0.5981308221817017, "alphanum_fraction": 0.6261682510375977, "avg_line_length": 14.285714149475098, "blob_id": "4a474e2ee7d7e648abe46bb01b488602cf810794", "content_id": "e2977377298e3cc7644dc0d4973873f7579fd5c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 28, "num_lines": 7, "path": "/setup.py", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='earnest',\n version='0.0.1a',\n packages=['earnest'],\n)\n" }, { "alpha_fraction": 0.5872781276702881, "alphanum_fraction": 0.5887573957443237, "avg_line_length": 21.915254592895508, "blob_id": "657bb146e5c3d7dc3fa777ab0d29e3fb279176cd", "content_id": "bdf990e387c672293e3abae301730428aaf1f7e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 59, "num_lines": 59, "path": "/earnest/earnest.py", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "try:\n # Python 3\n from functools import reduce\n STRING_TYPE = str\nexcept ImportError:\n # Python 2\n STRING_TYPE = basestring # noqa\n\n\n_SENTINEL = object()\n\n\ndef walk(obj, parent_first=True):\n\n # Top down?\n if parent_first:\n yield (), obj\n\n # For nested objects, the key is the path component.\n if isinstance(obj, dict):\n children = obj.items()\n\n # For nested lists, the position is the path component.\n elif isinstance(obj, (list, tuple)):\n children = enumerate(obj)\n\n # Scalar values have no children.\n else:\n children = []\n\n # Recurse into children\n for key, value in children:\n for child_path, child in walk(value, parent_first):\n yield (key,) + child_path, child\n\n # Bottom up?\n if not parent_first:\n yield (), obj\n\n\ndef lookup_path(obj, path, default=_SENTINEL):\n\n if isinstance(path, STRING_TYPE):\n path = path.split('.')\n\n # Convert integer components into real integers.\n for position, component in enumerate(path):\n try:\n path[position] = int(component)\n except ValueError:\n pass\n\n try:\n return reduce(lambda x, y: x[y], path, obj)\n except (IndexError, KeyError, TypeError):\n if default is _SENTINEL:\n raise\n\n return default\n" }, { "alpha_fraction": 0.583242654800415, "alphanum_fraction": 0.5952121615409851, "avg_line_length": 22.538461685180664, "blob_id": "f852b4abbf5ebcf208d96a868bc86a5c711fc66e", "content_id": "846a77321b83be4ca151114f3be1fcdbce96db3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 919, "license_type": "no_license", "max_line_length": 73, "num_lines": 39, "path": "/test_earnest.py", "repo_name": "wbolster/earnest", "src_encoding": "UTF-8", "text": "\nimport pytest\n\nimport earnest\n\n\[email protected]()\ndef sample_object():\n return dict(\n a=1,\n b=2,\n c=['c1', 'c2'],\n d=dict(nested=[1, dict(foo='bar', baz={})]),\n )\n\n\ndef test_walk(sample_object):\n import pprint\n\n pprint.pprint(sample_object)\n print()\n\n for path, obj in earnest.walk(sample_object, parent_first=True):\n print('.'.join(map(str, path)))\n print(obj)\n print()\n\n\ndef test_lookup_path(sample_object):\n\n lookup_path = earnest.lookup_path\n assert lookup_path(sample_object, ['a']) == 1\n assert lookup_path(sample_object, 'a') == 1\n assert lookup_path(sample_object, ['d', 'nested', 1, 'foo']) == 'bar'\n assert lookup_path(sample_object, 'd.nested.1.foo') == 'bar'\n\n with pytest.raises(KeyError):\n lookup_path(sample_object, 'd.nested.1.too-bad')\n\n assert lookup_path(sample_object, 'd.nested.1.too-bad', 'x') == 'x'\n" } ]
6
ycc9135/PlaneWar
https://github.com/ycc9135/PlaneWar
3126d70b1c55dbbb237bd1901247833eaa25d352
3ccce76b946f289498b4904b272927c9cf13945a
2e511e858dd612c5374f94fa2cb3105179de3fe5
refs/heads/master
2020-07-28T00:19:42.312456
2019-09-20T07:32:21
2019-09-20T07:32:21
209,253,249
0
0
null
2019-09-18T08:06:06
2019-09-19T07:53:52
2019-09-20T07:32:22
Python
[ { "alpha_fraction": 0.5153061151504517, "alphanum_fraction": 0.5221088528633118, "avg_line_length": 26, "blob_id": "9eed3934041a28c2d0956cf93ca69f7c54235451", "content_id": "0a759011526a92ece37b7957a6aff9298d32fcf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/StoneGe.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "from PlaneWar.Stone import *\r\nimport random as r\r\n\r\n\r\nclass StoneGe:\r\n def __init__(self, map, totalNum, frameNum):\r\n self.totalNum = totalNum\r\n self.stones = []\r\n self.frameNum = frameNum\r\n self.n = 0\r\n self.map = map\r\n\r\n def run(self):\r\n self.n += 1\r\n if self.n >= self.frameNum and len(self.stones) < self.totalNum:\r\n stone = Stone()\r\n\r\n x, y = r.randint(-stone.dleft, self.map.w - 1 - stone.dright), -stone.dtop\r\n stone.setxy(x, y)\r\n self.stones.append(stone)\r\n self.n = 0\r\n" }, { "alpha_fraction": 0.4193548262119293, "alphanum_fraction": 0.44372761249542236, "avg_line_length": 27.0625, "blob_id": "a4b371853f04258a2426168c92790338a48b073e", "content_id": "1e209b41a1200cbc345c0ea83be99772c9e994c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1395, "license_type": "no_license", "max_line_length": 69, "num_lines": 48, "path": "/Plane.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "from PlaneWar.Shape import *\r\nfrom PlaneWar.Bullet import *\r\n\r\n\r\nclass Plane(Shape):\r\n def __init__(self, cd):\r\n super(Plane, self).__init__(2, 0, 0, [\r\n (0, 0),\r\n (0, -1),\r\n (0, -2),\r\n (0, -3),\r\n (-1, 0),\r\n (1, 0),\r\n (-1, -2),\r\n (-2, -2),\r\n (1, -2),\r\n (2, -2),\r\n (-2, -3),\r\n (2, -3)\r\n ])\r\n self.bullets = []\r\n self.alive = True\r\n self.cd = cd\r\n self.fireN = cd\r\n self.speed = 1\r\n\r\n def goleft(self, map):\r\n if self.checkOutOfMap(self.x - self.speed, self.y, map) == 0:\r\n self.setxy(self.x - self.speed, self.y)\r\n\r\n def goright(self, map):\r\n if self.checkOutOfMap(self.x + self.speed, self.y, map) == 0:\r\n self.setxy(self.x + self.speed, self.y)\r\n\r\n def goup(self, map):\r\n if self.checkOutOfMap(self.x, self.y - self.speed, map) == 0:\r\n self.setxy(self.x, self.y - self.speed)\r\n\r\n def godown(self, map):\r\n if self.checkOutOfMap(self.x, self.y + self.speed, map) == 0:\r\n self.setxy(self.x, self.y + self.speed)\r\n\r\n def fire(self):\r\n if self.fireN >= self.cd:\r\n bullet = Bullet()\r\n bullet.setxy(self.x, self.y + self.dtop - 1)\r\n self.bullets.append(bullet)\r\n self.fireN = 0\r\n" }, { "alpha_fraction": 0.3277978301048279, "alphanum_fraction": 0.3364620804786682, "avg_line_length": 29.477272033691406, "blob_id": "0a6e0f70232e660208848cc1fc40096ef4c66eb2", "content_id": "275975b7fc4b8bfdd997540b57fded72504984d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 56, "num_lines": 44, "path": "/Map.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "import pygame as pg\r\nfrom PlaneWar.Colors import *\r\n\r\n\r\nclass Map:\r\n def __init__(self, screen, width, height, cellSize):\r\n self.data = []\r\n self.screen = screen\r\n self.cellSize = cellSize\r\n self.w = int(width / cellSize)\r\n self.h = int(height / cellSize)\r\n\r\n for i in range(self.h):\r\n lineData = [[0] for _ in range(self.w)]\r\n self.data.append(lineData)\r\n\r\n def draw(self):\r\n for i in range(self.h):\r\n for j in range(self.w):\r\n d = self.data[i][j][0]\r\n if d != 0:\r\n c = BLACK\r\n # c = 1\r\n if d == 1:\r\n c = WHITE\r\n elif d == 2:\r\n c = BLUE\r\n elif d == 3:\r\n c = RED\r\n\r\n elif d == 4:\r\n c = DeepPink\r\n elif d == 5:\r\n c = DarkMagenta\r\n elif d == 6:\r\n c = DoderBlue\r\n elif d == 7:\r\n c = DarkRed\r\n pg.draw.rect(self.screen, c, (\r\n j * self.cellSize,\r\n i * self.cellSize,\r\n self.cellSize,\r\n self.cellSize\r\n ), 0)\r\n" }, { "alpha_fraction": 0.4797297418117523, "alphanum_fraction": 0.48479729890823364, "avg_line_length": 24.909090042114258, "blob_id": "5f38fca1f24b6466b92250d0667ca1f06a45224c", "content_id": "ca97916d4763ca43ec2dd80364e8ce836472592a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/Store.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "import random as r\r\n\r\n\r\nclass Store:\r\n def __init__(self, maxNum):\r\n # 一条记忆:环境,动作,奖励,下一个环境\r\n self.stores = []\r\n self.maxNum = maxNum\r\n self.curIndex = 0\r\n\r\n def add(self, s, a, r, s_):\r\n if len(self.stores) == self.maxNum:\r\n self.stores[self.curIndex] = [s, a, r, s_]\r\n self.curIndex += 1\r\n if self.curIndex == self.maxNum:\r\n self.curIndex = 0\r\n else:\r\n self.stores.append([s, a, r, s_])\r\n\r\n def sample(self, batch):\r\n res = r.sample(self.stores, batch)\r\n return res\r\n" }, { "alpha_fraction": 0.35961538553237915, "alphanum_fraction": 0.44294872879981995, "avg_line_length": 26.88888931274414, "blob_id": "fe1c0ba8fc8deb1f584619fd9267c16838a58882", "content_id": "0de6fc0017e97e683554880aa0144d76be8e46b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1560, "license_type": "no_license", "max_line_length": 59, "num_lines": 54, "path": "/ML.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "import torch as t\r\nimport torch.nn as nn\r\n\r\n\r\nclass A(nn.Module):\r\n def __init__(self):\r\n super(A, self).__init__()\r\n self.cnn = nn.Sequential(\r\n nn.Conv2d(2, 32, 3, 1, 1), # 40,60,2\r\n nn.MaxPool2d(2, 2), # 40,60,32\r\n nn.LeakyReLU(), # 20,30,32\r\n\r\n nn.Conv2d(32, 64, 3, 1, 1),\r\n nn.MaxPool2d(2, 2), # 20,30,64\r\n nn.LeakyReLU(), # 10,15,64\r\n\r\n nn.Conv2d(64, 128, 3, 1, 1),\r\n nn.MaxPool2d(2, 2), # 10,15,128\r\n nn.LeakyReLU(), # 5,7,128\r\n )\r\n self.fc = nn.Sequential(\r\n nn.Linear(4480, 1024),\r\n nn.LeakyReLU(),\r\n nn.Linear(1024, 128),\r\n nn.LeakyReLU(),\r\n nn.Linear(128, 64),\r\n nn.LeakyReLU(),\r\n nn.Linear(64, 5),\r\n nn.Softmax()\r\n )\r\n self.opt = t.optim.Adam(self.parameters(), lr=1e-3)\r\n self.mls = nn.MSELoss()\r\n\r\n def forward(self, inputs):\r\n out = self.cnn(inputs)\r\n out = out.view(out.size(0), -1)\r\n out = self.fc(out)\r\n return out\r\n\r\n\r\nclass C(nn.Module):\r\n def __init__(self):\r\n super(C, self).__init__()\r\n self.fc = nn.Sequential(\r\n nn.Linear(4805, 4000),\r\n nn.LeakyReLU(),\r\n nn.Linear(4000, 1000),\r\n nn.LeakyReLU(),\r\n nn.Linear(1000, 500),\r\n nn.LeakyReLU(),\r\n nn.Linear(500, 1)\r\n )\r\n self.opt = t.optim.Adam(self.parameters(), lr=1e-3)\r\n self.mls = nn.MSELoss()\r\n" }, { "alpha_fraction": 0.3181818127632141, "alphanum_fraction": 0.5681818127632141, "avg_line_length": 17.81818199157715, "blob_id": "d3861f3c4e57bbf4e130c675c4d2a91a3d336e16", "content_id": "420d3b352ad30b6ba0ca8422c0111b688f924324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 29, "num_lines": 11, "path": "/Colors.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "WHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nRED = (255, 0, 0)\r\nGREEN = (0, 255, 0)\r\nBLUE = (0, 0, 255)\r\n\r\n\r\nDeepPink=(255,20,147)#深粉色\r\nDarkMagenta=(139,0,139)#\t深洋红色\r\nDoderBlue=(30,144,255)#道奇蓝\r\nDarkRed=(139,0,0)#\t深红色\r\n\r\n" }, { "alpha_fraction": 0.3629310429096222, "alphanum_fraction": 0.3939655125141144, "avg_line_length": 27, "blob_id": "3e3596cf46f5742d42698ae02a351774c4939406", "content_id": "9463eb07896a25243d564df4114379c1c4c843bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1160, "license_type": "no_license", "max_line_length": 65, "num_lines": 40, "path": "/Stone.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "from PlaneWar.Shape import *\r\nimport random as r\r\nimport random\r\n\r\n\r\nclass Stone(Shape):\r\n def __init__(self):\r\n super(Stone, self).__init__(random.randint(3,7), 0, 0, [\r\n (0, 0),\r\n (0, -1),\r\n (0, 1),\r\n (1, 0),\r\n (-1, 0),\r\n ])\r\n self.dir = r.randint(1, 3)\r\n\r\n def move(self, map):\r\n if self.dir == 1:\r\n omp = self.checkOutOfMap(self.x - 1, self.y + 1, map)\r\n if omp == 1:\r\n self.dir = 3\r\n elif omp == 4:\r\n return False\r\n else:\r\n self.setxy(self.x - 1, self.y + 1)\r\n elif self.dir == 2:\r\n omp = self.checkOutOfMap(self.x, self.y + 1, map)\r\n if omp == 4:\r\n return False\r\n else:\r\n self.setxy(self.x, self.y + 1)\r\n elif self.dir == 3:\r\n omp = self.checkOutOfMap(self.x + 1, self.y + 1, map)\r\n if omp == 3:\r\n self.dir = 1\r\n elif omp == 4:\r\n return False\r\n else:\r\n self.setxy(self.x + 1, self.y + 1)\r\n return True\r\n" }, { "alpha_fraction": 0.44222360849380493, "alphanum_fraction": 0.46221113204956055, "avg_line_length": 26.589284896850586, "blob_id": "d33939784abc4fd91826d04d53cff97d104c0c44", "content_id": "46e043e1f34a0fc886693038016a17c0aacdc7a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1601, "license_type": "no_license", "max_line_length": 74, "num_lines": 56, "path": "/Shape.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "class Shape:\r\n def __init__(self, shapeType, x, y, dertCellList): # [(0,-1),(1,0)]\r\n self.x = x\r\n self.y = y\r\n self.dertCellList = dertCellList\r\n self.shapeType = shapeType\r\n self.dtop = 9999\r\n self.dbottom = -9999\r\n self.dleft = 9999\r\n self.dright = -9999\r\n for a, b in dertCellList:\r\n if a > self.dright:\r\n self.dright = a\r\n if a < self.dleft:\r\n self.dleft = a\r\n if b > self.dbottom:\r\n self.dbottom = b\r\n if b < self.dtop:\r\n self.dtop = b\r\n\r\n def getCellList(self):\r\n return [(x[0] + self.x, x[1] + self.y) for x in self.dertCellList]\r\n\r\n def putInMap(self, map):\r\n cellList = self.getCellList()\r\n for x, y in cellList:\r\n map.data[y][x][0] = self.shapeType\r\n\r\n def removeFromMap(self, map):\r\n cellList = self.getCellList()\r\n for x, y in cellList:\r\n map.data[y][x][0] = 0\r\n\r\n def setxy(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def checkOutOfMap(self, x, y, map):\r\n if x + self.dleft < 0:\r\n return 1\r\n elif x + self.dright >= map.w:\r\n return 3\r\n elif y + self.dtop < 0:\r\n return 2\r\n elif y + self.dbottom >= map.h:\r\n return 4\r\n else:\r\n return 0\r\n\r\n def checkAABB(self, other):\r\n scl = self.getCellList()\r\n ocl = other.getCellList()\r\n for xy in scl:\r\n if xy in ocl:\r\n return True\r\n return False\r\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 12, "blob_id": "34f61232ce69b905ce79c675f0cdbcf73e312eae", "content_id": "42fb1e327b93ee41740e793c0b6bbd2e7afb0cc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/README.md", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "# PlaneWar\nPython实训--飞机大战\n" }, { "alpha_fraction": 0.5050504803657532, "alphanum_fraction": 0.5353535413742065, "avg_line_length": 31, "blob_id": "3a37394675c18376964fb32b3f47f471893c8822", "content_id": "01ce36e224060b38583b250222c6f928abbfcc48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 69, "num_lines": 6, "path": "/Tools.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "def getInputs(map1, map2, h, w):\r\n inputs = []\r\n for i in range(h):\r\n lineData = [[map1[i][j][0], map2[i][j][0]] for j in range(w)]\r\n inputs.append(lineData)\r\n return inputs\r\n" }, { "alpha_fraction": 0.5206122398376465, "alphanum_fraction": 0.5381632447242737, "avg_line_length": 21.90243911743164, "blob_id": "74c70fe9183dbfc6669ca340cf201fff745487ef", "content_id": "3e1789438a17310661efeabe27ba2ea1a464b405", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5298, "license_type": "no_license", "max_line_length": 99, "num_lines": 205, "path": "/Main.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "from PlaneWar.Plane import *\r\nfrom PlaneWar.Map import *\r\nfrom pygame.locals import *\r\nfrom PlaneWar.Stone import *\r\nfrom PlaneWar.Bullet import *\r\nfrom PlaneWar.StoneGe import *\r\nimport sys\r\nimport copy\r\nfrom PlaneWar.Tools import *\r\nfrom PlaneWar.ML import *\r\nimport torch as t\r\nfrom PlaneWar.Store import *\r\nimport numpy as np\r\n\r\nsize = width, height = 400, 600\r\nscreen = pg.display.set_mode(size)\r\npg.display.set_caption('飞机大战')\r\npg.init()\r\n\r\nclock = pg.time.Clock()\r\n\r\n_map = Map(screen, width, height, 10)\r\nstoneGe = StoneGe(_map, 5, 10)\r\nplayer = Plane(5)\r\nplayer.setxy(20, 50)\r\nscore = 0\r\n\r\nfontBig = pg.font.SysFont('楷体', 50)\r\nfontSmall = pg.font.SysFont('楷体', 24)\r\n\r\nperScore = 1 # 打死一个加一分\r\n\r\n\r\ndef playerCtrl():\r\n key_press = pg.key.get_pressed()\r\n if key_press[K_a]:\r\n player.goleft(_map)\r\n elif key_press[K_d]:\r\n player.goright(_map)\r\n if key_press[K_w]:\r\n player.goup(_map)\r\n elif key_press[K_s]:\r\n player.godown(_map)\r\n if key_press[K_j]:\r\n player.fire()\r\n\r\n\r\ndef AICtrl(mo):\r\n if mo == 0:\r\n player.goleft(_map)\r\n elif mo == 1:\r\n player.goright(_map)\r\n if mo == 2:\r\n player.goup(_map)\r\n elif mo == 3:\r\n player.godown(_map)\r\n if mo == 4:\r\n player.fire()\r\n\r\n\r\ndef replay():\r\n global score\r\n player.alive = True\r\n player.setxy(20, 50)\r\n player.fireN = player.cd\r\n stoneGe.stones.clear()\r\n player.bullets.clear()\r\n stoneGe.n = 0\r\n score = 0\r\n\r\n\r\ndef exit():\r\n for event in pg.event.get():\r\n if event.type == QUIT:\r\n sys.exit()\r\n\r\n\r\ndef koutu():\r\n for b in player.bullets:\r\n b.removeFromMap(_map)\r\n for s in stoneGe.stones:\r\n s.removeFromMap(_map)\r\n if player.alive:\r\n player.removeFromMap(_map)\r\n\r\n\r\ndef otherAct():\r\n global score\r\n for b in player.bullets:\r\n res = b.move(_map)\r\n if not res:\r\n player.bullets.remove(b)\r\n for s in stoneGe.stones:\r\n res = s.move(_map)\r\n if not res:\r\n stoneGe.stones.remove(s)\r\n for b in player.bullets:\r\n for s in stoneGe.stones:\r\n if b.checkAABB(s):\r\n player.bullets.remove(b)\r\n stoneGe.stones.remove(s)\r\n score += perScore # 分数累加\r\n break\r\n\r\n\r\ndef putInMap():\r\n for b in player.bullets:\r\n b.putInMap(_map)\r\n for s in stoneGe.stones:\r\n s.putInMap(_map)\r\n if player.alive:\r\n player.putInMap(_map)\r\n\r\n\r\nlastMap = None\r\naNet = A()\r\ncNet = C()\r\nstore = Store(100)\r\nwhile True:\r\n exit()\r\n stoneGe.run()\r\n\r\n # 做动作前\r\n if lastMap is None:\r\n map1 = copy.deepcopy(_map.data)\r\n else:\r\n map1 = lastMap\r\n map2 = copy.deepcopy(_map.data)\r\n inputs = getInputs(map1, map2, _map.h, _map.w)\r\n inputs = t.Tensor([inputs])\r\n inputs = inputs.reshape((1, 2, 60, 40))\r\n # 做动作前\r\n\r\n koutu()\r\n\r\n # 做动作\r\n if player.alive:\r\n player.fireN += 1\r\n a_out = aNet(inputs)\r\n ss = inputs.detach().numpy().tolist()\r\n a = a_out.detach().numpy().tolist()\r\n mo = a_out.max(1)[1].item()\r\n # playerCtrl()\r\n AICtrl(mo)\r\n oldScore = score\r\n # 做动作\r\n\r\n if not player.alive and pg.key.get_pressed()[K_r]:\r\n replay()\r\n otherAct()\r\n if player.alive:\r\n for s in stoneGe.stones:\r\n if player.checkAABB(s):\r\n stoneGe.stones.remove(s)\r\n player.alive = False\r\n break\r\n putInMap()\r\n\r\n # 做动作后\r\n r = score - oldScore\r\n map3 = copy.deepcopy(_map.data)\r\n s_ = t.Tensor([getInputs(map2, map3, _map.h, _map.w)]).reshape((1, 2, 60, 40)).numpy().tolist()\r\n store.add(ss, a, r, s_)\r\n\r\n if len(store.stores) == store.maxNum:\r\n sample = store.sample(64)\r\n sample = np.array(sample)\r\n ss = sample[:, 0]\r\n aa = sample[:, 1]\r\n rr = sample[:, 2]\r\n ss_ = sample[:, 3]\r\n\r\n # cInputs = t.Tensor(ss)\r\n # cInputs = cInputs.view(cInputs.size(), 64)\r\n # print(cInputs.shape)\r\n\r\n # c网络的输入 = ss拼接aa\r\n # c网络输出 = c(c网络输入)\r\n # cnext网络输出(ss_拼接【ss_放入a网络中得到的输出】)\r\n # c网络输出=cnext网络输出+奖励\r\n # 计算c网络误差 实际值:c网络输出 标签值:cnext网络输出+奖励\r\n # c网络梯度归零,c网络误差反向传播\r\n # c网络参数优化\r\n\r\n # 冻结c网络参数\r\n # ss输入a网络得到输出aa,ss拼接输出aa传入c网络得到c网络输出\r\n # a网络误差 = -c网络输出\r\n # a网络梯度归零\r\n # a网络误差反向传播\r\n # a网络按时优化\r\n\r\n # 做动作后\r\n\r\n screen.fill(BLACK) # 通过填充黑色RGB颜色来擦除屏幕\r\n\r\n _map.draw()\r\n scoreTxt = fontBig.render('Score:' + str(score), 1, GREEN)\r\n if not player.alive:\r\n overTxt = fontBig.render('Game Over', 1, RED)\r\n tipTxt = fontSmall.render('Press \"R\" to replay', 1, BLUE)\r\n screen.blit(overTxt, (100, 200))\r\n screen.blit(tipTxt, (120, 300))\r\n screen.blit(scoreTxt, (0, 0))\r\n pg.display.flip()\r\n clock.tick(20)\r\n" }, { "alpha_fraction": 0.440443217754364, "alphanum_fraction": 0.4626038670539856, "avg_line_length": 22.066667556762695, "blob_id": "3201a86d139bb7c6b4118113552d674c376937b8", "content_id": "dd1636e22a8c87b16bd830c724172806f3212a68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/Bullet.py", "repo_name": "ycc9135/PlaneWar", "src_encoding": "UTF-8", "text": "from PlaneWar.Shape import *\r\n\r\n\r\nclass Bullet(Shape):\r\n def __init__(self):\r\n super(Bullet, self).__init__(1,0, 0, [\r\n (0, 0)\r\n ])\r\n\r\n def move(self, map):\r\n if self.checkOutOfMap(self.x, self.y - 1, map) == 2:\r\n return False\r\n else:\r\n self.setxy(self.x, self.y - 1)\r\n return True\r\n" } ]
12
mcuneo/hello_world
https://github.com/mcuneo/hello_world
80ca5d2058e8b1fc18097fcf06559345c7cbcb94
d09de2c658c2a8dad03b793c27afa5de543a451d
18717c7d802aafef63c7bc3a90d1a8154d07f13e
refs/heads/master
2020-06-26T23:18:21.251946
2019-07-31T05:35:11
2019-07-31T05:35:11
199,785,340
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22, "blob_id": "d411911c9921e652d666536b117e8b73c35f2d27", "content_id": "fcaf20831c9f77ae6a6f21a3bac1e9464b961784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 22, "num_lines": 1, "path": "/hello_marina.py", "repo_name": "mcuneo/hello_world", "src_encoding": "UTF-8", "text": "print('hello marina!')\n" } ]
1
heroinlin/python_tool
https://github.com/heroinlin/python_tool
4e5b22c714e53782cfb9e2cf8c938fe3848b22f7
9e8599939839dfdc9d6e25a8b2b582ed42cbfd8d
5ec469e9b4fb56c1bdfa3d5c3530e11abb97c5f5
refs/heads/master
2021-01-18T20:08:04.711335
2016-09-28T09:23:36
2016-09-28T09:23:36
68,795,251
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6365079283714294, "alphanum_fraction": 0.6920635104179382, "avg_line_length": 30.5, "blob_id": "fd017552e7d14cad223bf1368a28bf5fa161c868", "content_id": "aef78df59b2ca38dc22229422bf871d27fe6162c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 91, "num_lines": 20, "path": "/files_rename.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\n\"\"\"\nrename each file in folder \n\"\"\"\nimport string\nimport os\nfrom os import listdir, getcwd\nfrom os.path import join\n'''\n重命名flodername文件夹下所有图片,0000001_old.jpg >> 0000001.jpg ,0000002_old.jpg >> 0000002.jpg\n'''\nflodername = \"/home/heroin/Dataset/labels\"\n# flodername1 = \"/home/heroin/Dataset/labels_new\"\n# if not os.path.exists(flodername1):\n# os.mkdir(flodername1)\nos.path.dirname(flodername)\nfor filename in os.listdir(flodername):\n str = string.split(filename, '_')\n newfilename = str[0]+'.'+string.split(str[1], '.')[1]\n os.renames(flodername+'/'+filename, flodername+'/'+newfilename)\n" }, { "alpha_fraction": 0.5607344508171082, "alphanum_fraction": 0.5790960192680359, "avg_line_length": 28.5, "blob_id": "b051eadc8d1496c6318d7cd7da61e479b827ee97", "content_id": "5b377445240c1d4e3926286014443595acb4e8a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/Python-Examples-master/print_fromat.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\n根据用户输入的宽度打印格式化的列表\n'-'用于左对齐,'*'作为宽度或者精度(或者两个都使用)\n\"\"\"\n\n\ndef main():\n width = input(\"Enter the width: \")\n price_width = 10\n item_width = width - price_width\n header_format = \"%-*s%*s\"\n format = \"%-*s%*.2f\"\n print('='*width)\n print header_format % (item_width, \"Item\", price_width, \"Price\")\n print('-'*width)\n print format % (item_width, \"Apple\", price_width, 0.4)\n print format % (item_width, \"Pear\", price_width, 0.5)\n print format % (item_width, \"Banana\", price_width, 0.6)\n print format % (item_width, \"Orange\", price_width, 2)\n print format % (item_width, \"Lemon\", price_width, 12)\n print(\"=\"*width)\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.546893298625946, "alphanum_fraction": 0.5633059740066528, "avg_line_length": 27.898305892944336, "blob_id": "a4a90655fd812551b63cd7e21880fcc38a00cb6a", "content_id": "bc19025dbbc97d2c6d54db060a2b89ba130d7a9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1768, "license_type": "no_license", "max_line_length": 88, "num_lines": 59, "path": "/Python-Examples-master/login_password.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n检查用户名和PIN码,用于登录\n\"\"\"\n\n\ndef _init_(self):\n self.data = []\n\n\n# 在self后添加一user\ndef add_user(self, name, password):\n # 添加一项\n self.append([name, password])\n\n # 添加多项\n # self.extend([[name, password], [name, password]])\n\n # self += [[name, password]]\n\n\ndef del_user(self, name, password):\n # 返回[name,password]在self中的索引\n index = self.index([name, password])\n del self[index]\n\n\ndef main():\n database = [['Jack', '1587'], ['Rose', '1698'], ['Jame', '1326'], ['House', '6688']]\n num = raw_input(\"Enter to sign in or sign up(1 or 2).\\n\\\n sign in please input number '1',\\n\\\n sign up please input number '2',\\n\\\n delete the user please input number '3':\\n\")\n if '1'in num:\n name = raw_input(\"Enter the name: \")\n password = raw_input(\"Enter the PIN code:\")\n if [name, password] in database:\n print(\"Login success! Hello \" + name)\n else:\n print(\"Name is not exist or password is wrong !\")\n elif '2' in num:\n name = raw_input(\"Enter the name: \")\n password = raw_input(\"Enter the PIN code:\")\n add_user(database, name, password)\n print(\"Hello, \" + name + \"! Welcome to join!\")\n elif '3' in num:\n name = raw_input(\"Enter the name: \")\n password = raw_input(\"Enter the PIN code:\")\n if [name, password] in database:\n del_user(database, name, password)\n print(\"Delete success! \" + name + \" has remove the database!\")\n else:\n print(\"Delete error!Name is not exist or password is wrong !\")\n else:\n print(\"Input error!Please enter 1 or 2 or 3!\")\n print(database)\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.6360759735107422, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 27.727272033691406, "blob_id": "e76529bcafc9929d529f513772ed9ad28af8b3c9", "content_id": "58ea864db420192490828dd8fbfa98edb7b837a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "no_license", "max_line_length": 88, "num_lines": 11, "path": "/opencv_test/string2image.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport pygame\nimport cv2\nfrom pygame.locals import *\npygame.init()\n \ntext = u\"这是一段测试文本,test 123。\"\nfont = pygame.font.Font('msyh.ttf', 20)#当前目录下要有微软雅黑的字体文件msyh.ttc,或者去c:\\Windows\\Fonts目录下找\nftext = font.render(text, True, (0, 0, 0), (255, 255, 255))\npygame.image.save(ftext, \"t.jpg\")\n" }, { "alpha_fraction": 0.6775510311126709, "alphanum_fraction": 0.7102040648460388, "avg_line_length": 28.440000534057617, "blob_id": "caf4bfde7b334906b1bd3de17bf0efa2de0d2342", "content_id": "60b522cb337fe4f434df801398a5809e70246b70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 86, "num_lines": 25, "path": "/opencv_test/video_canny.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport cv2.cv as cv\n\ncapture = cv.CaptureFromFile('../images/test.avi')\n\nnbFrames = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT))\nprint(\"Frame=\",nbFrames)\nfps = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FPS)\n#wait = int(1/fps * 1000/1)\n\ndst = cv.CreateImage((int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)),\n int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))), 8, 1)\n\nfor f in xrange( nbFrames ):\n\n frame = cv.QueryFrame(capture)\n\n cv.CvtColor(frame, dst, cv.CV_BGR2GRAY)\n cv.Canny(dst, dst, 125, 350)\n cv.Threshold(dst, dst, 128, 255, cv.CV_THRESH_BINARY_INV)\n\n cv.ShowImage(\"The Video\", frame)\n cv.ShowImage(\"The Dst\", dst)\n#cv.WaitKey(wait)\n cv.WaitKey(1)" }, { "alpha_fraction": 0.6142034530639648, "alphanum_fraction": 0.6266794800758362, "avg_line_length": 23.809524536132812, "blob_id": "53152e857ee4f7ee4d8197575db4ed9ca9b5f897", "content_id": "64f7881a500da26031e3ec00f787ba365c6ab501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1210, "license_type": "no_license", "max_line_length": 87, "num_lines": 42, "path": "/get_jpg_from_html.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# coding=utf-8\nimport urllib\nimport re\nimport time\n\n#获取网页中的所有图片url\ndef parseTarget(url):\n content=urllib.urlopen(url).read()#以源码方式打开url\n #print(content)\n #pattern = r'src=\"(.*?\\.jpg)\" '#根据网页图片模式更改正则式\n pattern = r'src=\"(.*\\.jpg)\" '\n imglist = re.findall(pattern,content)#在源码中寻找pattern,将结果列表\n return imglist\n\n#下载urls中的图片\ndef downloadURL(urls):\n \"\"\"\n urls: 需要下载的url列表\n dirpath: 下载的本地路径\n \"\"\"\n i = 0\n for url in urls:\n if len(url)>0:\n urllib.urlretrieve(url, './images/%05d.jpg'%i)#下载url中的图片到本地dirpath\n print('now downloading: '+url)\n i += 1\n\n\nurls = []#需要下载的图片地址列表\n# for i in range(1,3):\n# http_url = \"http://www.ivsky.com/tupian/ziranfengguang/index_%s\" % str(i)+\".html\"\n# try:\n# urls.extend(parseTarget(http_url))\n# except:\n# break\nhttp_url = \"http://www.ivsky.com/tupian/ziranfengguang/index_1.html\"\nurls.extend(parseTarget(http_url))\nprint(urls)\ntime1 = time.time()\ndownloadURL(urls)\ntime2 = time.time()\nprint u'耗时:' + str(time2 - time1)\n" }, { "alpha_fraction": 0.5349794030189514, "alphanum_fraction": 0.5812757015228271, "avg_line_length": 20.15217399597168, "blob_id": "a0a7d6c3d1373e22246fba93275742d82a564944", "content_id": "672542c6b20eb33f0641b78ab5a2427c3e445545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 60, "num_lines": 46, "path": "/opencv_test/split_image.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 15 15:05:21 2016\n\n@author: heroin\n\"\"\"\n#图片通道分离和合并\nimport cv2 \nimport numpy as np \n \nimg = cv2.imread(\"../images/cat.jpg\") \n#(1)\n#b, g, r = cv2.split(img) \n\n#(2)\n# b = cv2.split(img)[0] \n# g = cv2.split(img)[1] \n# r = cv2.split(img)[2] \n\n#(3)\nb = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) \ng = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) \nr = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) \nb[:,:] = img[:,:,0] \ng[:,:] = img[:,:,1] \nr[:,:] = img[:,:,2] \n#\ncv2.imshow(\"Blue\", b) \ncv2.imshow(\"Red\", r) \ncv2.imshow(\"Green\", g) \ncv2.waitKey(0) \n#(a)\nmerged = cv2.merge([b,g,r]) \n#print \"Merge by OpenCV\" \n#print merged.strides \n#print merged \n #(b) \nmergedByNp = np.dstack([b,g,r]) \n#print \"Merge by NumPy \" \n#print mergedByNp.strides \n#print mergedByNp \n \ncv2.imshow(\"Merged\", merged) \ncv2.imshow(\"MergedByNp\", merged) \ncv2.waitKey(0) \ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.5356037020683289, "avg_line_length": 17, "blob_id": "fa0b5f450a9ebf4eb2e09c4636c5e50de4996d4c", "content_id": "53f5cdbceb141920b4d13362375939b8642b0484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/opencv_test/show_image.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 15 14:32:57 2016\n\n@author: heroin\n\"\"\"\n# 导入OpenCV模块\nimport sys\nimport cv2 \nif __name__ == '__main__':\n \n # 载入图像,强制转化为Gray\n \n pImg = cv2.imread(sys.argv[1])\n cv2.namedWindow(\"Image\") \n # 显示图像\n cv2.imshow (\"Image\", pImg)\n cv2.waitKey(0)" }, { "alpha_fraction": 0.7228525280952454, "alphanum_fraction": 0.734197735786438, "avg_line_length": 28.380952835083008, "blob_id": "0b7a879879cd5dda4d877a2bd4c92c9f98f0c5e9", "content_id": "a8b3e391e4cf72c7a75e12ce3d8cb9ca66f4c033", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 52, "num_lines": 21, "path": "/jpg2png.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\ntranslate the form of images from .jpg to .png\n'''\nimport os\nimport string\nfrom os import listdir,getcwd\nfrom os.path import join\nfrom skimage.io import imread, imsave\n'''\n将文件夹foldername文件夹下的.jpg图片转为.png格式并保存至foldername1文件夹下\n'''\nfoldername = \"/home/heroin/Dataset/labels/\"\nfoldername1 = \"/home/heroin/Dataset/labels_png/\"\nif not os.path.exists(foldername1):\n os.mkdir(foldername1)\nos.path.dirname(foldername)\nfor filename in os.listdir(foldername):\n src_img = imread(foldername+filename)\n picname = string.split(filename,'.')[0]+'.png'\n imsave(foldername1+picname,src_img)\n" }, { "alpha_fraction": 0.538947343826294, "alphanum_fraction": 0.5452631711959839, "avg_line_length": 24, "blob_id": "8da70186879568ede9ea99b425c3cb0100f671cf", "content_id": "3c5bfff29f6b35ededa9d25c07f52cf807d26dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "no_license", "max_line_length": 72, "num_lines": 19, "path": "/Python-Examples-master/dic_HTML.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# 字典用于html中的例子\n# \"%(key)s\"%{key:value} 以字符串形式输出字典里key对应的value\ntemplate = ''' <html>\n <head><title>%(title)s</title></head>\n <body>\n <h1>%(title)s</h1>\n <p>%(text)s</p>\n </body>'''\n\n\ndef main():\n data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}\n print (template % data)\n out_html = open(\"my_home_page.html\", 'w')\n out_html.write(template % data)\n out_html.close()\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6736401915550232, "alphanum_fraction": 0.6792189478874207, "avg_line_length": 24.60714340209961, "blob_id": "0bc385be494a38ed371df141c4e444d25626146e", "content_id": "022e6b453419dcdfbce8d547260dae3782c0b791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 62, "num_lines": 28, "path": "/filepaths_write_to_txt.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nlist files path into txt\n\"\"\"\nimport string\nimport os\nimport sys\nfrom os import listdir, getcwd\nfrom os.path import join\n\"\"\"\n将self文件夹下的所有filetype格式文件的路径写入到out_file文件中\n\"\"\"\ndef filepaths_write_to_txt(self, out_file, filetype=None):\n\t#print(os.path.dirname(self))\n\tfor filename in os.listdir(self):\n\t\tif string.find(filename,filetype or '.')!=-1:\n\t\t\tout_file.write('%s/%s\\n'% ( self, filename)) \n\t\t\tprint (filename)\n\ndef main():\n\tfoldername = str(sys.argv[1])\n\tout_file= open(str(sys.argv[2]),'w')\n\t#foldername = \"/home/heroin/Dataset/images\"\n\t#out_file = open('/home/heroin/Dataset/images_list.txt', 'w')\n\tfilepaths_write_to_txt(foldername,out_file,'jpg')\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6403872966766357, "alphanum_fraction": 0.6832641959190369, "avg_line_length": 33.42856979370117, "blob_id": "02f76abbf7ff73d192666998782d9d81d210c8a2", "content_id": "333cc15b4cbdfe813c822e57e30be63199e6b237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "no_license", "max_line_length": 90, "num_lines": 21, "path": "/opencv_test/chinese.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#import codecs \n#start,end = (0x4E00, 0x9FA5) \n#with codecs.open(\"chinese.txt\", \"wb\", encoding=\"utf-8\") as f: \n# for codepoint in range(int(start),int(end)): \n# f.write(unichr(codepoint)) \n\nimport os \nimport pygame \nchinese_dir = 'chinese' \nif not os.path.exists(chinese_dir): \n os.mkdir(chinese_dir) \n \npygame.init() \nstart,end = (0x4E00, 0x9FA5)#汉字编码范围 \n#for codepoint in range(int(start),int(end)): \nfor codepoint in range(int(start),int(start)+2): \n word = unichr(codepoint) \n font = pygame.font.Font(\"msyh.ttf\", 22)#当前目录下要有微软雅黑的字体文件msyh.ttc,或者去c:\\Windows\\Fonts目录下找 \n rtext = font.render(word, True, (0, 0, 0), (255, 255, 255)) \n pygame.image.save(rtext, os.path.join(chinese_dir,word+\".png\")) " }, { "alpha_fraction": 0.5621788501739502, "alphanum_fraction": 0.6176772713661194, "avg_line_length": 29.375, "blob_id": "2cbd6861a724d10efaca831361547593b4982e9e", "content_id": "18151c66633e7bcf245a5ebf6f0598a53163720b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 84, "num_lines": 32, "path": "/opencv_test/opencvtest.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 15 15:05:21 2016\n\n@author: heroin\n\"\"\"\n\n\n# 图像的载入、显示、复制和保存\nimport sys\nimport cv2\nimport numpy as np\n \nif __name__ == '__main__':\n \n # 打开图像\n img = cv2.imread(sys.argv[1])\n cv2.namedWindow(\"Image\") \n emptyImage = np.zeros(img.shape, np.uint8) \n emptyImage2 = img.copy() \n emptyImage3=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) \n#emptyImage3[...]=0 \n cv2.imshow(\"EmptyImage\", emptyImage) \n cv2.imshow(\"Image\", img) \n cv2.imshow(\"EmptyImage2\", emptyImage2) \n cv2.imshow(\"EmptyImage3\", emptyImage3) \n cv2.imwrite(\"../images/cat2.jpg\", img, [int(cv2.IMWRITE_JPEG_QUALITY), 5]) \n cv2.imwrite(\"../images/cat3.jpg\", img, [int(cv2.IMWRITE_JPEG_QUALITY), 100]) \n cv2.imwrite(\"../images/cat1.png\", img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0]) \n cv2.imwrite(\"../images/cat2.png\", img, [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) \n cv2.waitKey (0) \n cv2.destroyAllWindows() " }, { "alpha_fraction": 0.6762075424194336, "alphanum_fraction": 0.6762075424194336, "avg_line_length": 38.85714340209961, "blob_id": "ba403fb291950a1b4d7babda7d5151446cc9ac78", "content_id": "52b34986487cc58d6650997167261ae14396c1f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 559, "license_type": "no_license", "max_line_length": 78, "num_lines": 14, "path": "/Python-Examples-master/README.md", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "Python Examples\n=============== \n--------\n\n* `read_file.py` - opens a file, reads each line, and processes the line.\n* `write_file.py` - write data to a file\n* `read_write_file.py` - opens two files, read from one, write to the other\n* `server.py` - Python server with sockets\n* `client.py` - Python client with sockets\n* `read_parse_url.py` - open a url and parse data using lxml and BeautifulSoup\n* `regular_expression.py` - the basics of using regular expressions\n* `read_xml_file.py` - open an xml file and parse the data using ElementTree\n\n-----------\n\n" }, { "alpha_fraction": 0.5998914241790771, "alphanum_fraction": 0.6281216144561768, "avg_line_length": 33.11111068725586, "blob_id": "5bc7bfa8004c9a59c363ad76bf4a0030e903e327", "content_id": "6ec6e4ae54117c582ca37037766e123fb97a2d1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/opencv_test/fill_string_in_image.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#python font\nimport os, pygame\nfrom pygame.locals import *\nfrom sys import exit\n\nif not pygame.font: print('Warning, fonts disabled')\npygame.init()\n#SCREEN_DEFAULT_SIZE = (500, 500)\nBG_IMAGE_NAME = '1.jpg'\nFROG_IMAGE_NAME = 't.jpg'\nTORK_FONT_NAME = 'msyh.ttf'\nbg_image_path = os.path.join('../images', BG_IMAGE_NAME)\nfrog_image_path = os.path.join('../images', FROG_IMAGE_NAME)\ntork_font_path = os.path.join('../images', TORK_FONT_NAME)\nif not os.path.exists(bg_image_path):\n print('Can\\'t found the background image:', bg_image_path)\nif not os.path.exists(frog_image_path):\n print('Can\\'t fount the frog image:', frog_image_path)\nif not os.path.exists(tork_font_path):\n print('Can\\'t fount the font:', tork_font_path)\nSCREEN_DEFAULT_SIZE = (500, 500)\nscreen = pygame.display.set_mode(SCREEN_DEFAULT_SIZE, 0, 32)\nbg = pygame.image.load(bg_image_path).convert()\nfrog = pygame.image.load(frog_image_path).convert_alpha()\ntork_font = pygame.font.Font(tork_font_path, 20)\n\nfrog_x, frog_y = 0, 0\nfrog_move_x, frog_move_y = 0, 0\nwhile 1:\n for event in pygame.event.get():\n if event.type == QUIT:\n exit()\n elif event.type == KEYDOWN:\n if event.key == K_LEFT:\n frog_move_x = -1\n elif event.key == K_UP:\n frog_move_y = -1\n elif event.key == K_RIGHT:\n frog_move_x = 1\n elif event.key == K_DOWN:\n frog_move_y = 1\n elif event.type == KEYUP:\n frog_move_x = 0\n frog_move_y = 0\n frog_x += frog_move_x\n frog_y += frog_move_y\n #print(frog_x, frog_y)\n screen.blit(bg, (0, 0))\n position_str = 'Position:' + str(frog_x) + ',' + str(frog_y)\n position = tork_font.render(position_str, True, (255, 255,255), (23, 43,234))\n screen.blit(position, (0, 480))\n screen.blit(frog, (frog_x, frog_y))\n pygame.display.update()\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.49496081471443176, "avg_line_length": 22.5, "blob_id": "368178744572ba3d32672e3e3b2bd51e447566ab", "content_id": "b9a819d13d9118bd937c8ea65942c523994dcc97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 72, "num_lines": 38, "path": "/Python-Examples-master/dic_telephone.py", "repo_name": "heroinlin/python_tool", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# 简单数据库,电话本示例\n# 使用人名作为键的自动,每个人用一字典表示,其键'phone'和'addr'分别表示他们的电话和地址\npeople = {\n 'Alice': {\n 'phone': '2341',\n 'addr': 'foo drive 23'\n },\n 'Beth': {\n 'phone': '9102',\n 'addr': 'bar street 42'\n },\n 'Cecil': {\n 'phone': '3158',\n 'addr': 'Baz avenue 90'\n }\n}\n\n\ndef main():\n # 针对电号码和地址使用的描述性标签,在打印输出时会用到\n labels = {\n 'phone': 'phone number',\n 'addr': 'address'\n }\n name = raw_input(\"Name: \")\n # 如果名字是字典里的有效键菜打印信息\n if name in people:\n request = raw_input(\"Find the phone number or address?(p/a): \")\n # 查找电话号码还是地址?使用正确的键:\n if request == 'p': key = 'phone'\n if request == 'a': key = 'addr'\n print(\"%s's %s is %s.\" % (name, labels[key], people[name][key]))\n else:\n print(\"people not in dictionary!\")\nif __name__ == '__main__':\n main()\n" } ]
16
pratikaher88/BookStoreProject
https://github.com/pratikaher88/BookStoreProject
67fcca0d1a0bf48ef45e8a04f08b738cc637c331
7fb51ac906d4b55c0601a4cf47892c0a5077a772
e88efc0f27f9490bcea36d6acaffc257f62638a0
refs/heads/master
2022-12-23T13:40:26.968631
2022-01-31T05:55:33
2022-01-31T05:55:33
163,747,442
0
0
null
2019-01-01T15:40:31
2019-01-02T14:34:12
2019-01-02T18:46:42
Python
[ { "alpha_fraction": 0.49347826838493347, "alphanum_fraction": 0.560869574546814, "avg_line_length": 20.904762268066406, "blob_id": "0c9156850ed5d58b8451ed74b3127fdf2609e3f8", "content_id": "eacc9f767741df9bff7499b53273f2fc0143fd56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 56, "num_lines": 21, "path": "/coreapp/migrations/0076_auto_20190129_0437.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-29 04:37\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0075_auto_20190126_1146'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='requests',\n options={'verbose_name_plural': 'Requests'},\n ),\n migrations.RemoveField(\n model_name='book',\n name='image',\n ),\n ]\n" }, { "alpha_fraction": 0.52555912733078, "alphanum_fraction": 0.5623003244400024, "avg_line_length": 26.217391967773438, "blob_id": "697703e81c8ef6da851b6cd2dcb0bd4f9dbca0ae", "content_id": "9afe2c37049745a433d80fa9c6e9586f87e31a76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 147, "num_lines": 23, "path": "/coreapp/migrations/0003_auto_20181231_1340.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2018-12-31 13:40\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0002_book_price'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='book',\n name='condition',\n field=models.CharField(choices=[('Acceptable', 'Acceptable'), ('Bad', 'Bad'), ('Good', 'Good')], default='Acceptable', max_length=100),\n ),\n migrations.AlterField(\n model_name='book',\n name='price',\n field=models.IntegerField(max_length=5),\n ),\n ]\n" }, { "alpha_fraction": 0.734032392501831, "alphanum_fraction": 0.7345090508460999, "avg_line_length": 32.30158615112305, "blob_id": "ba589060fea1421e78be528fa609239a531640bd", "content_id": "9ce15a95d747cc5c2009d4c10d76d050efe805cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2098, "license_type": "no_license", "max_line_length": 232, "num_lines": 63, "path": "/search/views.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom dal import autocomplete\nfrom django.views import generic\nfrom django.views.generic.edit import FormView\nfrom django.urls import reverse_lazy, reverse\nfrom search.forms import SearchForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom coreapp.models import Book, Profile, Transaction, FinalBuyOrder\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.db.models import Q\n\n\nclass SearchListView(LoginRequiredMixin, generic.ListView):\n model = Book\n template_name = 'list_entries.html'\n context_object_name = 'books'\n ordering = ['-created_at']\n\n def get_queryset(self):\n book_name = self.request.GET.get('search')\n\n ordered_books = FinalBuyOrder.objects.values_list('book')\n requester_books = Transaction.objects.values_list('requester_book')\n offerrer_books = Transaction.objects.values_list('offerrer_book')\n\n return Book.objects.exclude(user=self.request.user).exclude(id__in=ordered_books).exclude(id__in=requester_books).exclude(id__in=offerrer_books).filter(Q(book_name__icontains=book_name) | Q(author_name__icontains=book_name))\n\n # return Book.objects.filter(Q(book_name__icontains=book_name)) | Book.objects.filter(Q(author_name__icontains=book_name))\n\n# def search_form(request):\n\n# \tif request.method == 'POST':\n# \t\tform = SearchForm(request.POST)\n\n# \t\tif form.is_valid():\n\n# \t\t\tform.save()\n# \t\t\trequest.session['home_request'] = True\n# \t\t\treturn redirect('coreapp:list_entries')\n# \telse:\n\n# \t\tform = SearchForm()\n\n# \treturn render(request, 'list_entries.html', {'form': form})\n\n\n# class SearchAutoComplete(FormView):\n# template_name = 'list_entries.html'\n# form_class = SearchForm\n# success_url = reverse_lazy('coreapp:list_entries')\n\n\nclass ContentAutoComplete(autocomplete.Select2QuerySetView):\n\n\tdef get_queryset(self):\n\n\t\tqs = Book.objects.all()\n\n\t\tif self.q:\n\t\t\tqs = qs.filter(book_name__istartswith=self.q)\n\t\t\treturn qs\n" }, { "alpha_fraction": 0.5370370149612427, "alphanum_fraction": 0.6003086566925049, "avg_line_length": 27.173913955688477, "blob_id": "894403cf99957b0853d7dfcb6a51c879d8290369", "content_id": "31da6e47fad0384cbd554d77c0272df236d8e131", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 105, "num_lines": 23, "path": "/coreapp/migrations/0042_auto_20190111_1406.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-11 14:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0041_auto_20190111_1357'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='address1',\n field=models.CharField(max_length=500, verbose_name='Address line 1'),\n ),\n migrations.AlterField(\n model_name='shippingaddress',\n name='address2',\n field=models.CharField(blank=True, max_length=500, null=True, verbose_name='Address line 2'),\n ),\n ]\n" }, { "alpha_fraction": 0.6203522682189941, "alphanum_fraction": 0.6203522682189941, "avg_line_length": 29.058822631835938, "blob_id": "9d289a99b6cfad79edef46e77ef6abee6215ef74", "content_id": "60e90aedbe019b009dff9e74ef7dde45ea80f066", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 511, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/static/js/exchangeorsell.js", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "document.getElementById(\"priceid\").disabled = true;\n\nvar sell_or_exchange = $(\"#id_sell_or_exchange\");\n\nfunction refreshOptions() {\n if (sell_or_exchange.val() === \"Sell\") {\n document.getElementById(\"priceid\").disabled = false;\n } else {\n if (sell_or_exchange.val() === \"Exchange\") {\n document.getElementById(\"priceid\").value = '';\n document.getElementById(\"priceid\").disabled = true;\n }\n }\n}\nrefreshOptions();\n\nsell_or_exchange.on(\"change\", refreshOptions);\n" }, { "alpha_fraction": 0.6893140077590942, "alphanum_fraction": 0.6959102749824524, "avg_line_length": 53.14285659790039, "blob_id": "00a51286dc19b6b435cd6822c70b5e8e2ddfb8a8", "content_id": "5922e28975b6a894a845454296d2e6d3fcef0a69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 172, "num_lines": 28, "path": "/nofapapp/context_processors.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from coreapp.models import Transaction, ShippingAddress, Requests, Profile, Order, FinalBuyOrder, UserCollection\nfrom django.shortcuts import get_object_or_404\nfrom coreapp.forms import ShippingAddressForm\nfrom django.db.models import Q\n\n\ndef add_variable_to_context(request):\n if request.user.id:\n\n requester_books = Transaction.objects.values_list('requester_book')\n offerrer_books = Transaction.objects.values_list('offerrer_book')\n\n # addressformcontext=ShippingAddressForm(\n # request.POST, instance=request.user.profile.address)\n orderitems = Order.objects.get(owner=request.user.profile)\n return {\n 'requestscount': Requests.objects.filter(requester=request.user).count(),\n 'offercount' : Requests.objects.filter(offerrer=request.user).count(),\n 'orderscount': Transaction.objects.filter(Q(offerrer=request.user) | Q(requester=request.user)).count()+FinalBuyOrder.objects.filter(user=request.user).count(),\n 'cartitemscount': orderitems.items.count(),\n 'addresscheck': get_object_or_404(ShippingAddress, profile=get_object_or_404(Profile, user=request.user)).address1,\n # 'addressformcontext': addressformcontext\n 'exchangeitemexists': UserCollection.objects.get(\n owner=request.user.profile).books.exclude(\n id__in=requester_books).exclude(id__in=offerrer_books).filter(sell_or_exchange=\"Exchange\").exists(),\n }\n else:\n return {}\n" }, { "alpha_fraction": 0.6700655221939087, "alphanum_fraction": 0.6802622079849243, "avg_line_length": 49.85185241699219, "blob_id": "2d9d17ee570df7a6db2a3e040c4b374eecf4dccb", "content_id": "cbfdac5b987fd8d183ec42fbc39514a3881674d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 154, "num_lines": 27, "path": "/nofapapp/urls.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.conf.urls import url,include\nfrom django.contrib import admin\nfrom django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n url('', include('coreapp.urls')),\n url('transaction/', include('transaction.urls', namespace='transaction')),\n url('search/',include('search.urls',namespace='search')),\n url('cartitems/',include('cart.urls', namespace='cart')),\n url(r'^login/$', LoginView.as_view(), name='login'),\n url(r'^logout/$', LogoutView.as_view(), name='logout'),\n url('^', include('django.contrib.auth.urls')),\n url(r'^cadabraadmin/', admin.site.urls),\n url(r'^password_reset/$', PasswordResetView.as_view() , name='password_reset'),\n url(r'^password_reset/done/$', PasswordResetDoneView.as_view(),\n name='password_reset_done'),\n url(r'^reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n PasswordResetConfirmView.as_view(), name='password_reset_confirm'),\n url(r'^reset/done/$', PasswordResetCompleteView.as_view(),\n name='password_reset_complete'),\n] \n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.4430379867553711, "alphanum_fraction": 0.5907173156738281, "avg_line_length": 25.33333396911621, "blob_id": "a5aaa31f03238487b8e3beb03f6332b0ba044f71", "content_id": "25f961b6d8e2c21fc8825e541e13892b2f743e56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 127, "num_lines": 18, "path": "/coreapp/migrations/0044_auto_20190112_0402.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-12 04:02\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0043_auto_20190111_1551'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='zip_code',\n field=models.CharField(choices=[('421202', '421202'), ('421201', '421201'), ('421203', '421203')], max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.6619047522544861, "alphanum_fraction": 0.6619047522544861, "avg_line_length": 29, "blob_id": "d123b46cca1fdaed04c0b51b79623b0681a83e96", "content_id": "569f4444e16aa546dbbb198a346fc9a26fa6cfc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 77, "num_lines": 14, "path": "/cart/urls.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from cart import views\nfrom django.urls import path\n\napp_name='cart'\n\nurlpatterns = [\n path('<int:item_id>/add', views.add_to_cart, name='add_to_cart'),\n path('cart/', views.cart_list_entries_view, name='cart_items'),\n path('<int:item_id>/delete', views.delete_from_cart, name='delete_item'),\n path('cart/<int:pk>/delete',\n views.FinalBuyOrderDeleteView.as_view(), name='finalorder-delete'),\n \n\n]\n" }, { "alpha_fraction": 0.5062836408615112, "alphanum_fraction": 0.5403949618339539, "avg_line_length": 21.280000686645508, "blob_id": "0b45c5fcd41cacea4acc4ee5e4a82b5c0f21ecca", "content_id": "9045b9d686b4c7b4997582bb32b6c7286475936f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "no_license", "max_line_length": 60, "num_lines": 25, "path": "/cart/migrations/0002_auto_20190105_0448.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 04:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cart', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='orderitem',\n name='book',\n ),\n migrations.AlterField(\n model_name='order',\n name='items',\n field=models.ManyToManyField(to='coreapp.Book'),\n ),\n migrations.DeleteModel(\n name='OrderItem',\n ),\n ]\n" }, { "alpha_fraction": 0.5356265306472778, "alphanum_fraction": 0.5896806120872498, "avg_line_length": 21.61111068725586, "blob_id": "ede5d0809420d8a8f2005466681620b495f9f7db", "content_id": "5ba667a4eabae8bdf970cf7522e30c103879b6e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/coreapp/migrations/0075_auto_20190126_1146.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-26 11:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0074_book_image_url'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='image_url',\n field=models.CharField(blank=True, max_length=500, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5644769072532654, "alphanum_fraction": 0.6107056140899658, "avg_line_length": 21.83333396911621, "blob_id": "47f941f2b5eeedb996c2e5189d042e9eea8af23b", "content_id": "d66ed362add7feece63164281b584f6e922c0fed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/coreapp/migrations/0036_auto_20190111_0747.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-11 07:47\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0035_oldrequests_requests_shippingaddress_transaction'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='transaction',\n old_name='offerer_book',\n new_name='offerrer_book',\n ),\n ]\n" }, { "alpha_fraction": 0.6299644112586975, "alphanum_fraction": 0.6384114027023315, "avg_line_length": 43.394737243652344, "blob_id": "2cb6ab13028a7d9c35acbf2ea97a452aff548ea5", "content_id": "d5fcfdf7cbdd4498a1d9d7c1ebec20ece5751e9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20244, "license_type": "no_license", "max_line_length": 218, "num_lines": 456, "path": "/coreapp/models.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save, post_delete ,pre_delete\nfrom django.dispatch import receiver\nfrom PIL import Image\nfrom random import choice\nfrom os.path import join as path_join\nfrom os import listdir\nimport os\nimport requests\nfrom os.path import isfile\nfrom nofapapp.settings import BASE_DIR, MAILGUN_KEY, MAILGUN_REQUEST_URL, MSG_SMS_URL, MSG_SMS_AUTH_KEY\nfrom django.core.validators import RegexValidator\nfrom django.core.mail import EmailMessage\nfrom django.core.mail import send_mail\nimport threading\n\nCONITION_CHOICES = (\n ('Almost New', 'Almost New'),\n ('Acceptable', 'Acceptable'),\n ('Good', 'Good'),\n ('Bad', 'Bad'),\n)\nZIP_CHOICES = (\n ('421202', '421202'),\n ('421201', '421201'),\n ('421204', '421204'),\n ('421203', '421203'),\n ('421301', '421301'),\n\n)\nBUY_OR_EXCHANGE = (\n ('Sell', 'Sell'),\n ('Exchange', 'Exchange'),\n)\n\n\ndef random_img():\n dir_path = os.path.join(BASE_DIR, 'static/profile_pic')\n files = [content for content in listdir(\n dir_path) if isfile(path_join(dir_path, content))]\n return str(choice(files))\n\n\nclass Book(models.Model):\n\n user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n book_name = models.CharField(\n max_length=100, help_text=\"We only deal with original books with ISBN codes, pirated books will not be accepted.\")\n author_name = models.CharField(max_length=100, blank=True, null=True)\n description = models.CharField(max_length=2000, blank=True, null=True)\n # image = models.ImageField('Book Image', null=True,\n # blank=True, upload_to=\"book_images/\")\n price = models.IntegerField(\n null=True, blank=True, help_text=\"We would be deducting 20 rupees from item price for delivery purposes.\")\n sell_or_exchange = models.CharField(\n max_length=100, choices=BUY_OR_EXCHANGE, default='Exchange', help_text=\"By adding items to exchange you can make requests to other users for exchange.\")\n condition = models.CharField(\n max_length=100, choices=CONITION_CHOICES, default='Acceptable')\n created_at = models.DateTimeField(auto_now_add=True)\n image_url = models.CharField(max_length=500,blank=True,null=True)\n\n class Meta:\n verbose_name = 'Book'\n verbose_name_plural = 'Books'\n\n def __str__(self):\n return self.book_name\n\n # def save(self, *args, **kwargs):\n # super(Book, self).save(*args, **kwargs)\n # if self.image:\n # img = Image.open(self.image.path)\n # output_size = (120, 120)\n # img.thumbnail(output_size)\n # img.save(self.image.path)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n profile_pic = models.ImageField(\n default=random_img, upload_to=\"profile_images/\")\n\n def __str__(self):\n return self.user.username\n\n def save(self, *args, **kwargs):\n super(Profile, self).save(*args, **kwargs)\n\n img = Image.open(self.profile_pic.path)\n if img.height > 300 or img.width > 300:\n output_size = (300, 300)\n img.thumbnail(output_size)\n img.save(self.profile_pic.path)\n\n\nclass ShippingAddress(models.Model):\n profile = models.OneToOneField(\n Profile, on_delete=models.CASCADE, related_name='address')\n phone_regex = RegexValidator(\n regex=r'^\\+?1?\\d{10,15}$', message=\"Phone number must be entered in the format: '+9999999999'. Up to 15 digits allowed.\")\n phone_number = models.CharField(\n validators=[phone_regex], max_length=17, help_text=\"Enter your 10 digit phone number without any prefix code.\")\n flatnumber = models.CharField(\"Flat Number\", max_length=100)\n address1 = models.CharField(\"Address line 1\", max_length=500,)\n address2 = models.CharField(\n \"Address line 2\", max_length=500, blank=True, null=True)\n zip_code = models.CharField(\n max_length=100, choices=ZIP_CHOICES, default='421202', help_text=\"We only operate in these locations for now!\")\n city = models.CharField(\"City\", max_length=100,)\n\n class Meta:\n verbose_name = \"Shipping Address\"\n verbose_name_plural = \"Shipping Addresses\"\n\n def status(self):\n return self.address1 is \"\" or self.phone_number is \"\"\n\n def __str__(self):\n return \"{},{},{},{},{},{}\".format(self.profile.user.username,self.flatnumber, self.address1, self.address2, self.zip_code, self.phone_number)\n\n\nclass Order(models.Model):\n owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)\n items = models.ManyToManyField(Book)\n date_ordered = models.DateTimeField(auto_now=True)\n\n def get_cart_items(self):\n return self.items.all()\n\n def __str__(self):\n return self.owner.user.username\n\n\nclass UserCollection(models.Model):\n owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)\n books = models.ManyToManyField(Book)\n date_ordered = models.DateTimeField(auto_now=True)\n\n def get_collection_items(self):\n return self.books.all()\n\n def __str__(self):\n return self.owner.user.username\n\n\nclass Requests(models.Model):\n\n requester = models.ForeignKey(\n User, related_name='to_user', on_delete=models.CASCADE)\n offerrer = models.ForeignKey(\n User, related_name='from_user', on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n requester_book = models.ForeignKey(\n Book, related_name='requester_book_from_user', on_delete=models.CASCADE)\n\n def __str__(self):\n return \"Request from {}, to {} ,with Book {}\".format(self.requester.username, self.offerrer.username, self.requester_book.book_name)\n\n class Meta:\n verbose_name_plural = \"Requests\"\n\n\nclass Transaction(models.Model):\n\n requester = models.ForeignKey(\n User, related_name='requester', on_delete=models.CASCADE)\n offerrer = models.ForeignKey(\n User, related_name='offerrer', on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n requester_book = models.ForeignKey(\n Book, related_name='requested_book_from_user', on_delete=models.CASCADE)\n offerrer_book = models.ForeignKey(\n Book, related_name='offerrer_book_from_user', on_delete=models.CASCADE)\n requester_address = models.ForeignKey(\n ShippingAddress, related_name='user_address', null=True, on_delete=models.CASCADE)\n offerrer_address = models.ForeignKey(\n ShippingAddress, related_name='seller_address', null=True, on_delete=models.CASCADE)\n\n def __str__(self):\n return \"From {}, to {} and {} to {}\".format(self.requester.username, self.offerrer.username, self.requester_book.book_name, self.offerrer_book.book_name)\n\n\nclass OldRequests(models.Model):\n\n requester = models.ForeignKey(\n User, related_name='old_to_user', on_delete=models.CASCADE)\n offerrer = models.ForeignKey(\n User, related_name='old_from_user', on_delete=models.CASCADE)\n requester_book = models.ForeignKey(\n Book, related_name='old_requester_book_from_user', on_delete=models.CASCADE, )\n\n def __str__(self):\n return \"From {}, to {} ,with Book {}\".format(self.requester.username, self.offerrer.username, self.requester_book.book_name)\n\n class Meta:\n verbose_name_plural = \"Old Requests\"\n\nclass FinalBuyOrder(models.Model):\n user = models.ForeignKey(User, related_name='user',\n on_delete=models.CASCADE)\n book = models.ForeignKey(Book, on_delete=models.CASCADE)\n seller = models.ForeignKey(\n User, related_name='seller', on_delete=models.CASCADE)\n useraddress = models.ForeignKey(\n ShippingAddress, related_name='address', on_delete=models.CASCADE)\n selleraddress = models.ForeignKey(\n ShippingAddress, related_name='selleraddress', on_delete=models.CASCADE)\n date_ordered = models.DateTimeField(auto_now_add=True)\n total_price = models.IntegerField(null=True)\n\n def __str__(self):\n return self.book.book_name\n\n\nclass CompletedTransaction(models.Model):\n\n requester = models.ForeignKey(\n User, related_name='completed_requester', on_delete=models.CASCADE)\n offerrer = models.ForeignKey(\n User, related_name='completed_offerrer', on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n requester_book_name = models.CharField(max_length=100, blank=True, null=True)\n\n offerrer_book_name = models.CharField(\n max_length=100, blank=True, null=True)\n \n requester_author_name = models.CharField(\n max_length=100, blank=True, null=True)\n\n offerrer_author_name = models.CharField(\n max_length=100, blank=True, null=True)\n \n requester_address = models.ForeignKey(\n ShippingAddress, related_name='completed_user_address', null=True, on_delete=models.CASCADE)\n offerrer_address = models.ForeignKey(\n ShippingAddress, related_name='completed_seller_address', null=True, on_delete=models.CASCADE)\n\n def __str__(self):\n return \"From {}, to {} Book1 is {} Book2 is{}\".format(self.requester.username, self.offerrer.username, self.requester_book_name, self.offerrer_book_name)\n\n\n\nclass CompletedBuyOrder(models.Model):\n\tuser = models.ForeignKey(User, related_name='completed_user',\n\t blank=True, null=True, on_delete=models.CASCADE)\n\tbook_name = models.CharField(max_length=100, blank=True, null=True)\n\tauthor_name = models.CharField(max_length=100, blank=True, null=True)\n\tseller = models.ForeignKey(\n\t\tUser, related_name='completed_seller', blank=True, null=True, on_delete=models.CASCADE)\n\tuseraddress = models.ForeignKey(\n\t\tShippingAddress, related_name='completed_address', blank=True, null=True, on_delete=models.CASCADE)\n\tselleraddress = models.ForeignKey(\n\t\tShippingAddress, related_name='completed_selleraddress', blank=True, null=True, on_delete=models.CASCADE)\n\tdate_ordered = models.DateTimeField(auto_now_add=True)\n\ttotal_price = models.IntegerField(null=True)\n\n\tdef __str__(self):\n\t\treturn self.book_name\n\n@receiver(post_save, sender=User)\ndef create_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n Order.objects.create(owner=instance.profile)\n ShippingAddress.objects.create(profile=instance.profile)\n UserCollection.objects.create(owner=instance.profile)\n\n\n@receiver(post_save, sender=User)\ndef save_profile(sender, instance, **kwargs):\n instance.profile.save()\n\n\n# class EmailThread(threading.Thread):\n# def __init__(self, subject, html_content, recipient_list):\n# self.subject = subject\n# self.recipient_list = recipient_list\n# self.html_content = html_content\n# threading.Thread.__init__(self)\n\n# def run(self):\n# msg = EmailMessage(self.subject, self.html_content, to=self.recipient_list)\n# msg.send()\n\nclass EmailThreadAPI(threading.Thread):\n def __init__(self, subject, text, recepient):\n self.subject = subject\n self.text = text\n self.recepient = recepient\n threading.Thread.__init__(self)\n\n def run(self):\n requests.post(MAILGUN_REQUEST_URL, auth=('api', MAILGUN_KEY), data={\n 'from': '[email protected]',\n 'to': self.recepient,\n 'subject': self.subject,\n 'text': self.text,\n })\n\ndef send_sms(mobiles,message):\n parms = {\n 'authkey': MSG_SMS_AUTH_KEY,\n 'country': '91',\n 'sender': 'CDABRA',\n 'route': '4',\n 'mobiles': mobiles,\n 'message': message,\n }\n request = requests.post(url=MSG_SMS_URL, params=parms)\n\n# Done\n@receiver(post_save, sender=Transaction)\ndef send_transaction_email(sender, instance, created, **kwargs):\n\n if created:\n\n EmailThreadAPI(subject='Exchange Order created for your book ' + instance.offerrer_book.book_name,\n text='An exchange order has been created for \"' + instance.requester_book.book_name +\n '\" from \"' + instance.requester.username +\n '\" and \"'+instance.offerrer_book.book_name +\n '\" from \"' + instance.offerrer.username +\n '\". Go to https://www.cadabra.co.in/transaction/orders/ to view the order. Thank You for ordering. Delivery of your book order will be attempted by CADABRA within one week.',\n recepient=instance.offerrer.email).start()\n\n EmailThreadAPI(subject='Exchange Order created for your book ' + instance.requester_book.book_name,\n text='An exchange order has been created for \"' + instance.requester_book.book_name +\n '\" from \"' + instance.requester.username +\n '\" and \"'+instance.offerrer_book.book_name +\n '\" from \"' + instance.offerrer.username +\n '\". Go to https://www.cadabra.co.in/transaction/orders/ to view the order. Thank You for ordering. Delivery of your book order will be attempted by CADABRA within one week.',\n recepient=instance.requester.email).start()\n\n send_sms(mobiles=instance.offerrer_address.phone_number, message='An exchange order has been created for \"' + instance.requester_book.book_name +\n '\" from user ' + instance.requester.username +\n ' and \"'+instance.offerrer_book.book_name +\n '\" from user ' + instance.offerrer.username +\n '. Go to https://www.cadabra.co.in/transaction/orders/ to view the order. Thank You for ordering. Delivery of your book order will be attempted by CADABRA within one week.')\n\n send_sms(mobiles=instance.requester_address.phone_number, message='An exchange order has been created for \"' + instance.requester_book.book_name +\n '\" from user ' + instance.requester.username +\n ' and \"'+instance.offerrer_book.book_name +\n '\" from user ' + instance.offerrer.username +\n '. Go to https://www.cadabra.co.in/transaction/orders/ to view the order. Thank You for ordering. Delivery of your book order will be attempted by CADABRA within one week.')\n\n# Done\n@receiver(post_save, sender=Requests)\ndef send_request_email(sender, instance, created, **kwargs):\n\n if created:\n\n EmailThreadAPI(subject='New Request for book \"'+instance.requester_book.book_name + '\"',\n text='You have recieved a new request from user \"'+instance.requester.username + '\" for book \"' +\n instance.requester_book.book_name +\n '\". Go to https://cadabra.co.in/transaction/offers/ for more details.', recepient=instance.offerrer.email).start()\n\n# Done\n@receiver(post_save, sender=FinalBuyOrder)\ndef send_buyorder_email(sender, instance, created, **kwargs):\n\n if created:\n\n EmailThreadAPI(subject='Buy Order successfully placed',\n text='You have successfully ordered book \"' + instance.book.book_name + '\" . Amount payable is Rs ' +\n str(instance.total_price) +\n '. Go to https://www.cadabra.co.in/transaction/orders/ to view the order. CADABRA will deliver the book within one week.',\n recepient=instance.user.email).start()\n\n EmailThreadAPI(subject='Order for your book \"' + instance.book.book_name + '\"',\n text='Your book \"' +\n instance.book.book_name + '\" has been sold to user'+instance.user.username+\n '. You can view the item at http://cadabra.co.in/userbooks/sold/. CADABRA will pick up the book within one week.',\n recepient=instance.seller.email).start()\n\n send_sms(mobiles=instance.selleraddress.phone_number, message='Your book \"' +\n instance.book.book_name + '\" has been sold. CADABRA will pick up the book within one week.')\n\n# Done\n@receiver(post_save, sender=CompletedTransaction)\ndef send_completed_transaction_email(sender, instance, created, **kwargs):\n\n if created:\n\n EmailThreadAPI(subject='Delivery Completed ',\n text='Delivery for \"' + instance.requester_book_name +\n '\" from \"' + instance.requester.username +\n '\" and \"'+instance.offerrer_book_name +\n '\" from \"' + instance.offerrer.username +\n '\" has been completed. Thank You for using CADABRA.',\n recepient=instance.offerrer.email).start()\n\n EmailThreadAPI(subject='Delivery Completed ',\n text='Delivery for \"' + instance.requester_book_name +\n '\" from \"' + instance.requester.username +\n '\" and \"'+instance.offerrer_book_name +\n '\" from \"' + instance.offerrer.username +\n '\" has been completed. Thank You for using CADABRA.',\n recepient=instance.requester.email).start()\n\n#Done\n@receiver(post_save, sender=CompletedBuyOrder)\ndef send_completed_buy_order_email(sender, instance, created, **kwargs):\n\n if created:\n\n EmailThreadAPI(subject='Delivery Completed ',\n text='Delivery for \"' + instance.book_name +\n '\" has been completed. Thank you for using CADABRA.',\n recepient=instance.user.email).start()\n\n# Done\n@receiver(pre_delete, sender=Requests)\ndef cancel_requests_email(sender, instance, **kwargs):\n\n EmailThreadAPI(subject='Request cancelled for \"' + instance.requester_book.book_name + '\"',\n text='Request for \"' + instance.requester_book.book_name + '\" from \"' +\n instance.requester.username +\n '\" is cancelled. Go to https://www.cadabra.co.in/ for more details.', recepient=instance.offerrer.email).start()\n\n# Done\n@receiver(pre_delete, sender=Transaction)\ndef delete_transaction_email(sender, instance, **kwargs):\n\n EmailThreadAPI(subject='Exchange Order cancelled ',\n text='An exchange order has been cancelled for book \"' + instance.requester_book.book_name +\n '\" from \"' + instance.requester.username +\n '\" and book \"'+instance.offerrer_book.book_name +\n '\" from \"' + instance.offerrer.username +\n '\".Go to https://www.cadabra.co.in/ for more books. Thank You for using CADABRA.',\n recepient=instance.offerrer.email).start()\n\n EmailThreadAPI(subject='Exchange Order cancelled ',\n text='An exchange order has been cancelled for book \"' + instance.requester_book.book_name +\n '\" from \"' + instance.requester.username +\n '\" and book \"'+instance.offerrer_book.book_name +\n '\" from \"' + instance.offerrer.username +\n '\".Go to https://www.cadabra.co.in/ for more books. Thank You for using CADABRA.',\n recepient=instance.requester.email).start()\n\n send_sms(mobiles=instance.offerrer_address.phone_number, message='An exchange order has been cancelled for book \"' + instance.requester_book.book_name +\n '\" from ' + instance.requester.username +\n ' and book '+instance.offerrer_book.book_name +\n ' from \"' + instance.offerrer.username +\n '\".')\n\n# Done\n@receiver(pre_delete, sender=FinalBuyOrder)\ndef delete_buyorder_email(sender, instance, **kwargs):\n\n EmailThreadAPI(subject='Buy Order cancelled',\n text='Buy Order for book \"' + instance.book.book_name + '\" is cancelled from user.',\n recepient=instance.seller.email).start()\n\n send_sms(mobiles=instance.selleraddress.phone_number, message='Buy Order for book \"' +\n instance.book.book_name + '\" is cancelled from user '+instance.user.username+'.')\n" }, { "alpha_fraction": 0.489130437374115, "alphanum_fraction": 0.573369562625885, "avg_line_length": 19.44444465637207, "blob_id": "e7391c1b377bfe78b7fffa8698a6188dbbb5a5f3", "content_id": "5c2fbd4892c909d3bab3fde69395bd5bcf254c4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/coreapp/migrations/0025_auto_20190104_0748.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-04 07:48\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0024_auto_20190104_0743'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='usercollection',\n old_name='user',\n new_name='owner',\n ),\n ]\n" }, { "alpha_fraction": 0.6172506809234619, "alphanum_fraction": 0.635579526424408, "avg_line_length": 37.64583206176758, "blob_id": "6b3f92492315b59a0cd9a073599440c8a438476c", "content_id": "34614000d30609e98333a15d6783de8648ab0af2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1855, "license_type": "no_license", "max_line_length": 174, "num_lines": 48, "path": "/coreapp/migrations/0071_auto_20190125_0309.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-25 03:09\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('coreapp', '0070_auto_20190125_0250'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='completedbuyorder',\n name='author_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='date_ordered',\n field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='seller',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='completed_seller', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='selleraddress',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='completed_selleraddress', to='coreapp.ShippingAddress'),\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='total_price',\n field=models.IntegerField(null=True),\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='useraddress',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='completed_address', to='coreapp.ShippingAddress'),\n ),\n ]\n" }, { "alpha_fraction": 0.5545774698257446, "alphanum_fraction": 0.5880281925201416, "avg_line_length": 23.69565200805664, "blob_id": "97ecc8fc6e76402e6c355d85c354226608344be0", "content_id": "721d8c0bd1028cbd349af364462d2b7756bc5897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "no_license", "max_line_length": 115, "num_lines": 23, "path": "/coreapp/migrations/0027_auto_20190105_0523.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 05:23\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0026_order'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='order',\n name='items',\n ),\n migrations.AddField(\n model_name='order',\n name='items',\n field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coreapp.Book'),\n ),\n ]\n" }, { "alpha_fraction": 0.5321683883666992, "alphanum_fraction": 0.5496425628662109, "avg_line_length": 26.369565963745117, "blob_id": "2eb78617aca737e80a5c85ef6ba4bad89a208c98", "content_id": "870bbf3c365309b2613cd08285631c5cf2c6c775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1259, "license_type": "no_license", "max_line_length": 74, "num_lines": 46, "path": "/coreapp/migrations/0070_auto_20190125_0250.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-25 02:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0069_completedbuyorder_completedtransaction'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='book',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='date_ordered',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='seller',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='selleraddress',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='total_price',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='user',\n ),\n migrations.RemoveField(\n model_name='completedbuyorder',\n name='useraddress',\n ),\n migrations.AddField(\n model_name='completedbuyorder',\n name='book_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7008892297744751, "alphanum_fraction": 0.7008892297744751, "avg_line_length": 50.54166793823242, "blob_id": "2d7b3db6528c560086326f0d49555ab2a2783325", "content_id": "e9419a2176fae023705cd0f29555b8fabb806179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1237, "license_type": "no_license", "max_line_length": 102, "num_lines": 24, "path": "/coreapp/urls.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom coreapp import views\nfrom django.urls import path\n\napp_name='coreapp'\n\nurlpatterns = [\n \n path('', views.BookListView.as_view(), name='list_entries'),\n path('buy/', views.BuyListView.as_view(), name='buy_entries'),\n path('exchange/', views.ExchangeListView.as_view(), name='exchange_entries'),\n path('newentry/', views.new_entry, name='new_entry'),\n path('bookdetail/<int:pk>/view', views.BookDetailView.as_view(), name='book_detail'),\n path('profile/',views.profile,name='profile'),\n path('profile/edit',views.update_profile,name='profile_edit'),\n path('profile/address/edit', views.update_address,name='address_edit'),\n path('signup/',views.SignUp.as_view(),name='signup'),\n path('userbooks/', views.UserBookListView.as_view(),name='userbooks'),\n path('userbooks/sold/',views.UserBookSoldItemsView.as_view(),name='sold-books'),\n path('userbooks/<str:username>', views.UserBookListViewForUser.as_view(),name='userbooksforuser'),\n path('userbooks/<int:pk>/update',views.PostUpdateView.as_view(),name='post-update'),\n path('userbooks/<int:pk>/delete',views.PostDeleteView.as_view(),name='post-delete'),\n path('aboutus/',views.aboutus,name='aboutus')\n]\n" }, { "alpha_fraction": 0.5278031229972839, "alphanum_fraction": 0.6189607977867126, "avg_line_length": 36.82758712768555, "blob_id": "b7973b18547438e5c04e259849d1c0ce9ddac990", "content_id": "ae3ced9849abd70b82fc7fb375fe5716144847d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 189, "num_lines": 29, "path": "/coreapp/migrations/0061_auto_20190119_1345.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 13:45\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0060_auto_20190118_1651'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='transaction',\n name='selleraddress',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='seller_address', to='coreapp.ShippingAddress'),\n ),\n migrations.AddField(\n model_name='transaction',\n name='useraddress',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_address', to='coreapp.ShippingAddress'),\n ),\n migrations.AlterField(\n model_name='shippingaddress',\n name='zip_code',\n field=models.CharField(choices=[('421202', '421202'), ('421201', '421201'), ('421204', '421204'), ('421203', '421203'), ('421301', '421301')], default='421202', max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.6104928255081177, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 34.94285583496094, "blob_id": "6a5a6249f4c536f6f401895ce5d2c492c0a45c5b", "content_id": "502fb48585eef97ba9b10b7a3e4c83e27c3f25c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 141, "num_lines": 35, "path": "/coreapp/migrations/0059_auto_20190118_1650.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-18 16:50\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0058_auto_20190118_1647'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='finalbuyorder',\n name='book',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='coreapp.Book'),\n ),\n migrations.AlterField(\n model_name='finalbuyorder',\n name='seller',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='seller', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AlterField(\n model_name='finalbuyorder',\n name='selleraddress',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='selleraddress', to='coreapp.ShippingAddress'),\n ),\n migrations.AlterField(\n model_name='finalbuyorder',\n name='useraddress',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='address', to='coreapp.ShippingAddress'),\n ),\n ]\n" }, { "alpha_fraction": 0.5478841662406921, "alphanum_fraction": 0.5708982944488525, "avg_line_length": 28.933332443237305, "blob_id": "9f704d89d0cbe19f69e506544d0c64619a073904", "content_id": "d0dc3aa64696b891690f02f708ea34d4233550d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1347, "license_type": "no_license", "max_line_length": 114, "num_lines": 45, "path": "/coreapp/migrations/0030_auto_20190105_0549.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 05:49\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0029_auto_20190105_0530'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='usercollectionitem',\n name='book',\n ),\n migrations.RemoveField(\n model_name='usercollection',\n name='items',\n ),\n migrations.AddField(\n model_name='usercollection',\n name='books',\n field=models.ManyToManyField(to='coreapp.Book'),\n ),\n migrations.AddField(\n model_name='usercollection',\n name='date_ordered',\n field=models.DateTimeField(auto_now=True),\n ),\n migrations.AlterField(\n model_name='order',\n name='owner',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='coreapp.Profile'),\n ),\n migrations.AlterField(\n model_name='usercollection',\n name='owner',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='coreapp.Profile'),\n ),\n migrations.DeleteModel(\n name='UserCollectionItem',\n ),\n ]\n" }, { "alpha_fraction": 0.7118320465087891, "alphanum_fraction": 0.7118320465087891, "avg_line_length": 48.904762268066406, "blob_id": "5fe22835d112d67d195f9f61d196f7c9ae60d844", "content_id": "60e949a183408955350f5ebb4372de33eb4087a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 116, "num_lines": 21, "path": "/transaction/urls.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom transaction import views\nfrom django.urls import path\n\napp_name = 'transaction'\n\nurlpatterns = [\n\n path('<int:book_id>/add', views.add_request, name='add_request'),\n path('requests/', views.RequestListView.as_view(), name='requests_view'),\n path('requests/<int:pk>/delete',views.RequestDeleteView.as_view(), name='request-delete'),\n path('offers/', views.OfferListView.as_view(), name='offers_view'),\n path('offers/<int:pk>/delete', views.OfferDeleteView.as_view(), name='offer-delete'),\n path('offers/<int:offer_id>/<int:book_id>/finaltransaction', views.final_transaction ,name='final-transaction'),\n path('orders/', views.TransactionListView.as_view(), name='orders_view'),\n path('orders/<int:pk>/delete', views.TransactionDeleteView.as_view(),name='order-delete'),\n path('orders/exchange-orders',\n views.TransactionCompletedExchangeOrder.as_view(), name='exchange-order'),\n path('orders/buy-orders', views.TransactionCompletedBuyOrder.as_view(), name='buy-order'),\n\n]\n" }, { "alpha_fraction": 0.557894766330719, "alphanum_fraction": 0.6231579184532166, "avg_line_length": 24, "blob_id": "3fb42b7c3fa9310d1bf624c24211ebfd153ab4ff", "content_id": "bbb82741f15d02e3762585065eb90583fffc5f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 120, "num_lines": 19, "path": "/coreapp/migrations/0033_auto_20190105_2116.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 21:16\n\nimport coreapp.models\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0032_auto_20190105_0613'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='image',\n field=models.ImageField(blank=True, default=coreapp.models.random_img, null=True, upload_to='book_images/'),\n ),\n ]\n" }, { "alpha_fraction": 0.5779816508293152, "alphanum_fraction": 0.5997706651687622, "avg_line_length": 31.296297073364258, "blob_id": "7123467e11fec213f0f3f56b01e7de3d6d05015d", "content_id": "04777bf05720ea19829202515e00bbd4cd85a338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 123, "num_lines": 27, "path": "/coreapp/migrations/0024_auto_20190104_0743.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-04 07:43\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0023_usercollection'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserCollectionItem',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_added', models.DateTimeField(auto_now=True)),\n ('book', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coreapp.Book')),\n ],\n ),\n migrations.AlterField(\n model_name='usercollection',\n name='items',\n field=models.ManyToManyField(to='coreapp.UserCollectionItem'),\n ),\n ]\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7174603343009949, "avg_line_length": 32.71428680419922, "blob_id": "6ffe57aea596a2749efe785828d2b9f655b2354f", "content_id": "c934b73c5a8cbeeb6172308769faef99d1c8d943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 129, "num_lines": 28, "path": "/transaction/transaction/templatetags/user_books_tag.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django import template\nfrom coreapp.models import Profile, Transaction, FinalBuyOrder\nfrom django.shortcuts import get_object_or_404\nregister = template.Library()\n\n\[email protected]\ndef user_books_for_user(collection_all, user_username):\n ordered_books = FinalBuyOrder.objects.values_list('book')\n requester_books = Transaction.objects.values_list('requester_book')\n offerrer_books = Transaction.objects.values_list('offerrer_book')\n \n user_profile = get_object_or_404(Profile, user__username=user_username)\n collection_items = collection_all.get(\n owner=user_profile)\n \n return collection_items.books.filter(\n sell_or_exchange='Exchange').exclude(id__in=ordered_books).exclude(id__in=offerrer_books).exclude(id__in=requester_books)\n\[email protected]\ndef author_list(authors):\n\n if authors:\n author_name = \",\".join(authors)\n\n return author_name + '.'\n else:\n return authors\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5917159914970398, "avg_line_length": 18.882352828979492, "blob_id": "689e40dd1597efdbada9911eb7e0be8ecab312ff", "content_id": "c9eb3a2fbd438c1a5c62dcd06ce618504396ac77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/coreapp/migrations/0049_remove_shippingaddress_country.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-12 04:38\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0048_auto_20190112_0433'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='shippingaddress',\n name='country',\n ),\n ]\n" }, { "alpha_fraction": 0.48633256554603577, "alphanum_fraction": 0.5216400623321533, "avg_line_length": 23.38888931274414, "blob_id": "da8742a17e33e39e594695692fb1ad601e722a1c", "content_id": "c86c8c5646a54ec61def24150711a495cff0f30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 878, "license_type": "no_license", "max_line_length": 88, "num_lines": 36, "path": "/coreapp/migrations/0022_auto_20190104_0550.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-04 05:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0021_auto_20190104_0332'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='order',\n name='items',\n ),\n migrations.RemoveField(\n model_name='order',\n name='owner',\n ),\n migrations.RemoveField(\n model_name='orderitem',\n name='book',\n ),\n migrations.AlterField(\n model_name='profile',\n name='profile_pic',\n field=models.ImageField(default='default.png', upload_to='profile_images/'),\n ),\n migrations.DeleteModel(\n name='Order',\n ),\n migrations.DeleteModel(\n name='OrderItem',\n ),\n ]\n" }, { "alpha_fraction": 0.5164557099342346, "alphanum_fraction": 0.594936728477478, "avg_line_length": 20.94444465637207, "blob_id": "84e6a7af6c0c215260e1261817ed71ef89ca2c07", "content_id": "64d24c55182823f9e3b6f067ddc41f0bc5622399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/coreapp/migrations/0066_finalbuyorder_total_price.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 14:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0065_auto_20190119_1415'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='finalbuyorder',\n name='total_price',\n field=models.IntegerField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5543932914733887, "alphanum_fraction": 0.6234309673309326, "avg_line_length": 25.55555534362793, "blob_id": "f66cd02515055931e68a2fc4212054b97d084a9c", "content_id": "9524d324b1fdf8a9c54f15e07539d6ee01ac7502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "no_license", "max_line_length": 145, "num_lines": 18, "path": "/coreapp/migrations/0068_auto_20190120_1419.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-20 14:19\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0067_auto_20190119_1549'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='price',\n field=models.IntegerField(blank=True, help_text='We would be deducting 20 rupees from item price for delivery purposes.', null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6903790235519409, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 38.88372039794922, "blob_id": "1542d218c2a133c5f15a99f7bd22d2cc1f474545", "content_id": "0629b3ac9de656ae7309f95f2573a095c009f089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8575, "license_type": "no_license", "max_line_length": 188, "num_lines": 215, "path": "/transaction/views.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic import ListView\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom coreapp.models import Book, Requests, Transaction, UserCollection, FinalBuyOrder, OldRequests, Profile, ShippingAddress, CompletedTransaction, CompletedBuyOrder, cancel_requests_email\nfrom coreapp.models import Requests\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.views import generic\nfrom django.contrib import messages\nfrom django.urls import reverse_lazy, reverse\nfrom coreapp.forms import ShippingAddressForm\nfrom django.db.models import Q\nfrom django.utils import timezone\nimport datetime\nfrom django.db import transaction\nfrom django.db.models import signals\n\nordered_books = FinalBuyOrder.objects.values_list('book')\nrequester_books = Transaction.objects.values_list('requester_book')\nofferrer_books = Transaction.objects.values_list('offerrer_book')\n\[email protected]\n@login_required\ndef final_transaction(request, offer_id, book_id):\n offerrer_book = get_object_or_404(Book, id=book_id)\n new_request = get_object_or_404(Requests,id=offer_id)\n address_form = ShippingAddressForm(\n request.POST, instance=request.user.profile.address)\n\n if request.method == \"POST\" and 'Yes' in request.POST:\n offerrer_address = get_object_or_404(ShippingAddress, profile=request.user.profile)\n\n # requester_profile = get_object_or_404(\n # Profile, user=new_request.requester)\n requester_address = get_object_or_404(\n ShippingAddress, profile=new_request.requester.profile)\n\n new_order = Transaction(requester=new_request.requester, offerrer=new_request.offerrer,\n requester_book=new_request.requester_book, offerrer_book=offerrer_book, requester_address=requester_address, offerrer_address=offerrer_address)\n old_request = OldRequests(requester=new_request.requester, offerrer=new_request.offerrer,\n requester_book=new_request.requester_book)\n\n # delete entry from requests\n signals.pre_delete.disconnect(cancel_requests_email, sender=Requests)\n\n new_request.delete()\n\n signals.pre_delete.connect(cancel_requests_email, sender=Requests)\n\n \n \n # save old request\n # save new order\n new_order.save()\n old_request.save()\n\n if not UserCollection.objects.get(\n owner=new_request.requester.profile).books.filter(\n sell_or_exchange='Exchange').exclude(id__in=offerrer_books).exclude(id__in=requester_books):\n Requests.objects.filter(requester=new_request.requester).delete()\n\n return redirect('transaction:orders_view')\n\n if request.method == 'POST' and 'updateadd' in request.POST:\n if address_form.is_valid():\n address_form.save()\n messages.success(request, ('Address successfully updated!'))\n\n offer = get_object_or_404(Requests,id=offer_id)\n address = get_object_or_404(ShippingAddress, profile=request.user.profile)\n context = {'offer': offer, 'book': offerrer_book,\n 'address': address, 'address_form': address_form}\n return render(request,'transaction_final.html',context)\n\n\[email protected]\n@login_required\ndef add_request(request,book_id):\n book = get_object_or_404(Book, id=book_id)\n new_request = Requests(requester=request.user, offerrer=book.user , requester_book=book)\n\n address = ShippingAddress.objects.get(profile=request.user.profile)\n if address.status():\n messages.info(request, \"You need to add address in profile to make request !\")\n else:\n if (UserCollection.objects.get(\n owner=request.user.profile).books.exclude(\n id__in=requester_books).exclude(id__in=offerrer_books).filter(sell_or_exchange=\"Exchange\").exists()):\n\n if Requests.objects.filter(requester=request.user, offerrer=book.user, requester_book=book).exists():\n messages.info(request,\"Request for this book already made!\")\n else:\n date_from = datetime.datetime.now(\n tz=timezone.utc) - datetime.timedelta(days=1)\n\n no_of_requests_made_in_one_day = Requests.objects.filter(requester=request.user, timestamp__gte=date_from).count()\n\n if no_of_requests_made_in_one_day>5:\n messages.warning(request,\"Maximum requests exceeded for one day : you can make maximum of 6 requests\")\n else:\n messages.info(\n request, \"New Request !\")\n\n new_request.save()\n\n return redirect('transaction:requests_view')\n else:\n messages.info(request, ('You need to add \"Exchange\" items to your collection to make a request!'))\n\n return redirect('coreapp:list_entries')\n\n\nclass RequestListView(LoginRequiredMixin, generic.ListView):\n model = Requests\n template_name = 'transaction_request.html'\n context_object_name = 'requests'\n\n def get_queryset(self):\n return Requests.objects.filter(requester=self.request.user).order_by('timestamp')\n\n\nclass RequestDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):\n model = Requests\n success_url = reverse_lazy('transaction:requests_view')\n template_name = 'transaction_request_confirm_delete.html'\n\n def test_func(self):\n request_object = self.get_object()\n if self.request.user == request_object.requester:\n return True\n return False\n\nclass OfferListView(LoginRequiredMixin, generic.ListView):\n model = Requests\n template_name = 'transaction_offer.html'\n context_object_name = 'offers'\n\n def get_queryset(self):\n return Requests.objects.filter(offerrer=self.request.user).order_by('timestamp')\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n context['collection_all'] = UserCollection.objects.all()\n\n return context\n\n\n\nclass OfferDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):\n model = Requests\n success_url = reverse_lazy('transaction:offers_view')\n template_name = 'transaction_offer_confirm_delete.html'\n\n def test_func(self):\n offer = self.get_object()\n if self.request.user == offer.offerrer:\n return True\n return False\n\n def delete(self, request, *args, **kwargs):\n\n signals.pre_delete.disconnect(cancel_requests_email, sender=Requests)\n\n self.object = self.get_object()\n self.object.delete()\n\n signals.pre_delete.connect(cancel_requests_email, sender=Requests)\n\n return redirect(self.get_success_url())\n\nclass TransactionListView(LoginRequiredMixin, generic.ListView):\n model = Transaction\n template_name = 'transaction_order.html'\n context_object_name = 'orders'\n\n def get_queryset(self):\n return Transaction.objects.filter(Q(offerrer=self.request.user) | Q(requester=self.request.user)).order_by('timestamp')\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n context['buy_order'] = FinalBuyOrder.objects.filter(\n user=self.request.user).order_by('-date_ordered')\n return context\n\n\nclass TransactionDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):\n model = Transaction\n success_url = reverse_lazy('transaction:orders_view')\n template_name = 'transaction_order_confirm_delete.html'\n\n def test_func(self):\n transaction = self.get_object()\n if self.request.user == transaction.requester or self.request.user == transaction.offerrer:\n return True\n return False \n\n\nclass TransactionCompletedExchangeOrder(LoginRequiredMixin, generic.ListView):\n model = CompletedTransaction\n template_name = 'transaction_completed_exchange_order.html'\n context_object_name = 'orders'\n\n def get_queryset(self):\n return CompletedTransaction.objects.filter(Q(offerrer=self.request.user) | Q(requester=self.request.user)).order_by('timestamp')\n\n\nclass TransactionCompletedBuyOrder(LoginRequiredMixin, generic.ListView):\n model = CompletedBuyOrder\n template_name = 'transaction_completed_buy_order.html'\n context_object_name = 'buy_order'\n\n def get_queryset(self):\n return CompletedBuyOrder.objects.filter(user=self.request.user).order_by('date_ordered')\n" }, { "alpha_fraction": 0.6369545459747314, "alphanum_fraction": 0.6392707824707031, "avg_line_length": 38.13450241088867, "blob_id": "703811f7c33c5b79f40127f0b7b031302d65a2c7", "content_id": "70fc87ad8e2943aa3fc86e48e4ed7f37a84d6286", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13384, "license_type": "no_license", "max_line_length": 184, "num_lines": 342, "path": "/coreapp/views.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.generic import CreateView, ListView, DetailView, UpdateView, DeleteView\nfrom django.views.generic.edit import FormView\nfrom django.urls import reverse_lazy, reverse\nfrom .forms import UserCreationForm, NewEntryForm, UserForm, ProfileForm, ShippingAddressForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom coreapp.models import Book, Profile, UserCollection, ShippingAddress, FinalBuyOrder, Transaction, CompletedBuyOrder, Requests\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.db.models import Q\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.core.cache import cache\nfrom django.core.paginator import Paginator\nfrom django.db.models import Case, When\nimport random\nimport requests\nimport json\nfrom nofapapp.settings import GOOGLE_BOOKS_URL\n\nordered_books = FinalBuyOrder.objects.values_list('book')\nrequester_books = Transaction.objects.values_list('requester_book')\nofferrer_books = Transaction.objects.values_list('offerrer_book')\n\n@login_required\ndef profile(request):\n address = ShippingAddress.objects.get(profile=request.user.profile)\n return render(request, 'profile.html', {'profile': request.user.profile, 'address': address})\n\n\nclass SignUp(SuccessMessageMixin, CreateView):\n form_class = UserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'signup.html'\n success_message = 'Account Created! You can now Login!'\n\nclass BookListView( ListView):\n model = Book\n template_name = 'list_entries.html'\n context_object_name = 'books'\n paginate_by = 12\n\n def get_queryset(self):\n # ordered_books = FinalBuyOrder.objects.values_list('book')\n # requester_books = Transaction.objects.values_list('requester_book')\n # offerrer_books = Transaction.objects.values_list('offerrer_book')\n\n if not self.request.session.get('all_books'):\n self.request.session['all_books'] = random.randrange(0, 3)\n \n id_list = cache.get('all_books_%d' %\n self.request.session['all_books'])\n\n if not id_list:\n id_list = [object['id']\n for object in Book.objects.values('id').all().order_by('?')]\n\n cache.set('all_books_%d' %\n self.request.session['all_books'], id_list, 200)\n\n preserved = Case(*[When(pk=pk, then=pos)\n for pos, pk in enumerate(id_list)])\n\n if self.request.user.is_authenticated:\n book_object_list = Book.objects.exclude(user=self.request.user).exclude(id__in=ordered_books).exclude(\n id__in=requester_books).exclude(id__in=offerrer_books).filter(id__in=id_list).order_by(preserved)\n else:\n book_object_list = Book.objects.exclude(id__in=ordered_books).exclude(\n id__in=requester_books).exclude(id__in=offerrer_books).filter(id__in=id_list).order_by(preserved)\n\n return book_object_list\n\n # return Book.objects.exclude(user=self.request.user).exclude(id__in=ordered_books).exclude(\n # id__in=requester_books).exclude(id__in=offerrer_books).order_by('-created_at')\n\nclass BuyListView(ListView):\n model = Book\n template_name = 'list_entries.html'\n context_object_name = 'books'\n paginate_by = 12\n\n def get_queryset(self):\n # ordered_books = FinalBuyOrder.objects.values_list('book')\n\n if not self.request.session.get('buy_books'):\n self.request.session['buy_books'] = random.randrange(0, 3)\n \n id_list = cache.get('buy_books_%d' %\n self.request.session['buy_books'])\n\n if not id_list:\n id_list = [object['id']\n for object in Book.objects.values('id').all().order_by('?')]\n\n cache.set('buy_books_%d' %\n self.request.session['buy_books'], id_list, 200)\n\n preserved = Case(*[When(pk=pk, then=pos)\n for pos, pk in enumerate(id_list)])\n\n \n if self.request.user.is_authenticated:\n\n book_object_list = Book.objects.exclude(user=self.request.user).exclude(\n id__in=ordered_books).filter(sell_or_exchange='Sell').filter(id__in=id_list).order_by(preserved)\n\n else:\n book_object_list = Book.objects.filter(id__in=id_list).exclude(\n id__in=ordered_books).filter(\n sell_or_exchange='Sell').order_by(preserved)\n\n return book_object_list\n\n # return Book.objects.exclude(user=self.request.user).exclude(id__in=ordered_books).filter(sell_or_exchange='Sell').order_by('-created_at')\n\n\nclass ExchangeListView( ListView):\n model = Book\n template_name = 'list_entries.html'\n context_object_name = 'books'\n paginate_by = 12\n\n def get_queryset(self):\n # requester_books = Transaction.objects.values_list('requester_book')\n # offerrer_books = Transaction.objects.values_list('offerrer_book')\n if not self.request.session.get('exchange_books'):\n self.request.session['exchange_books'] = random.randrange(0, 3)\n \n id_list = cache.get('exchange_books_%d' %\n self.request.session['exchange_books'])\n\n if not id_list:\n id_list = [object['id']\n for object in Book.objects.values('id').all().order_by('?')]\n\n cache.set('exchange_books_%d' %\n self.request.session['exchange_books'], id_list, 200)\n\n preserved = Case(*[When(pk=pk, then=pos)\n for pos, pk in enumerate(id_list)])\n\n \n if self.request.user.is_authenticated:\n\n book_object_list = Book.objects.exclude(user=self.request.user).exclude(id__in=requester_books).exclude(\n id__in=offerrer_books).filter(sell_or_exchange='Exchange').order_by(preserved)\n\n else:\n\n book_object_list = Book.objects.exclude(id__in=requester_books).exclude(\n id__in=offerrer_books).filter(id__in=id_list).filter(\n sell_or_exchange='Exchange').order_by(preserved)\n\n\n return book_object_list\n\n # return Book.objects.exclude(user=self.request.user).exclude(id__in=requester_books).exclude(id__in=offerrer_books).filter(sell_or_exchange='Exchange').order_by('-created_at')\n\n\nclass UserBookListView(LoginRequiredMixin, ListView):\n model = Book\n template_name = 'user_books_list_entries.html'\n context_object_name = 'books'\n ordering = ['-created_at']\n\n def get_queryset(self):\n # ordered_books = FinalBuyOrder.objects.values_list('book')\n # requester_books = Transaction.objects.values_list('requester_book')\n # offerrer_books = Transaction.objects.values_list('offerrer_book')\n collection_items = UserCollection.objects.get(\n owner=self.request.user.profile)\n\n return collection_items.books.exclude(id__in=ordered_books).exclude(\n id__in=requester_books).exclude(id__in=offerrer_books)\n\n\nclass UserBookSoldItemsView(LoginRequiredMixin, ListView):\n model = Book\n template_name = 'user_books_sold_list_entries.html'\n context_object_name = 'books'\n ordering = ['-created_at']\n\n def get_queryset(self):\n # ordered_books = FinalBuyOrder.objects.values_list('book')\n # requester_books = Transaction.objects.values_list('requester_book')\n # offerrer_books = Transaction.objects.values_list('offerrer_book')\n return CompletedBuyOrder.objects.filter(seller=self.request.user).order_by('date_ordered')\n\n\nclass UserBookListViewForUser( ListView):\n model = Book\n template_name = 'collection_user_entries.html'\n context_object_name = 'books'\n ordering = ['-created_at']\n\n def get_queryset(self):\n user = self.kwargs['username']\n\n user_profile = get_object_or_404(Profile, user__username=user)\n collection_items = UserCollection.objects.get(\n owner=user_profile)\n\n # ordered_books = FinalBuyOrder.objects.values_list('book')\n # requester_books = Transaction.objects.values_list('requester_book')\n # offerrer_books = Transaction.objects.values_list('offerrer_book')\n return collection_items.books.exclude(id__in=ordered_books).exclude(\n id__in=requester_books).exclude(id__in=offerrer_books)\n\n\nclass BookDetailView(DetailView):\n model = Book\n template_name = 'book_detail_view.html'\n\n\n@login_required\ndef new_entry(request):\n if request.method == 'POST' and 'check' in request.POST:\n new_entry_form = NewEntryForm(request.POST, instance=request.user)\n book_name = new_entry_form.data['book_name']\n if book_name:\n parms = {\"q\": book_name, \"printType\": \"books\", \"projection\": \"lite\"}\n r = requests.get(\n url=GOOGLE_BOOKS_URL, params=parms)\n items = json.loads(r.text)\n return render(request, 'new_entry.html', {'form': new_entry_form, 'items': items['items']})\n else:\n return render(request, 'new_entry.html', {'form': new_entry_form})\n\n if request.method == 'POST' and 'submitentry' in request.POST:\n new_entry_form = NewEntryForm(request.POST, instance=request.user)\n if new_entry_form.is_valid():\n\n address = get_object_or_404(\n ShippingAddress, profile=request.user.profile)\n if address.address1 == '':\n messages.info(\n request, 'You need to update address in profile to add a book!')\n return redirect('coreapp:new_entry')\n\n if new_entry_form.cleaned_data['price'] is None and new_entry_form.cleaned_data['sell_or_exchange'] == 'Sell':\n messages.info(request,\"Price cannot be blank in Sell order\")\n return redirect('coreapp:new_entry')\n \n book = Book()\n book.user = request.user\n book.book_name = new_entry_form.cleaned_data['book_name']\n book.author_name = new_entry_form.cleaned_data['author_name']\n book.price = new_entry_form.cleaned_data['price']\n book.description = new_entry_form.cleaned_data['description']\n book.sell_or_exchange = new_entry_form.cleaned_data['sell_or_exchange']\n book.image_url = new_entry_form.cleaned_data['image_url']\n book.save()\n collection, status = UserCollection.objects.get_or_create(\n owner=request.user.profile)\n collection.books.add(book)\n collection.save()\n return redirect('coreapp:userbooks')\n else:\n return render(request, 'new_entry.html', {'form': new_entry_form})\n\n new_entry_form = NewEntryForm(instance=request.user)\n\n return render(request, 'new_entry.html', {\n 'form': new_entry_form,\n })\n\n\nclass PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\n model = Book\n form_class = NewEntryForm\n template_name = 'new_entry_update.html'\n success_url = reverse_lazy('coreapp:userbooks')\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super().form_valid(form)\n\n def test_func(self):\n book = self.get_object()\n if self.request.user == book.user:\n return True\n return False\n\n\nclass PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):\n model = Book\n success_url = reverse_lazy('coreapp:userbooks')\n template_name = 'book_confirm_delete.html'\n\n def test_func(self):\n book = self.get_object()\n if self.request.user == book.user:\n return True\n return False\n\n def delete(self, *args, **kwargs):\n reponse = super(PostDeleteView, self).delete(*args, *kwargs)\n if not (UserCollection.objects.get(\n owner=self.request.user.profile).books.filter(\n sell_or_exchange='Exchange').exclude(id__in=offerrer_books).exclude(id__in=requester_books).exists()):\n Requests.objects.filter(requester=self.request.user).delete()\n\n return reponse\n\n\n@login_required\ndef update_profile(request):\n if request.method == 'POST':\n user_form = UserForm(request.POST, instance=request.user)\n if user_form.is_valid():\n user_form.save()\n messages.success(request, (\n 'Your profile was successfully updated!'))\n return redirect('coreapp:profile')\n else:\n user_form = UserForm(instance=request.user)\n return render(request, 'profile_edit.html', {\n 'user_form': user_form,\n\n })\n\n\n@login_required\ndef update_address(request):\n if request.method == 'POST':\n address_form = ShippingAddressForm(\n request.POST, instance=request.user.profile.address)\n if address_form.is_valid():\n address_form.save()\n messages.success(request, ('Address successfully updated!'))\n return redirect('coreapp:profile')\n\n else:\n address_form = ShippingAddressForm(\n instance=request.user.profile.address)\n return render(request, 'address_edit.html', {\n 'address_form': address_form\n })\n\n\n\ndef aboutus(request):\n return render(request, 'aboutus.html')\n" }, { "alpha_fraction": 0.5205724239349365, "alphanum_fraction": 0.5760286450386047, "avg_line_length": 23.30434799194336, "blob_id": "5d839030a1223edb218a7eb583e8b6b6e3a5ef2d", "content_id": "f77ee904de559f4c1c795e58bb6fde6f650b462e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/coreapp/migrations/0056_auto_20190117_1332.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-17 13:32\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0055_auto_20190117_0425'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='finalbuyorder',\n old_name='selleraddres',\n new_name='selleraddress',\n ),\n migrations.AddField(\n model_name='finalbuyorder',\n name='date_ordered',\n field=models.DateTimeField(auto_now=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6549270749092102, "alphanum_fraction": 0.6659551858901978, "avg_line_length": 65.92857360839844, "blob_id": "354f9db3ea30b90faaa63d7a904e85a017ca54c3", "content_id": "201bc4c7f3ab33ef89b265c14ce5805ea26f5f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2811, "license_type": "no_license", "max_line_length": 183, "num_lines": 42, "path": "/coreapp/migrations/0069_completedbuyorder_completedtransaction.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-22 12:38\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('coreapp', '0068_auto_20190120_1419'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CompletedBuyOrder',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_ordered', models.DateTimeField(auto_now_add=True)),\n ('total_price', models.IntegerField(null=True)),\n ('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='coreapp.Book')),\n ('seller', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_seller', to=settings.AUTH_USER_MODEL)),\n ('selleraddress', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_selleraddress', to='coreapp.ShippingAddress')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_user', to=settings.AUTH_USER_MODEL)),\n ('useraddress', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_address', to='coreapp.ShippingAddress')),\n ],\n ),\n migrations.CreateModel(\n name='CompletedTransaction',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('offerrer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_offerrer', to=settings.AUTH_USER_MODEL)),\n ('offerrer_address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='completed_seller_address', to='coreapp.ShippingAddress')),\n ('offerrer_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_offerrer_book_from_user', to='coreapp.Book')),\n ('requester', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_requester', to=settings.AUTH_USER_MODEL)),\n ('requester_address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='completed_user_address', to='coreapp.ShippingAddress')),\n ('requester_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completed_requested_book_from_user', to='coreapp.Book')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.4863387942314148, "alphanum_fraction": 0.5710382461547852, "avg_line_length": 19.33333396911621, "blob_id": "cac3603c7a8e4a588b005625ee6008170d5f95eb", "content_id": "6a5feb3b43ae06086a90e6d51c111940379f54f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/coreapp/migrations/0057_auto_20190117_1338.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-17 13:38\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0056_auto_20190117_1332'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='finalbuyorder',\n old_name='Book',\n new_name='book',\n ),\n ]\n" }, { "alpha_fraction": 0.5609567761421204, "alphanum_fraction": 0.584876537322998, "avg_line_length": 30.609756469726562, "blob_id": "c5a9d63271a520e765d3c315af24d554f00fae5a", "content_id": "9ffbb540c8ed5c480d34fede60c2a57c3d85b19c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1296, "license_type": "no_license", "max_line_length": 74, "num_lines": 41, "path": "/coreapp/migrations/0073_auto_20190125_0324.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-25 03:24\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0072_completedbuyorder_user'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='completedtransaction',\n name='offerrer_book',\n ),\n migrations.RemoveField(\n model_name='completedtransaction',\n name='requester_book',\n ),\n migrations.AddField(\n model_name='completedtransaction',\n name='offerrer_author_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AddField(\n model_name='completedtransaction',\n name='offerrer_book_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AddField(\n model_name='completedtransaction',\n name='requester_author_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n migrations.AddField(\n model_name='completedtransaction',\n name='requester_book_name',\n field=models.CharField(blank=True, max_length=100, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5834563970565796, "alphanum_fraction": 0.6602658629417419, "avg_line_length": 34.6315803527832, "blob_id": "b57272038babaae363eb94e037132a1cb85926db", "content_id": "89f5f03ed962a96638cdca4a1d6bc48a1736eb9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 296, "num_lines": 19, "path": "/coreapp/migrations/0081_auto_20190207_1821.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-02-07 18:21\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0080_auto_20190130_0336'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='phone_number',\n field=models.CharField(help_text='Enter your 10 digit phone number without any prefix code.', max_length=17, validators=[django.core.validators.RegexValidator(message=\"Phone number must be entered in the format: '+9999999999'. Up to 15 digits allowed.\", regex='^\\\\+?1?\\\\d{10,15}$')]),\n ),\n ]\n" }, { "alpha_fraction": 0.49673911929130554, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 39, "blob_id": "0ca52c0a6ea88a26159ddbfe5b4107c36e22c3fa", "content_id": "0f28554a5600f2a04be2a73ddce40213ba86b571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 246, "num_lines": 23, "path": "/coreapp/migrations/0064_auto_20190119_1412.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 14:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0063_auto_20190119_1409'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='sell_or_exchange',\n field=models.CharField(choices=[('Sell', 'Sell'), ('Exchange', 'Exchange')], default='Exchange', help_text='By adding items to exchange you can make requests to ther users for exchange!', max_length=100),\n ),\n migrations.AlterField(\n model_name='shippingaddress',\n name='zip_code',\n field=models.CharField(choices=[('421202', '421202'), ('421201', '421201'), ('421204', '421204'), ('421203', '421203'), ('421301', '421301')], default='421202', help_text='We only operate in these locations for now!', max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.5302245020866394, "alphanum_fraction": 0.5682210922241211, "avg_line_length": 25.31818199157715, "blob_id": "d660971e349b0bda5b5ff6bf68c2ff264b21612a", "content_id": "436c78dc33be8b1d2fb1ec5c0dadc783bcb1edea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 125, "num_lines": 22, "path": "/coreapp/migrations/0051_auto_20190116_0910.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-16 09:10\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0050_book_buy_or_exchange'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='book',\n name='buy_or_exchange',\n ),\n migrations.AddField(\n model_name='book',\n name='sell_or_exchange',\n field=models.CharField(choices=[('Sell', 'Sell'), ('Exchange', 'Exchange')], default='Exchange', max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.490835040807724, "alphanum_fraction": 0.7006109952926636, "avg_line_length": 17.185184478759766, "blob_id": "f54ffa9cc358ad6c7038323fce935fba77c6a4c2", "content_id": "3c43dc39071228f97f943adf47c69d2c476357b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 491, "license_type": "no_license", "max_line_length": 32, "num_lines": 27, "path": "/requirements.txt", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "appdirs==1.4.3\nastroid==1.6.5\nattrs==18.2.0\ncertifi==2018.11.29\ndj-database-url==0.4.2\nDjango==2.1.4\ndjango-autocomplete-light==3.3.2\ndjango-compat==1.0.15\ndjango-crispy-forms==1.7.2\ndjango-import-export==1.2.0\ndjango-widget-tweaks==1.4.3\nopenpyxl==2.5.12\nPillow==5.3.0\npsycopg2==2.7.6.1\npsycopg2-binary==2.7.6.1\npython-decouple==3.1\npytz==2018.7\nPyYAML==3.13\nrequests==2.21.0\nsix==1.12.0\ntablib==0.12.1\ntoml==0.10.0\nunicodecsv==0.14.1\nurllib3==1.24.1\nwrapt==1.10.11\nxlrd==1.2.0\nxlwt==1.3.0\n" }, { "alpha_fraction": 0.5806060433387756, "alphanum_fraction": 0.6266666650772095, "avg_line_length": 33.375, "blob_id": "5e4a3a4c1663436cceff751ccbd4add7223b19ef", "content_id": "427e6651e406fc1a7e3b2d00413ba200537f89af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 225, "num_lines": 24, "path": "/coreapp/migrations/0067_auto_20190119_1549.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 15:49\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0066_finalbuyorder_total_price'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='image',\n field=models.ImageField(blank=True, null=True, upload_to='book_images/', verbose_name='Book Image'),\n ),\n migrations.AlterField(\n model_name='shippingaddress',\n name='phone_number',\n field=models.CharField(max_length=17, validators=[django.core.validators.RegexValidator(message=\"Phone number must be entered in the format: '+9999999999'. Up to 15 digits allowed.\", regex='^\\\\+?1?\\\\d{10,15}$')]),\n ),\n ]\n" }, { "alpha_fraction": 0.5449233055114746, "alphanum_fraction": 0.5675675868988037, "avg_line_length": 32.39024353027344, "blob_id": "98ea602bed3645e9aba1150568725d5ee7018ff2", "content_id": "ace762d837b08ff7c94da4d63f94b2103ae4b964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1369, "license_type": "no_license", "max_line_length": 123, "num_lines": 41, "path": "/cart/migrations/0001_initial.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-04 05:50\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('coreapp', '0022_auto_20190104_0550'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_ordered', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='OrderItem',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_added', models.DateTimeField(auto_now=True)),\n ('book', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coreapp.Book')),\n ],\n ),\n migrations.AddField(\n model_name='order',\n name='items',\n field=models.ManyToManyField(to='cart.OrderItem'),\n ),\n migrations.AddField(\n model_name='order',\n name='owner',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coreapp.Profile'),\n ),\n ]\n" }, { "alpha_fraction": 0.69028639793396, "alphanum_fraction": 0.6964865922927856, "avg_line_length": 37.4886360168457, "blob_id": "a336fbde66a587e3e55669a3a132c957e0b08a2a", "content_id": "5bcdf1070076693c409d43ee769e2cee235ac428", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3387, "license_type": "no_license", "max_line_length": 124, "num_lines": 88, "path": "/cart/views.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import generic\nfrom django.urls import reverse_lazy, reverse\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom coreapp.models import Book, Profile, Order, ShippingAddress, FinalBuyOrder\nfrom coreapp.forms import ShippingAddressForm\nfrom django.db.models import Q\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.db.models import Sum\n\n\n@login_required\ndef add_to_cart(request, item_id):\n book = get_object_or_404(Book,id=item_id)\n user_order, status = Order.objects.get_or_create(\n owner=request.user.profile)\n if book in user_order.get_cart_items():\n messages.warning(request, 'Item Already in Cart!')\n return redirect(reverse('coreapp:buy_entries'))\n user_order.items.add(book)\n user_order.save()\n messages.info(request, \"Item added to cart!\")\n return redirect(reverse('coreapp:buy_entries'))\n\n@login_required\ndef delete_from_cart(request, item_id):\n book = get_object_or_404(Book,id=item_id)\n orders = Order.objects.get(owner=request.user.profile)\n orders.items.remove(book)\n\n messages.info(request, \"Item has been deleted\")\n return redirect(reverse('cart:cart_items'))\n\n@login_required\ndef cart_list_entries_view(request):\n orders = Order.objects.get(owner=request.user.profile)\n\n address_form = ShippingAddressForm(\n request.POST, instance=request.user.profile.address)\n\n user_address = get_object_or_404(\n ShippingAddress, profile=request.user.profile)\n orderitems = Order.objects.get(owner=request.user.profile)\n orders = orderitems.get_cart_items()\n\n total_price = Order.objects.filter(\n owner=request.user.profile).aggregate(Sum('items__price'))\n\n total_price = (list(total_price.values())[0])\n\n if request.method == \"POST\" and 'Yes' in request.POST:\n\n for order in orders:\n\n seller_profile = get_object_or_404(Profile, user=order.user)\n seller_address = get_object_or_404(\n ShippingAddress, profile=seller_profile)\n\n FinalBuyOrder.objects.create(user=request.user, book=order, seller=order.user,\n useraddress=user_address, selleraddress=seller_address, total_price=total_price+20)\n orderitems.items.remove(order)\n\n messages.success(request, ('Item successfully Ordered!'))\n return redirect('transaction:orders_view')\n\n if request.method == 'POST' and 'updateadd' in request.POST:\n if address_form.is_valid():\n address_form.save()\n messages.success(request, ('Address successfully updated!'))\n return redirect('cart:cart_items')\n\n context = {'orders': orders, 'address': user_address,\n 'address_form': address_form, 'total_price': total_price}\n return render(request, 'cart_list_entries.html', context)\n\n\nclass FinalBuyOrderDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):\n model = FinalBuyOrder\n success_url = reverse_lazy('transaction:orders_view')\n template_name = 'final_order_confirm_delete.html'\n\n def test_func(self):\n order = self.get_object()\n if self.request.user == order.user:\n return True\n return False\n" }, { "alpha_fraction": 0.5085574388504028, "alphanum_fraction": 0.591687023639679, "avg_line_length": 21.72222137451172, "blob_id": "a76a414923cf4a2ed1b1a8e06c0f93e6bb12e0de", "content_id": "8fa66d919158da3eeabf2e4f6af7165bc53c678d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/coreapp/migrations/0074_book_image_url.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-26 11:41\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0073_auto_20190125_0324'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='book',\n name='image_url',\n field=models.CharField(blank=True, max_length=200, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.510152280330658, "alphanum_fraction": 0.5888324975967407, "avg_line_length": 20.88888931274414, "blob_id": "32311758411d3480303cc22489598a3df83a3308", "content_id": "523ad08d84372744bf2ef0de5218ffa2b76d832b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/coreapp/migrations/0053_auto_20190116_1608.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-16 16:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0052_auto_20190116_1519'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='price',\n field=models.IntegerField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6589259505271912, "alphanum_fraction": 0.6661828756332397, "avg_line_length": 33.45000076293945, "blob_id": "f9a386bac7e27f81e47bc51212c4e7f0141f3106", "content_id": "52bf91f88a15a44e94b01a272fc97d33229b541e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 85, "num_lines": 20, "path": "/search/forms.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom coreapp.models import Book, Profile\nfrom dal import autocomplete\n\nclass SearchForm(forms.Form):\n\n search = forms.CharField(\n max_length=100, widget=autocomplete.ModelSelect2(url='country-autocomplete'))\n\n # class Meta:\n # widgets = {'search': autocomplete.ListSelect2(\n # url='content-autocomplete')}\n\n # def __init__(self, *args, **kwargs):\n # super(FeedbackInfoInputModelForm, self).__init__(*args, **kwargs)\n # self.fields['search'].widget = forms.TextInput(attrs={\n # 'id': 'search',\n # })\n" }, { "alpha_fraction": 0.5928417444229126, "alphanum_fraction": 0.6184068918228149, "avg_line_length": 58.935482025146484, "blob_id": "2886d23f1206b1949ad364f24345c548fcc24785", "content_id": "5dd4a92afe78926f27a24fb86ddf0b8b42986e34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3716, "license_type": "no_license", "max_line_length": 163, "num_lines": 62, "path": "/coreapp/migrations/0035_oldrequests_requests_shippingaddress_transaction.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-08 15:24\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('coreapp', '0034_auto_20190105_2123'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OldRequests',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('offerrer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='old_from_user', to=settings.AUTH_USER_MODEL)),\n ('requester', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='old_to_user', to=settings.AUTH_USER_MODEL)),\n ('requester_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='old_requester_book_from_user', to='coreapp.Book')),\n ],\n ),\n migrations.CreateModel(\n name='Requests',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('offerrer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user', to=settings.AUTH_USER_MODEL)),\n ('requester', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user', to=settings.AUTH_USER_MODEL)),\n ('requester_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='requester_book_from_user', to='coreapp.Book')),\n ],\n ),\n migrations.CreateModel(\n name='ShippingAddress',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('flatnumber', models.CharField(max_length=100, verbose_name='Flat Number')),\n ('address1', models.CharField(max_length=200, verbose_name='Address line 1')),\n ('address2', models.CharField(max_length=200, verbose_name='Address line 2')),\n ('zip_code', models.CharField(choices=[('421202', '421202'), ('421201', '421201'), ('421203', '421203')], default='421201', max_length=100)),\n ('city', models.CharField(max_length=100, verbose_name='City')),\n ('country', models.CharField(max_length=100, verbose_name='Country')),\n ],\n options={\n 'verbose_name': 'Shipping Address',\n 'verbose_name_plural': 'Shipping Addresses',\n },\n ),\n migrations.CreateModel(\n name='Transaction',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('offerer_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='offerrer_book_from_user', to='coreapp.Book')),\n ('offerrer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='offerrer', to=settings.AUTH_USER_MODEL)),\n ('requester', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='requester', to=settings.AUTH_USER_MODEL)),\n ('requester_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='requested_book_from_user', to='coreapp.Book')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.43844857811927795, "alphanum_fraction": 0.6070826053619385, "avg_line_length": 31.94444465637207, "blob_id": "1664c716782ace6c2a7d26d95b9ad101f93ae74b", "content_id": "cbecbc963a6249bc191a18f368d2311d06800582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 246, "num_lines": 18, "path": "/coreapp/migrations/0063_auto_20190119_1409.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 14:09\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0062_auto_20190119_1352'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='zip_code',\n field=models.CharField(choices=[('421202', '421202'), ('421201', '421201'), ('421204', '421204'), ('421203', '421203'), ('421301', '421301')], default='421202', help_text='we only operate in these locations for now!', max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.748670220375061, "alphanum_fraction": 0.7952127456665039, "avg_line_length": 61.66666793823242, "blob_id": "0ea4c2345ff8df86c337b4b3cd5697917ec0a537", "content_id": "629c89130e924fc79be463e1664d523215fe8950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 754, "license_type": "no_license", "max_line_length": 184, "num_lines": 12, "path": "/README.md", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Cadabra\n\nCadabra (www.cadabra.co.in) is a website exclusively for Book readers where they can exchange, buy or sell their books. \nSo a user would have his collection and another user would have his collection. So a request can me made for a book and the other person would pick a book from requester’s collection. \nOnce the swap is agreed upon we carry out the exchange for them. There is another part where we you just sell the book, for a certain amount.\n\nFull Stack : Developed the entire website using Django Framework and then, deployed the website.\n\nEntrepreneurship : Responsible for management, logistics and delivery of books.\n\n\n![image](https://user-images.githubusercontent.com/25560037/151745640-1a983af2-ab5d-414f-a428-ee81b3f4c24c.png)\n" }, { "alpha_fraction": 0.5558510422706604, "alphanum_fraction": 0.5970744490623474, "avg_line_length": 31.69565200805664, "blob_id": "dfc99ff059223cfa62d2f3c8c4bb5707b95c0712", "content_id": "62341a8e49ce9ccdfda9b71f7197b3bc12eae7d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license_type": "no_license", "max_line_length": 124, "num_lines": 23, "path": "/coreapp/migrations/0026_order.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 05:11\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0025_auto_20190104_0748'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date_ordered', models.DateTimeField(auto_now=True)),\n ('items', models.ManyToManyField(to='coreapp.Book')),\n ('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='coreapp.Profile')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5691964030265808, "alphanum_fraction": 0.6183035969734192, "avg_line_length": 23.88888931274414, "blob_id": "139d65b09e1a5cc7a2518b4e2a0bcef377b513b5", "content_id": "e44cab1017d79a66df1cd7a1444760a35e44c482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 92, "num_lines": 18, "path": "/coreapp/migrations/0047_auto_20190112_0429.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-12 04:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0046_shippingaddress_phone_number'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='country',\n field=models.CharField(default='India', max_length=100, verbose_name='Country'),\n ),\n ]\n" }, { "alpha_fraction": 0.5742331147193909, "alphanum_fraction": 0.6196318864822388, "avg_line_length": 34.434783935546875, "blob_id": "13cc91e4da126cd01fcd8e9ba44f4e70ddadc51a", "content_id": "d34c5b1e953d08915410212030efc48859ffd69c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 217, "num_lines": 23, "path": "/coreapp/migrations/0065_auto_20190119_1415.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 14:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0064_auto_20190119_1412'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='book_name',\n field=models.CharField(help_text='We only deal with original books with ISBN codes, pirated books will not be accepted.', max_length=100),\n ),\n migrations.AlterField(\n model_name='book',\n name='sell_or_exchange',\n field=models.CharField(choices=[('Sell', 'Sell'), ('Exchange', 'Exchange')], default='Exchange', help_text='By adding items to exchange you can make requests to other users for exchange.', max_length=100),\n ),\n ]\n" }, { "alpha_fraction": 0.7648327946662903, "alphanum_fraction": 0.7648327946662903, "avg_line_length": 34.644229888916016, "blob_id": "4cbfad4b2d4322b870413179e2b752c916d0ed70", "content_id": "8e108da5e4ece321ed32b26d9442474ab4e3bff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3708, "license_type": "no_license", "max_line_length": 375, "num_lines": 104, "path": "/coreapp/admin.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.contrib.admin import actions\nfrom django.contrib import admin\nfrom coreapp.models import Book, Profile, UserCollection, Order, Requests, Transaction, ShippingAddress, FinalBuyOrder, OldRequests, CompletedBuyOrder, CompletedTransaction\nfrom import_export.admin import ImportExportModelAdmin\nfrom django.contrib import admin\nfrom coreapp.models import delete_transaction_email, send_buyorder_email, send_completed_buy_order_email, delete_buyorder_email\nfrom django.db.models import signals\n# Register your models here.\n\nadmin.site.register(CompletedBuyOrder)\nadmin.site.register(CompletedTransaction)\n\n# class TransactionAdmin(ImportExportModelAdmin):\n# pass\n\ndef delete_selected_exchange_order(modeladmin, request, queryset):\n\n signals.pre_delete.disconnect(\n delete_transaction_email, sender=Transaction)\n\n for obj in queryset:\n\n CompletedTransaction.objects.create(requester=obj.requester, offerrer=obj.offerrer, requester_book_name=obj.requester_book.book_name, offerrer_book_name=obj.offerrer_book.book_name, requester_author_name=obj.requester_book.author_name, offerrer_author_name=obj.offerrer_book.author_name, requester_address=obj.requester_address, offerrer_address=obj.offerrer_address)\n obj.requester_book.delete()\n obj.offerrer_book.delete()\n\n obj.delete()\n\n signals.pre_delete.connect(\n delete_transaction_email, sender=Transaction)\n\ndelete_selected_exchange_order.short_description = \"Delete Exchange Order on Completion (Select This)\"\n\n\ndef delete_selected_exchange_order_without_notifications(modeladmin, request, queryset):\n\n signals.pre_delete.disconnect(\n delete_transaction_email, sender=Transaction)\n\n for obj in queryset:\n\n obj.delete()\n\n signals.pre_delete.connect(\n delete_transaction_email, sender=Transaction)\n\ndelete_selected_exchange_order_without_notifications.short_description = \"Delete Exchange Order without Notifications\"\n\n\nclass TransactionAdmin(admin.ModelAdmin):\n actions = [delete_selected_exchange_order,\n delete_selected_exchange_order_without_notifications]\n\n\nadmin.site.register(Transaction, TransactionAdmin)\n\n\ndef delete_selected_buy_order(modeladmin, request, queryset):\n\n signals.pre_delete.disconnect(\n delete_buyorder_email, sender=FinalBuyOrder)\n\n for obj in queryset:\n CompletedBuyOrder.objects.create(user=obj.user,book_name=obj.book.book_name, author_name=obj.book.author_name, seller=obj.seller,\n useraddress=obj.useraddress, selleraddress=obj.selleraddress, total_price=obj.total_price)\n obj.book.delete()\n\n obj.delete()\n\n signals.pre_delete.connect(\n delete_buyorder_email, sender=FinalBuyOrder)\n\n\ndelete_selected_buy_order.short_description = \"Delete Selected Buy Order on Completion (Select This)\"\n\n\ndef delete_selected_buy_order_without_notifications(modeladmin, request, queryset):\n\n signals.pre_delete.disconnect(\n delete_buyorder_email, sender=FinalBuyOrder)\n\n for obj in queryset:\n\n obj.delete()\n\n signals.pre_delete.connect(\n delete_buyorder_email, sender=FinalBuyOrder)\n\ndelete_selected_buy_order_without_notifications.short_description = \"Delete Selected without sending notifications\"\n\nclass FinalBuyOrderAdmin(admin.ModelAdmin):\n actions = [delete_selected_buy_order,\n delete_selected_buy_order_without_notifications]\n\n\nadmin.site.register(FinalBuyOrder, FinalBuyOrderAdmin)\n\nadmin.site.register(Book)\nadmin.site.register(Profile)\nadmin.site.register(Order)\nadmin.site.register(OldRequests)\nadmin.site.register(UserCollection)\nadmin.site.register(Requests)\nadmin.site.register(ShippingAddress)\n\n" }, { "alpha_fraction": 0.5834970474243164, "alphanum_fraction": 0.6444007754325867, "avg_line_length": 25.789474487304688, "blob_id": "2bb12a5c06abb315e46c2daf30db6394c98a0e85", "content_id": "009540fc3fe448fa70f4e3b9fee87cac0cb24168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 130, "num_lines": 19, "path": "/coreapp/migrations/0043_auto_20190111_1551.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-11 15:51\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0042_auto_20190111_1406'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shippingaddress',\n name='profile',\n field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='address', to='coreapp.Profile'),\n ),\n ]\n" }, { "alpha_fraction": 0.45739299058914185, "alphanum_fraction": 0.4628404676914215, "avg_line_length": 31.745222091674805, "blob_id": "17b17d831b7db7ae246c8f438ce0300acd03cfe2", "content_id": "dc7cf97e38a8c7413eafa158ba04905ac6adc692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5140, "license_type": "no_license", "max_line_length": 143, "num_lines": 157, "path": "/templates/cart_list_entries.html", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load crispy_forms_tags %}\n{% block content %}\n\n{% if messages %}\n{% for message in messages %}\n<div class=\"alert alert-{{ message.tags }}\">\n {{ message }}\n</div>\n{% endfor %}\n{% endif %}\n\n{% if orders %}\n\n<h2>WISHLIST ITEMS :</h2>\n<br/>\n{% for book in orders %}\n\n<div class=\"card text-left\">\n <div class=\"card-header\">\n <p class=\"card-text\">Seller Name : {{ book.user }}</p>\n </div>\n <div class=\"card-body\">\n\n <div class=\"d-flex justify-content-between\">\n <div>\n <h5 class=\"card-title\">{{ book.book_name }}</h5>\n {% if book.author_name %}\n <p class=\"card-text\">Author name: {{ book.author_name }}</p>\n {% endif %}\n \n <p class=\"card-text\">Condition : {{ book.condition }} </p>\n {% if book.price %}\n <p class=\"card-text\">Price : {{ book.price }} </p>\n {% endif %}\n </div>\n <div class=\"mr-3\">\n {% if book.image_url %}\n <img src=\"{{ book.image_url }}\">\n {% endif %}\n \n </div>\n </div>\n\n </div>\n <div class=\"card-footer text-mutxed\">\n <a href=\"{% url 'cart:delete_item' book.id %}\" class=\"mr-2 btn btn-info float-right\">Delete Item</a>\n\n </div>\n</div>\n</br>\n{% endfor %}\n\n<br />\n<div class=\"row\">\n <div class=\"col-sm-6\">\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Address</h5>\n {% if address.address1 != \"\" %}\n {{ address }}\n <hr />\n <p>Phone number: {{ address.phone_number }}</p>\n\n {% else %}\n <p class=\"card-text\">\n Address and Phone Number, you need to add address in profile settings, it is a one time process</p>\n <a class=\"btn btn-success\" style=\"color: white\" data-toggle=\"modal\" data-target=\"#updateaddress\">Update</a>\n\n <div class=\"modal fade\" id=\"updateaddress\" role=\"dialog\">\n <div class=\"modal-dialog \">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title\">Update Address </h4>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n </div>\n <div class=\"modal-body\">\n <form method=\"post\" novalidate>\n {% csrf_token %}\n {{ address_form | crispy }}\n <button type=\"submit\" class=\"btn btn-primary btn-block\" name=\"updateadd\">Save\n Changes</button>\n\n </form>\n </div>\n </div>\n </div>\n </div>\n\n {% endif %}\n </div>\n </div>\n </div>\n <div class=\"col-sm-6\">\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Payment</h5>\n <p>Price : {{ total_price }}</p>\n <p class=\"card-text\">You need to pay additional 20 rupees at the time of pickup or delivery.</p>\n <p class=\"card-text\"> Total Price : {{ total_price | add:20 }} </p>\n </div>\n </div>\n </div>\n</div>\n<br/>\n\n{% if address.address1 == \"\" %}\n<button class=\"mr-2 mb-2 btn btn-success float-right disabled\" style=\"color: cornsilk\" data-toggle=\"modal\" data-target=\"#confirmselection\">Make\n Transaction!</button>\n{% else %}\n\n<button class=\"mr-2 mb-2 btn btn-success float-right\" style=\"color: cornsilk\" data-toggle=\"modal\" data-target=\"#confirmselection\">Make\n Transaction!</button>\n\n<div class=\"modal fade\" id=\"confirmselection\" role=\"dialog\">\n <div class=\"modal-dialog \">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title\">Confirm Selection</h4>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n </div>\n <div class=\"modal-body\">\n <p>Are you sure you want to make the Purchase?</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n <form method=\"post\">\n {% csrf_token %}\n <input type=\"submit\" class=\"btn btn-info\" name=\"Yes\" />\n </form>\n </div>\n </div>\n </div>\n</div>\n{% endif %}\n\n\n{% else %}\n\n<div class=\"text-center\">\n <h1>Cart Empty ! Add Books to Cart ! </h1>\n\n <hr/>\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col text-center\">\n <a class=\"btn btn-success btn-lg center\" href=\"{% url 'coreapp:list_entries' %}\"> Home </a>\n </div>\n </div>\n </div>\n\n</div>\n\n\n{% endif %}\n\n{% endblock %}" }, { "alpha_fraction": 0.5637727975845337, "alphanum_fraction": 0.6227223873138428, "avg_line_length": 37.875, "blob_id": "00ba08c3ec1511c878b16d5f6fd1717fd9859e99", "content_id": "874deef72119d1184319297b323bca2668e56a44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "no_license", "max_line_length": 271, "num_lines": 24, "path": "/coreapp/migrations/0078_auto_20190129_1355.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-29 13:55\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0077_auto_20190129_0438'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='book',\n name='condition',\n field=models.CharField(choices=[('Almost New', 'Almost New'), ('Acceptable', 'Acceptable'), ('Good', 'Good'), ('Bad', 'Bad')], default='Acceptable', max_length=100),\n ),\n migrations.AlterField(\n model_name='shippingaddress',\n name='phone_number',\n field=models.CharField(help_text='Enter your 10 digit phone number', max_length=17, validators=[django.core.validators.RegexValidator(message=\"Phone number must be entered in the format: '+9999999999'. Up to 15 digits allowed.\", regex='^\\\\+?1?\\\\d{10,15}$')]),\n ),\n ]\n" }, { "alpha_fraction": 0.46247464418411255, "alphanum_fraction": 0.5253549814224243, "avg_line_length": 19.54166603088379, "blob_id": "546268c37f78ab8092ab29e76c7351be3e01192a", "content_id": "32c3210657de57b90f6b137ac9a04947f06129b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 493, "license_type": "no_license", "max_line_length": 47, "num_lines": 24, "path": "/cart/migrations/0003_auto_20190105_0511.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-05 05:11\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cart', '0002_auto_20190105_0448'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='order',\n name='items',\n ),\n migrations.RemoveField(\n model_name='order',\n name='owner',\n ),\n migrations.DeleteModel(\n name='Order',\n ),\n ]\n" }, { "alpha_fraction": 0.6883116960525513, "alphanum_fraction": 0.6935064792633057, "avg_line_length": 34, "blob_id": "5cc5ae1775db7d5c2eb49aa22e8f6c3fc162373c", "content_id": "6dec8fc37fd393c78dbeb9d19ed2381e971c4d50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 99, "num_lines": 11, "path": "/search/urls.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom search import views\n\napp_name = 'searchapp'\n\nurlpatterns = [\n path('', views.SearchListView.as_view(), name='search'),\n # path('', views.search_form , name='search'),\n path('content-autocomplete/', views.ContentAutoComplete.as_view(),name='content-autocomplete'),\n # path('search1/', views.SearchAutoComplete.as_view(), name='search1'),\n]\n" }, { "alpha_fraction": 0.6407322883605957, "alphanum_fraction": 0.6643783450126648, "avg_line_length": 47.55555725097656, "blob_id": "a40e8248e628cffe6dafe6f2acb3dddd0c0817af", "content_id": "4d96bea2783d369d1eea734c5327770607b44eb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 160, "num_lines": 27, "path": "/coreapp/migrations/0054_finalbuyorder.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-17 03:32\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('coreapp', '0053_auto_20190116_1608'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FinalBuyOrder',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Book', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='coreapp.Book')),\n ('seller', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='seller', to=settings.AUTH_USER_MODEL)),\n ('selleraddres', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='selleraddress', to='coreapp.ShippingAddress')),\n ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)),\n ('useraddress', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='address', to='coreapp.ShippingAddress')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5859201550483704, "alphanum_fraction": 0.588691771030426, "avg_line_length": 28.09677505493164, "blob_id": "6bd3398dc29caf331159823306f4a02b217d9254", "content_id": "40a70c5d1df4ed4fa21dd04460985a0cf82bb8fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 76, "num_lines": 62, "path": "/coreapp/forms.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom coreapp.models import Book, Profile, ShippingAddress\nfrom dal import autocomplete\n\n\nclass UserCreationForm(UserCreationForm):\n email = forms.EmailField(required=True, label='Email')\n\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n\n def save(self, commit=True):\n user = super(UserCreationForm, self).save(commit=False)\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n\n\nclass NewEntryForm(forms.ModelForm):\n class Meta:\n model = Book\n fields = ['book_name','author_name', 'description',\n 'sell_or_exchange', 'price', 'condition','image_url']\n widgets = {\n 'description': forms.Textarea(attrs={'rows': 4, 'cols': 15}),\n }\n\n def __init__(self, *args, **kwargs):\n super(NewEntryForm, self).__init__(*args, **kwargs)\n # self.fields['sell_or_exchange'].widget = forms.ChoiceField(attrs={\n # 'id': 'sellorexchangeid',\n # })\n\n self.fields['price'].widget = forms.TextInput(attrs={\n 'type': 'number',\n 'id': 'priceid',\n })\n\nclass ShippingAddressForm(forms.ModelForm):\n class Meta:\n model = ShippingAddress\n fields = '__all__'\n exclude = ('profile',)\n\n field_order = ['flatnumber', 'address1',\n 'address2', 'zip_code','city', 'phone_number']\n\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ['username', 'email']\n\n\nclass ProfileForm(forms.ModelForm):\n class Meta:\n model = Profile\n fields = ['profile_pic', ]\n" }, { "alpha_fraction": 0.5110294222831726, "alphanum_fraction": 0.5680146813392639, "avg_line_length": 22.65217399597168, "blob_id": "d411d8554db10f1b783fb77a06df2a6a4d3d4fee", "content_id": "60f56204a6aa767aad81801d9a87f876e453cf7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 47, "num_lines": 23, "path": "/coreapp/migrations/0062_auto_20190119_1352.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-19 13:52\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0061_auto_20190119_1345'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='transaction',\n old_name='selleraddress',\n new_name='offerrer_address',\n ),\n migrations.RenameField(\n model_name='transaction',\n old_name='useraddress',\n new_name='requester_address',\n ),\n ]\n" }, { "alpha_fraction": 0.5177111625671387, "alphanum_fraction": 0.6021798253059387, "avg_line_length": 20.58823585510254, "blob_id": "3288d7e6e8c07ba0112cc74f6a37826925833686", "content_id": "852267176481df190ea0efde6792652174b02c44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/coreapp/migrations/0077_auto_20190129_0438.py", "repo_name": "pratikaher88/BookStoreProject", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.4 on 2019-01-29 04:38\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('coreapp', '0076_auto_20190129_0437'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='oldrequests',\n options={'verbose_name_plural': 'Old Requests'},\n ),\n ]\n" } ]
61
imen-yaich/django
https://github.com/imen-yaich/django
adc957a8c298c3a777a28faff8622ffffdeb149f
240fc48f0ce19374c09a0f6c71e5922e45a8251e
e34b7cc5e2ecd3c8da26a2b9518df0f5e0adceb2
refs/heads/master
2022-12-02T11:34:01.983162
2020-08-21T07:56:45
2020-08-21T07:56:45
289,212,663
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.380952388048172, "alphanum_fraction": 0.3857142925262451, "avg_line_length": 14, "blob_id": "9826d88b13a0a34303b58eedcfb6b9681ce72f4d", "content_id": "fe16187ccce4647315ad16da853bbd4a34da3565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 420, "license_type": "no_license", "max_line_length": 33, "num_lines": 28, "path": "/imenapp/templates/index.html", "repo_name": "imen-yaich/django", "src_encoding": "UTF-8", "text": "{% block content %}\n{{ t.imen }} imen\n<table class=\"table table-hover\">\n <thead>\n <tr>\n <th scope=\"col\">.</th>\n <th scope=\"col\">22</th>\n <th scope=\"col\">karazt</th>\n </tr>\n </thead>\n\n <tbody>\n {% for t in row %}\n <tr>\n \n <td>{{ t }}</td>\n <td>{{ t}}</td>\n <td>{{ t}}</td>\n {{ i }}\n \n \n </tr>\n\n {% endfor %}\n\n </tbody>\n</table>\n{% endblock %}\n" }, { "alpha_fraction": 0.7115384340286255, "alphanum_fraction": 0.754807710647583, "avg_line_length": 22.11111068725586, "blob_id": "fa2ee5ce4fcf91a028313b6b03f1f9070976d24e", "content_id": "39129f2157caf0472a6bb3865677200ac5179f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/imenapp/models.py", "repo_name": "imen-yaich/django", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass row(models.Model):\n\timen = models.CharField(max_length=200)\n\tyaich = models.CharField(max_length=200)\n\tsexy = models.CharField(max_length=200)\n\n# Create your models here.\n" }, { "alpha_fraction": 0.581589937210083, "alphanum_fraction": 0.5941422581672668, "avg_line_length": 26.576923370361328, "blob_id": "7157bca9aa290fd0cef8af692c659aa51351216a", "content_id": "393fa5e2ee221a496aa8856161ab8e610effbf13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 717, "license_type": "no_license", "max_line_length": 55, "num_lines": 26, "path": "/imenapp/views.py", "repo_name": "imen-yaich/django", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport pandas as pd \nfrom pandas import DataFrame\nimport sqlite3\nimport sys\nimport MySQLdb\ndef index(request):\n\tconnection = MySQLdb.connect(host = \"172.17.0.2\",\n user = \"imen\",\n passwd = \"imen\",\n db = \"test\")\n\n\tcrsr = connection.cursor()\n\tcrsr.execute(\"SELECT * FROM table_name ;\")\n\trowss = crsr.fetchall()\n\tcrsr.execute(\"SELECT COUNT(*) FROM table_name ;\")\n\t#row = pd.DataFrame(crsr.fetchall())\n\t#row.columns = resoverall.keys()\n\tt = crsr.fetchall()\n\tprint (t)\n\trow = list( rowss )\n\tfor r in row:\n\t\tprint(r[0])\n\ti = \"ahmed\"\n \n\treturn render(request,'index.html',{'row':row,'i':i} )\n" }, { "alpha_fraction": 0.7444444298744202, "alphanum_fraction": 0.7444444298744202, "avg_line_length": 16.799999237060547, "blob_id": "0f43228909b7065210004875f0c05644dd4cd58e", "content_id": "bea674866b80720a64a69c8e75ca99ef0942d618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/imenapp/apps.py", "repo_name": "imen-yaich/django", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass imenappConfig(AppConfig):\n name = 'imenapp'\n\n" } ]
4
ArantzazuSt/test-repositorio
https://github.com/ArantzazuSt/test-repositorio
cce1ce1e58260e721c6911ef498a70b737914ad4
884e3c4a3768fa24419b5de19874e75450bfbac8
ad9c86e3d94c5fb58670e63dac07d2e8c8c03728
refs/heads/master
2023-01-20T09:50:13.110539
2020-11-30T17:21:15
2020-11-30T17:21:15
309,689,618
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.577674388885498, "alphanum_fraction": 0.5786046385765076, "avg_line_length": 25.875, "blob_id": "e00f683a5d9718e77850fd566f90adeee291836c", "content_id": "625ce71e705186ad6d60183f7d9c42d684adbf9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 82, "num_lines": 40, "path": "/opendaqjson.py", "repo_name": "ArantzazuSt/test-repositorio", "src_encoding": "UTF-8", "text": "'''Programa que imprime el valor de las entrads al fijar un valor en la salida '''\n\nimport json\nimport argparse\nimport time\n\nfrom opendaq import *\n\n\nif __name__ == 'main':\n\n parser = argparse.ArgumentParser(description='Valor de las salidas Opendaq')\n\n parser.add_argument('-p', '--puerto', metavar='', help='Puerto seleccionado')\n parser.add_argument('-l', '--listInput', nargs='+', metavar='',\n type=int, help='Entradas seleccionadas')\n parser.add_argument('-r', '--rep', metavar='', type=int,\n help='Numero de repeticiones')\n\n args = parser.parse_args()\n daq = DAQ(args.puerto)\n\n mylist = args.listInput # Array de entradas a leer\n\n f = open(\"prueba.json\", 'w')\n data = {\n \"model\": daq.hw_ver,\n \"serial\": daq.serial_str,\n \"port\": args.puerto,\n # \"time\": int(time.time()),\n \"items\": []\n\n }\n\n for i in mylist:\n data[\"items\"].append({\"Input number\": i, \"readings\": daq.read_analog()})\n print(data)\n\n json.dump(data, f, indent=2)\n f.close()\n" } ]
1
Gamillkar/Regexp
https://github.com/Gamillkar/Regexp
fc19221aed8b49c1e180188bcb82c78600bd295c
a6a6b8faa241fb38dfbb50509db26aa8673c3b28
d297b6041fb5bf1490b8307a36c3a396ce89dfe6
refs/heads/master
2022-11-19T20:11:55.334536
2020-07-21T14:42:02
2020-07-21T14:42:02
281,423,279
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.585919976234436, "alphanum_fraction": 0.5958399772644043, "avg_line_length": 40.05263137817383, "blob_id": "3d0852c6944dd4ebb481da9d4c77261dc5028250", "content_id": "3d796dac3040db4aec094d4d0f43c6d616bbf5eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3302, "license_type": "no_license", "max_line_length": 124, "num_lines": 76, "path": "/phonebook_regexp.py", "repo_name": "Gamillkar/Regexp", "src_encoding": "UTF-8", "text": "from pprint import pprint\nimport csv\nimport re\n\nwith open(\"phonebook_raw.csv\", encoding='utf-8') as f:\n rows = csv.reader(f, delimiter=\",\")\n contacts_list = list(rows)\n\ndef conversion_name():\n fix_full_name = []\n pattern = re.compile(r\"^([А-ЯЁ][\\w]*)(\\,|\\s)([А-ЯЁ][\\w]*)(\\,|\\s)([А-ЯЁ][\\w]+)?(\\,)\")\n for contact in contacts_list[1:]:\n str_contact = ','.join(contact)\n full_name = pattern.sub(r\"\\1,\\3,\\5,\", str_contact)\n fix_full_name.append(full_name)\n return fix_full_name\n\ndef fix_number():\n fix_number_name = []\n number_main = re.compile(r'\\,(\\+7|8)\\s*\\(*(\\d{3})\\)*\\s*\\-*(\\d{3})\\s*\\-*(\\d{2})\\s*\\-*(\\d{2})(\\,*)')\n number_additional = re.compile(r'\\,\\s\\(*\\доб. (\\d*)\\)*')\n for basic_number in conversion_name():\n fix_number = number_main.sub(r',+7(\\2)\\3-\\4-\\5,', basic_number)\n if 'доб' in fix_number:\n fix_number = number_additional.sub(r' доб.\\1', fix_number)\n fix_number_name.append(fix_number)\n return fix_number_name\n\ndef clear_data():\n clear_comma_list = []\n del_more_comma = re.compile(r'\\,+')\n for item in fix_number():\n fix_comma = del_more_comma.sub(r',', item)\n clear_comma_list.append(fix_comma)\n return clear_comma_list\n\ndef transfer_data():\n name_surname_list = []\n transfer_data = []\n repeat_data = []\n for contact in clear_data():\n contact_name = contact.split(',')\n name_surname = f'{contact_name}'\n name_surname_control = (f'{contact_name[0]},{contact_name[1]}')\n # print(name_surname, name_surname_1)\n if name_surname_control not in name_surname_list:\n name_surname_list.append(name_surname_control) #добавление name и surname в отд. лист\n transfer_data.append(contact_name) #добавление недублируемых данных в отд. лист\n else:\n repeat_data.append(contact.split(','))\n return transfer_data, repeat_data\n\ndef union_contact():\n list_contact, repeat_data = transfer_data()\n # перемещение пункта position и email\n for repeat_contact in repeat_data:\n rep_contact = (repeat_contact[0], repeat_contact[1])\n\n for contact in list_contact:\n contact_name = (contact[0], contact[1])\n # если из повторяющ. list name и sername совпадает с общим list,то извлекаеться инф. и вставляеться в общий лист\n if contact_name == rep_contact and len(repeat_contact)>=4:\n move_data = repeat_contact[4]\n contact.insert(4, move_data) #вставка position\n elif contact_name == rep_contact:\n if '@' in ','.join(repeat_contact):\n email = [data_contact for data_contact in repeat_contact if '@' in data_contact]\n email = email[0]\n contact.insert(-1, email) #вставка email\n header = ['lastname', 'firstname', 'surname', 'organization', 'position', 'phone', 'email']\n list_contact.insert(0, header)\n return list_contact\n\nwith open(\"phonebook.csv\", \"w\", encoding='utf-8') as f:\n datawriter = csv.writer(f, delimiter=',')\n datawriter.writerows(union_contact())\n\n\n\n\n\n" } ]
1
josealfredojimenezgarcia/Primer-c-digo
https://github.com/josealfredojimenezgarcia/Primer-c-digo
ade78c1982ca444f8bf2124cfa87ea94f1fc6375
0e65f34969bd45a2f88b3ca614084541faa4dce6
dae1a4a9ca158cbb0c4f7a86c32946b6c5dd051c
refs/heads/master
2023-07-09T14:31:11.973125
2021-08-07T11:41:31
2021-08-07T11:41:31
381,564,499
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5418719053268433, "alphanum_fraction": 0.6133005023002625, "avg_line_length": 15.916666984558105, "blob_id": "2c453fe85244339141a4af4f529aebc3ef85b7dc", "content_id": "b7c1c59a82c6daed62d7fb37e0e6245b9919da32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 48, "num_lines": 24, "path": "/index.py", "repo_name": "josealfredojimenezgarcia/Primer-c-digo", "src_encoding": "UTF-8", "text": "print(\"Dios es Amor\");\n\na=20;\nb=3;\nc=0;\n\nConjunto={1,2,3,4,5,6,7,8,9};\n\nLista=['valerie', 'Josesito', 'Stiven'];\n\nTupla=((((((1,2,3,5,4,6,69,98,852,124))))));\n\ndiccionario={a:'jose', b:'Stiven', c:'Valerie'};\n\nc=a**b;\nprint(c)\nprint(\"Valerie es Hermosa\");\nprint(\"Dios es bueno todo el tiempo\");\n\nh=str(input('Digite su nombre '))\n\nprint('Usted se registró como: ', h)\n\nprint('Gracias, Fin del Programa')\n" } ]
1
rkouere/PAC_TP2
https://github.com/rkouere/PAC_TP2
118969905c055275019176662b581e9d21ebe5b1
ead3f73e759d3db58f489ca9e704e3c5368ca59d
a8c690ec6795f0121225f2ec5faae77d870ed25e
refs/heads/master
2020-04-11T14:08:30.419651
2015-03-22T19:31:12
2015-03-22T19:31:12
30,710,849
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4948316216468811, "alphanum_fraction": 0.654884934425354, "avg_line_length": 42.463768005371094, "blob_id": "e44c4bec6d8224e13ee0d2db5dab9f27d606ae31", "content_id": "2651d60cc58c7f06186629e4116f508a5b54903a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3021, "license_type": "no_license", "max_line_length": 726, "num_lines": 69, "path": "/md5-collisions/coll_finder/client.py", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": "import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport base64\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n <BLANKLINE>\n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\ndef xor(a, b):\n c = bytearray()\n for x,y in zip(a,b):\n c.append(x ^ y)\n return c\n\nURL=\"http://pac.bouillaguet.info/TP2\"\nserver = Server(URL)\n\nf = open(\"ex1_1.txt\", \"rb\")\nm0 = base64.b16encode(f.read())\n\nf = open(\"ex1_2.txt\", \"rb\")\nm1 = base64.b16encode(f.read())\n\n\nprint(server.query(\"/md5-collisions/checker/echallier\", {0: \"656368616c6c696572206c6c6c6d6e617a6a68666c64666c7164736a6673716a666b6a646b7366686e6b736a68666473716a666a666471736b666a6b736f640aa5aa8e2a93cbb3fe7dff33f72885884cbc6459c5a22819081a723f2eb5b594869eacf7e5d86ded7c6b0e5e02aed36c21f6cbeac94a78750f852ddd5a4cef82bbb6dd226565a0eab09d7ed08ba656ed97d797467b7c1d92e82db320583b6068a7cf932018a745be557703485b53202097255ba588e0764e29dac32f947d6f386c2050414320504f574141414141414141414141\", 1: \"656368616c6c696572206c6c6c6d6e617a6a68666c64666c7164736a6673716a666b6a646b7366686e6b736a68666473716a666a666471736b666a6b736f640aa5aa8e2a93cbb3fe7dff33f72885884cbc645945a22819081a723f2eb5b594869eacf7e5d86ded7c6b0e5e02ae536d21f6cbeac94a78750f852dddda4cef82bbb6dd226565a0eab09d7ed08ba656ed97d79746fb7c1d92e82db320583b6068a7cf932018a745be557703485b53a01f97255ba588e0764e29dac32f147d6f386c2050414320504f574141414141414141414141\"}))\n" }, { "alpha_fraction": 0.6054053902626038, "alphanum_fraction": 0.6108108162879944, "avg_line_length": 14.416666984558105, "blob_id": "cdd4f8cf33eb4b229b3f13e36dbceac9409f10ec", "content_id": "992c73eec0a77f9e3439d5bdea4a923e4563b97a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 185, "license_type": "no_license", "max_line_length": 39, "num_lines": 12, "path": "/md5-collisions/coll_finder/Makefile", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": ".PHONY: clean\n\ncoll_finder: lib/libcoll.a md5.o main.o\n\tg++ lib/*.o *.o -o coll_finder\n\nlib/libcoll.a:\n\tcd lib && $(MAKE)\n\nclean:\n\trm -f coll_finder\n\trm -f *.o\n\tcd lib && $(MAKE) clean\n" }, { "alpha_fraction": 0.5123456716537476, "alphanum_fraction": 0.6319109201431274, "avg_line_length": 37.41237258911133, "blob_id": "116aae81cd0de83b860eeeb5192654b158d5f647", "content_id": "433070db7b3fc33d5de9631078de4b086cbd0420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7479, "license_type": "no_license", "max_line_length": 397, "num_lines": 194, "path": "/padding-attack/client_q3_lastIV.py", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": "import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport base64\nimport helpers\n\n\n# excelente explication\n#http://blog.gdssecurity.com/labs/2010/9/14/automated-padding-oracle-attacks-with-padbuster.html\n# text fin\n# ['36', '63', '63', '66', '31', '64', '61', '65', '36', '35', '32', '38', '31', '32', '34', '01']\n\n\nDEBUG = 1\nindex_du_cypher = 0x01\nformat_index = 1\nIntValue = []\n#le valeur intermediaire que l'on cherche a trouver\nCLimiterOriginal = 32\nCLimiter = CLimiterOriginal\n\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n <BLANKLINE>\n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\ndef xor(a, b):\n c = bytearray()\n for x,y in zip(a,b):\n c.append(x ^ y)\n return c\n\ndef getBloc(cypher, nbrBlock):\n if nbrBlock*32 >= len(cypher):\n return -1\n else:\n return cypher[nbrBlock * 32:(nbrBlock + 1) * 32]\n\n\n# get a seed with 01 as the last byte\ndef getSeed(i):\n while 1:\n try:\n seed = server.query(\"/padding-attack/last-byte/echallier/\"+str(i), {\"value\": \"01\"})\n if seed['status'] == 'OK':\n print(\"seed working = \" + str(i))\n return i\n break\n except:\n print(\"seed dead\")\n i = i + 1\n\ndef nbr_to_hexa(nbr):\n return \"{0:002x}\".format(nbr)\n\ndef bytes_to_hex(bytes_to_encode):\n return base64.b16encode(bytes_to_encode).decode()\n\ndef string_hex_to_bytes(string_to_encode):\n return base64.b16decode(string_to_encode.encode(), casefold=True)\n\n# permet de connaitre la valeur originel du block C à l'index \"index/256\"\ndef find_value_plaintext(index):\n global IntValue\n format = index * 0x00\n for i in range(0x00, 257):\n # on va incrementer de 1 le masque à chaque itérations\n plaintext = \"{0:032x}\".format(format)\n IV_tmp=base64.b16encode(xor(base64.b16decode(C, casefold=True), base64.b16decode(plaintext, casefold=True)))\n format = index * (i + 1)\n result = server.query(oracle, {\"IV\": IV_tmp.decode(), \"ciphertext\": cipherTextHack})\n if(DEBUG):\n print(IV_tmp)\n print(plaintext)\n if(result['status'] == 'OK'):\n # on a besoin de tout transofmer en bytes pour pouvoir utiliser la fonction xor\n # on a besoin du C\n tmp1 = base64.b16decode(IV_tmp[CLimiter-2:CLimiter], casefold=True)\n # on a besoin de l'index pour connaitre la valeur que l'on \"hackait\"\n tmp2 = base64.b16decode(nbr_to_hexa(index_du_cypher), casefold=True)\n # la valeur intermediaire\n tmp3 = base64.b16encode(xor(tmp1, tmp2)).decode()\n if(DEBUG):\n print(\"tmp3\")\n print(tmp3)\n print(IV_tmp[CLimiter-2:CLimiter])\n print(\"index_dy_cypher\")\n print(index_du_cypher)\n \n IntValue.insert(-int(index_du_cypher), base64.b16encode(xor(base64.b16decode(C_original[CLimiter-2:CLimiter], casefold=True), base64.b16decode(tmp3, casefold=True))).decode())\n if(DEBUG):\n print(\"IntValue\")\n print(IntValue[-int(index_du_cypher)])\n return index * 256\n break\n\n\n\ndef init_block_cracked_oracle():\n global index_du_cypher\n global format_index\n global CLimiter\n C = C_original\n CLimiter = CLimiterOriginal\n for i in range(index_du_cypher):\n tmp1 = string_hex_to_bytes(C[CLimiter-2:CLimiter])\n tmp2 = string_hex_to_bytes(IntValue[-int(i+1)])\n tmp3 = bytes_to_hex(xor(tmp1, tmp2))\n val_C_to_replace = bytes_to_hex(xor(string_hex_to_bytes(nbr_to_hexa(index_du_cypher + 1)), string_hex_to_bytes(tmp3)))\n C = C[0:CLimiter-2] + val_C_to_replace + C[CLimiter:]\n CLimiter = CLimiter - 2\n index_du_cypher = index_du_cypher + 1\n return C[0:CLimiter-2] + \"00\" + C[CLimiter:]\n\n\n\n\n# DEFINITION DES VARIABLES\nURL=\"http://pac.bouillaguet.info/TP2\"\nserver = Server(URL)\noracle=\"/padding-attack/oracle/echallier\"\nseedNum = 135\n\n#53616C757420656368616C6C69657227\n#C3\n#A9757373692021204E276F75626C696520706173206465202264C3A9636F64657222206365636920656E20756E69636F64652065740A6427656E6C65766572206C652070616464696E672E0A2D2D2D2D2D2D2D2D2D2D0A54686520503443207333727633720A0A736565643A203133350A70736575646F2D72616E646F6D206A756E6B3A20666F6F0A6D61633A203230643266653664393866343466613163366366653338616439323530343332\n\nplain_final =\"53616C757420656368616C6C69657227C3A9757373692021204E276F75626C696520706173206465202264C3A9636F64657222206365636920656E20756E69636F64652065740A6427656E6C65766572206C652070616464696E672E0A2D2D2D2D2D2D2D2D2D2D0A54686520503443207333727633720A0A736565643A203133350A70736575646F2D72616E646F6D206A756E6B3A20666F6F0A6D61633A203230643266653664393866343466613163366366653338616439323530343332\"\n\n\nC = plain_final[0:32] + \"00\" + plain_final[34:]\nformat = 0\n\n# for i in range(256):\n# val_tmp = \"{0:02x}\".format(format)\n# format = (i + 1)\n# C = plain_final[0:32] + str(val_tmp) + plain_final[34:38]\n# print(C)\n# try:\n# plaintext = base64.b16decode(C).decode()\n \n# print(server.query(\"/padding-attack/validation/echallier/\"+str(seedNum), {'plaintext': plaintext}))\n# print(C)\n# except:\n# print(\"bad char\")\n\n\n#plaintext = base64.b16decode(IV_tmp).decode()\nplaintext = 'Salut echallier,\\n\\nBravo, tu as réussi ! N\\'oublie pas de \"décoder\" ceci en unicode et\\nd\\'enlever le padding.\\n----------\\nThe P4C s3rv3r\\n\\nseed: 135\\npseudo-random junk: foo\\nmac: 20d2fe6d98f44fa1c6cfe38ad9250432'\nprint(plaintext)\nprint(server.query(\"/padding-attack/validation/echallier/\"+str(seedNum), {'plaintext': plaintext}))\n" }, { "alpha_fraction": 0.6406926512718201, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 16.769229888916016, "blob_id": "18e4a050273646a0b408186a947fffac05a188ce", "content_id": "8751a9b6266b30e41015a307d65eb4d8a8b07260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 231, "license_type": "no_license", "max_line_length": 119, "num_lines": 13, "path": "/md5-collisions/coll_finder/lib/Makefile", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": "OBJ=block0.o block1stevens00.o block1stevens10.o block1wang.o md5.o block1.o block1stevens01.o block1stevens11.o main.o\n\n.PHONY: clean\n\nCXX=g++\nCPPFLAGS=-O3\n\nlibcoll.a: $(OBJ)\n\tar rcs libcoll.a $(OBJ)\n\nclean:\n\trm -f *.a\n\trm -f *.o\n" }, { "alpha_fraction": 0.5592105388641357, "alphanum_fraction": 0.586403489112854, "avg_line_length": 31.571428298950195, "blob_id": "ed95cc1a9f4a566bc5b6ef8824c0f5ed057c2553", "content_id": "9f66556af6674d683ff4745f8c7a37d9110d2ec4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9145, "license_type": "no_license", "max_line_length": 187, "num_lines": 280, "path": "/padding-attack/seed153/client_q3.py", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": "import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport base64\nimport helpers\nimport sys\n\n# excelente explication\n#http://blog.gdssecurity.com/labs/2010/9/14/automated-padding-oracle-attacks-with-padbuster.html\n# text fin\n# ['36', '63', '63', '66', '31', '64', '61', '65', '36', '35', '32', '38', '31', '32', '34', '01']\n\n\nDEBUG = 0\nindex_du_cypher = 0x01\nformat_index = 1\nIntValue = []\n#le valeur intermediaire que l'on cherche a trouver\nCLimiterOriginal = 32\nCLimiter = CLimiterOriginal\n\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n <BLANKLINE>\n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\ndef xor(a, b):\n c = bytearray()\n for x,y in zip(a,b):\n c.append(x ^ y)\n return c\n\ndef getBloc(cypher, nbrBlock):\n if nbrBlock*32 >= len(cypher):\n return -1\n else:\n return cypher[nbrBlock * 32:(nbrBlock + 1) * 32]\n\n\n# get a seed with 01 as the last byte\ndef getSeed(i):\n while 1:\n try:\n seed = server.query(\"/padding-attack/last-byte/echallier/\"+str(i), {\"value\": \"01\"})\n if seed['status'] == 'OK':\n print(\"seed working = \" + str(i))\n return i\n break\n except:\n print(\"seed dead\")\n i = i + 1\n\ndef nbr_to_hexa(nbr):\n return \"{0:002x}\".format(nbr)\n\ndef bytes_to_hex(bytes_to_encode):\n return base64.b16encode(bytes_to_encode).decode()\n\ndef string_hex_to_bytes(string_to_encode):\n return base64.b16decode(string_to_encode.encode(), casefold=True)\n\n# permet de connaitre la valeur originel du block C à l'index \"index/256\"\ndef find_value_plaintext(index):\n global IntValue\n format = index * 0x00\n for i in range(0x00, 257):\n # on va incrementer de 1 le masque à chaque itérations\n plaintext = \"{0:032x}\".format(format)\n IV_tmp=base64.b16encode(xor(base64.b16decode(C, casefold=True), base64.b16decode(plaintext, casefold=True)))\n format = index * (i + 1)\n result = server.query(oracle, {\"IV\": IV_tmp.decode(), \"ciphertext\": cipherTextHack})\n if(DEBUG):\n print(IV_tmp)\n print(plaintext)\n if(result['status'] == 'OK'):\n # on a besoin de tout transofmer en bytes pour pouvoir utiliser la fonction xor\n # on a besoin du C\n tmp1 = base64.b16decode(IV_tmp[CLimiter-2:CLimiter], casefold=True)\n # on a besoin de l'index pour connaitre la valeur que l'on \"hackait\"\n tmp2 = base64.b16decode(nbr_to_hexa(index_du_cypher), casefold=True)\n # la valeur intermediaire\n tmp3 = base64.b16encode(xor(tmp1, tmp2)).decode()\n if(DEBUG):\n print(\"tmp3\")\n print(tmp3)\n print(IV_tmp[CLimiter-2:CLimiter])\n print(\"index_dy_cypher\")\n print(index_du_cypher)\n \n IntValue.insert(-int(index_du_cypher), base64.b16encode(xor(base64.b16decode(C_original[CLimiter-2:CLimiter], casefold=True), base64.b16decode(tmp3, casefold=True))).decode())\n if(DEBUG):\n print(\"IntValue\")\n print(IntValue[-int(index_du_cypher)])\n # print(IntValue)\n return index * 256\n break\n\n\n\ndef init_block_cracked_oracle():\n global index_du_cypher\n global format_index\n global CLimiter\n C = C_original\n CLimiter = CLimiterOriginal\n for i in range(index_du_cypher):\n tmp1 = string_hex_to_bytes(C[CLimiter-2:CLimiter])\n tmp2 = string_hex_to_bytes(IntValue[-int(i+1)])\n tmp3 = bytes_to_hex(xor(tmp1, tmp2))\n val_C_to_replace = bytes_to_hex(xor(string_hex_to_bytes(nbr_to_hexa(index_du_cypher + 1)), string_hex_to_bytes(tmp3)))\n C = C[0:CLimiter-2] + val_C_to_replace + C[CLimiter:]\n CLimiter = CLimiter - 2\n index_du_cypher = index_du_cypher + 1\n return C[0:CLimiter-2] + \"00\" + C[CLimiter:]\n\n\n\n\n# DEFINITION DES VARIABLES\nURL=\"http://pac.bouillaguet.info/TP2\"\nserver = Server(URL)\noracle=\"/padding-attack/oracle/echallier\"\n# seedNum = 135\nseedNum = 136\n\n#print(getSeed(51))\n\nseed=server.query(\"/padding-attack/challenge/echallier/\" + str(seedNum))\n\n\ncypher=seed['ciphertext']\nIV=seed['IV']\nprint(\"!!!!!!!!!!!!\")\nprint(int(sys.argv[1]))\nbegining_index_block = int(sys.argv[1])\nindex_block = int(sys.argv[2])\nprint(\"message crypte\")\nprint(cypher)\nprint(\"------------------------\")\nprint(\"INDEXES\")\nprint(\"from\")\nprint(begining_index_block)\nprint(\"to\")\nprint(index_block)\n\n\n#le IV que l'on va manipuler\n\n# debut boucle\nif(index_block != 0):\n for i in range(begining_index_block, index_block + 1):\n C = getBloc(cypher, index_block)\n C_original = getBloc(cypher, index_block)\n index_du_cypher = 0x01\n format_index = 1\n IntValue = []\n #le valeur intermediaire que l'on cherche a trouver\n CLimiterOriginal = 32\n CLimiter = CLimiterOriginal\n \n print(\"---------\")\n print(\"index du block (depuis la fin) = \" + str(index_block))\n print(\"Block traite = \" + C_original)\n #le ciphertext que l'on va envoyer\n cipherTextHack = getBloc(cypher, index_block + 1)\n #utilise pour gerer la place du mask\n #index qui permet de parcourir le bloc et ded changer les valeures lorsque l'on veut avoir un xor avec 1, 2, 3 etc...\n \n # FIN DEFINITION DES VARIABLES\n \n \n # on calcul le premier chara\n \n C = C[0:CLimiter-2] + \"00\" + C[CLimiter:]\n print(C)\n format_index = find_value_plaintext(format_index)\n \n # on calcul le reste\n for i in range(15):\n C=init_block_cracked_oracle()\n format_index = find_value_plaintext(format_index)\n print(\"valeur reel du bloque\")\n print(IntValue)\n index_block = index_block - 1\n print(\"---------\")\n\n\n#dernier avec IV\nelse:\n C = IV\n C_original = IV\n index_du_cypher = 0x01\n format_index = 1\n IntValue = []\n #le valeur intermediaire que l'on cherche a trouver\n CLimiterOriginal = 32\n CLimiter = CLimiterOriginal\n \n print(\"--------- IV -----------\")\n print(\"index du block (depuis la fin) = \" + str(index_block))\n print(\"Block traite = \" + C_original)\n #le ciphertext que l'on va envoyer\n cipherTextHack = getBloc(cypher, index_block)\n #utilise pour gerer la place du mask\n #index qui permet de parcourir le bloc et ded changer les valeures lorsque l'on veut avoir un xor avec 1, 2, 3 etc...\n \n # FIN DEFINITION DES VARIABLES\n \n \n # on calcul le premier chara\n \n C = C[0:CLimiter-2] + \"00\" + C[CLimiter:]\n print(C)\n format_index = find_value_plaintext(format_index)\n \n # on calcul le reste\n for i in range(15):\n C=init_block_cracked_oracle()\n format_index = find_value_plaintext(format_index)\n\n print(\"valeur reel du bloque\")\n print(IntValue)\n index_block = index_block - 1\n print(\"---------\")\n\n\n\n# fin boucle\n# 2 recuperer l'array et la copier dans resArr\n\n# resArr = ['36', '63', '66', '65', '33', '38', '61', '64', '39', '32', '35', '30', '34', '33', '32', '01']\n# resStr = \"\"\n# for i in range(len(resArr)):\n# resStr += resArr[i]\n\n# # enjoy !\n# print(server.query(\"/padding-attack/last-block/echallier/\"+str(seedNum), {'value': resStr}))\n" }, { "alpha_fraction": 0.54256671667099, "alphanum_fraction": 0.5606734156608582, "avg_line_length": 30.469999313354492, "blob_id": "0f7974360b465fb21e312a3c53558c5327ce26a9", "content_id": "2761d527a2da21d81614e27bc8f3cdd2b178e69c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3170, "license_type": "no_license", "max_line_length": 84, "num_lines": 100, "path": "/two-time-pad/client.py", "repo_name": "rkouere/PAC_TP2", "src_encoding": "UTF-8", "text": "import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport base64\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n <BLANKLINE>\n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\ndef xor(a, b):\n c = bytearray()\n for x,y in zip(a,b):\n c.append(x ^ y)\n return c\n\nURL=\"http://pac.bouillaguet.info/TP2\"\nserver = Server(URL)\n\n\n# seed 1\nseed=server.query(\"/two-time-pad/challenge/echallier/1\")\nquestion=server.query(\"/two-time-pad/question/echallier/1\")\n\nAPrime=seed['A'].encode()\nBPrime=seed['B'].encode()\nAXORB=xor(base64.b16decode(APrime), base64.b16decode(BPrime))\nAEncode=base64.b16decode(APrime)\n\ncpt = 0\n\nprint(xor(AXORB, b'0' * 1000).decode())\nprint('--------------')\nprint(xor(AXORB, b'1' * 1000).decode())\n\nprint(question)\nfor i in range(0, len(AXORB)):\n if AXORB[i]^ord('0') == ord('\\n'):\n print(i)\n elif AXORB[i]^ord('1') == ord('\\n'):\n print(i)\n\nprint('espace')\nfor i in range(586, len(AXORB)):\n if AXORB[i]^ord('0') == ord(' '):\n cpt = cpt + 1 \n print('i ' + str(i) + ' word ' + str(cpt))\n \n elif AXORB[i]^ord('1') == ord(' '):\n cpt = cpt + 1 \n print('i ' + str(i) + ' word ' + str(cpt))\n\nprint('mot')\nfor i in range(605, 613):\n print(chr(AXORB[i]^ord('0')) + ' - ' + chr(AXORB[i]^ord('1')))\n\n\nprint(server.query(\"/two-time-pad/answer/echallier/1\", {'word': 'grill'}))\n\n" } ]
6
mlinton/LinkedUp
https://github.com/mlinton/LinkedUp
067b3ff1c9d7694a47cb84b7533ba1bd69342a2a
2d31d8144b75f31969f899a9ed8c017326668a87
2e3623731d1da4f3c82da0adf9060d38d2ca1748
refs/heads/master
2021-08-24T13:18:56.068610
2017-11-21T06:56:04
2017-11-21T06:56:04
111,510,343
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6616393327713013, "alphanum_fraction": 0.7639344334602356, "avg_line_length": 42.57143020629883, "blob_id": "ab8bf8867575a212edc0e45ecc4dfba406a54c8e", "content_id": "e1a300916f6355f1b25c015f27ab8988e7c3997a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1525, "license_type": "no_license", "max_line_length": 198, "num_lines": 35, "path": "/LinkedUp.py", "repo_name": "mlinton/LinkedUp", "src_encoding": "UTF-8", "text": "# import libraries\nimport urllib2\nimport json\nfrom bs4 import BeautifulSoup\n\n\n\n# specify the url\nquote_page = 'https://www.linkedin.com/search/results/people/?facetCurrentCompany=%5B%221182748%22%5D&keywords=apega&origin=GLOBAL_SEARCH_HEADER'\n\n\nopener = urllib2.build_opener()\nopener.addheaders.append(('Cookie', 'bcookie=\"v=2&ce4fe073-0436-4071-828a-ffb5bda680fe\"'))\nopener.addheaders.append(('Cookie', '_ga=GA1.2.358098630.1511215779'))\nopener.addheaders.append(('Cookie', 'RT=s=1511216311522&r=https%3A%2F%2Fwww.linkedin.com%2F'))\nopener.addheaders.append(('Cookie', 'sl=\"v=1&dowlo\"'))\nopener.addheaders.append(('Cookie', 'lang=\"v=2&lang=en-us\"'))\nopener.addheaders.append(('Cookie', 'liap=true'))\nopener.addheaders.append(('Cookie', 'JSESSIONID=\"ajax:4849649980279285355\"'))\nopener.addheaders.append(('Cookie', 'mst=\"v=1&dowlo\"'))\nopener.addheaders.append(('Cookie', 'li_at=AQEDAQCUwtcC_6xIAAABX9uD5BIAAAFf_5BoElYAN2ZrWG6Hm39MVZfRrpyxNK9T1cj2ws5444ISzdC0lk9Y_bAUBowcgoYSHNo1JCiQMIqfYPH2Bv1_3-gRhXzX51pxIGyCW7cGz5bSVZp-hlhSqzf4'))\nopener.addheaders.append(('Cookie', 'lidc=\"b=OB07:g=642:u=346:i=1511216376:t=1511302776:s=AQFKAzYadBr44J4gysCyXXjP4COQQ06Q\"'))\n\n\npage = opener.open(quote_page)\n\n# parse the html using beautiful soap and store in variable soup\nsoup = BeautifulSoup(page, 'html.parser')\n\n# Take out the <div> of name and get its value\nname_box = soup.find('span', attrs={'class': 'name actor-name'})\nprint name_box\n\n# name = name_box.text.strip() # strip() is used to remove starting and trailing\n# print name\n" } ]
1
sriharikamani/Face-Liveness
https://github.com/sriharikamani/Face-Liveness
d16dff4e0478fc530b183f6ceaffb3d132096bb6
b081c619f1643f4e836c9c2abf818c7110566827
e2253cbacff60e3aa0098d50f110a9204f518440
refs/heads/master
2022-12-08T07:13:38.752430
2020-08-19T09:32:18
2020-08-19T09:32:18
288,688,684
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6656215190887451, "alphanum_fraction": 0.6779395341873169, "avg_line_length": 39.23423385620117, "blob_id": "02d638f69b20586d6ac290ca21acf20ee2675c87", "content_id": "f7748abfb255f609a144ef1ff10e1945ac360669", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4471, "license_type": "no_license", "max_line_length": 227, "num_lines": 111, "path": "/known_face_encodings.py", "repo_name": "sriharikamani/Face-Liveness", "src_encoding": "UTF-8", "text": "# ### Find and recognize unknown faces from known people faces using face_recognition API\n#Seps involved are\n\n#1. Find face in a image\n#2. Preprocess image\n# Converting it to grayscale\n# Resizing the image\n# CLAHE (Contrast Limited Adaptive Histogram Equalization) to smooth out lighting differences\n# Align\n#3. Analyze facial features and capture 128 basic measurements from each face using CNN\n#4. Compare each unknown person against known faces measurements captured and get a euclidean distance having the closest \n# measurement\n#5. The distance tells how similar the faces are and that’s our match!\n\nimport numpy as np\nimport pandas as pd\nimport face_recognition\nfrom PIL import Image,ImageEnhance #, ImageDraw\nfrom imutils.face_utils import FaceAligner\nfrom imutils.face_utils import rect_to_bb\nimport imutils\nimport os\nimport cv2\nimport dlib\n\nCASE_PATH = \"C:/Users/sriha/Documents/My_Data/Work_Documents/Posidex/face_detection_emotion/Data/haarcascade_frontalface_default.xml\"\npath = \"C:/Users/sriha/Documents/My_Data/Work_Documents/Posidex/face_rec/face_rec-blink/\"\nos.chdir(path)\n\n################## Face detectors\n\nhog_face_detector = dlib.get_frontal_face_detector()\nface_classifier = cv2.CascadeClassifier(CASE_PATH)\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\nfa = FaceAligner(predictor, desiredFaceWidth=256)\n\nknown_face_encodings = []\nknown_face_names = []\nknown_face_encode_error = []\n\nos.chdir(path + \"dataset/knownImages/\")\n\n# #### Load all known images from drive to get basic 128 measurements with upsample = 1\n\ndef initial():\n \n global known_face_encode_error\n global known_face_encodings\n global known_face_names\n \n known_face_encodings = []\n known_face_names = []\n Upsample = 1\n\n for dirpath, dnames, knownimages in os.walk(path +\"dataset/knownImages/\"):\n for knownimage in knownimages:\n img = face_recognition.load_image_file(path + \"dataset/knownImages/\" + knownimage)\n known_image_encode(img,Upsample,knownimage)\n\n # Try capturing basic facial measurements for failed images by incrementing the Upsample. Repeat for 4 iterations\n # Repeat for 3 iterations. Upsampling the image helps to detect smaller faces\n\n repeat = 1\n while ( (len(known_face_encode_error) > 0) and (repeat <=3)):\n\n known_face_encode_error_bk = known_face_encode_error\n known_face_encode_error = []\n Upsample = Upsample + 1\n \n for i in range(len(known_face_encode_error_bk)):\n img = face_recognition.load_image_file(path + \"dataset/knownImages/\" + known_face_encode_error_bk[i])\n known_image_encode(img,Upsample,known_face_encode_error_bk[i])\n\n repeat += 1\n \n return(known_face_encodings,known_face_names)\n\n# ### Routine to capture basic 128 measurements (known as embedding) for each known face images \ndef known_image_encode(img,Upsample,knownimage):\n \n global known_face_encode_error\n global known_face_encodings\n global known_face_names\n \n img = imutils.resize(img, width=400)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(5,8)) # Divide image into small blocks called “tiles” (Size is 8x8 by default in OpenCV)\n gray = clahe.apply(gray)\n #res = np.hstack((gray,clahe)) #stacking images side-by-side\n gray = cv2.bilateralFilter(gray,5,75,75) # bilateral filter d = 15 and sigmaColor = sigmaSpace = 75. The greater its value, the more further pixels will mix together, given that their colors lie within the sigmaColor range\n rects = hog_face_detector(gray, Upsample) # Upsampling each image to detect faces\n if (len(rects) > 0):\n\n for rect in rects:\n faceAligned = fa.align(img, gray, rect)\n try:\n face_encoding = face_recognition.face_encodings(faceAligned)[0] # Generate basic measurements\n known_face_encodings.append(face_encoding)\n known_face_names.append(knownimage)\n except Exception as e:\n known_face_encode_error.append(knownimage)\n break\n else:\n known_face_encode_error.append(knownimage)\n\n return()\n\nif __name__ == '__main__':\n known_face_encodings,known_face_names = initial()\n\n#### End of the Code ###" } ]
1
sju-code/sju-code
https://github.com/sju-code/sju-code
842cc5bbec483a2ca27ea848f80f59a03df8672a
2015febd197e23a66cbfce1209b5e9a3c1197f1c
93f462f380e2fc7ea24e6b7a1c38fb16e09bd166
refs/heads/main
2023-07-15T19:54:17.525601
2021-08-22T04:51:27
2021-08-22T04:51:27
327,765,856
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2777777910232544, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 16, "blob_id": "e39e951d93562e028ca69501d66e70f0e69d25cb", "content_id": "8e8441587ba5371a006cc7c6c327f7375e3ad1ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/61.py", "repo_name": "sju-code/sju-code", "src_encoding": "UTF-8", "text": "print(449 + 639)\n\n" } ]
1
TimurAbdymazhinov/adeliya-backend
https://github.com/TimurAbdymazhinov/adeliya-backend
cd973f28a60915e3eca0cb03c00048d7e9b8c656
4420f615af2bf529380e5da08af830e0fc12b73a
dd477c82ce2e4859eeb73ef4085d3226c37c57fc
refs/heads/main
2023-06-24T01:18:48.008891
2021-07-26T18:52:19
2021-07-26T18:52:19
389,737,295
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6798487901687622, "alphanum_fraction": 0.6810119152069092, "avg_line_length": 28.39316177368164, "blob_id": "1dd1a7fdd63b193d3390fe56e29a650d018dfaec", "content_id": "f422ff494e51074faf59ce3984e8e43a2e78f886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3456, "license_type": "no_license", "max_line_length": 89, "num_lines": 117, "path": "/apps/info/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.db.models import Prefetch\n\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import generics\nfrom rest_framework.permissions import AllowAny\n\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom apps.brand.pagination import SmallListPagination\nfrom core.constants import PROMOTION\nfrom .models import (\n Banner,\n ProgramCondition,\n Contact,\n PromotionAndNews, PromotionAndNewsImage,\n)\nfrom .serializers import (\n ProgramConditionSerializer,\n ContactListSerializer,\n BannerDetailSerializer,\n BannerAndPromotionSerializer,\n PromotionAndNewsSerializer,\n PromotionAndNewsDetailSerializer,\n)\nfrom apps.notifications.service import SendPushNotification\n\n\nclass BannerRetrieveAPIView(generics.RetrieveAPIView):\n queryset = Banner.objects.all()\n serializer_class = BannerDetailSerializer\n\n def get_object(self):\n return self.get_queryset().first()\n\n\nclass BannerAndPromotionAPIView(generics.RetrieveAPIView):\n \"\"\"\n API view for banner and promotion\n \"\"\"\n serializer_class = BannerAndPromotionSerializer\n\n def retrieve(self, request, *args, **kwargs):\n banner = Banner.objects.first()\n promotion = (\n PromotionAndNews.objects.filter(\n is_active=True,\n information_type=PROMOTION\n ).prefetch_related(\n Prefetch('images', PromotionAndNewsImage.objects.filter(\n is_main=True\n ))\n )[:3]\n )\n banner_and_promotion = dict(\n banner=banner,\n promotion=promotion,\n )\n serializer = self.get_serializer(banner_and_promotion)\n return Response(serializer.data)\n\n\nclass ProgramConditionAPIView(generics.RetrieveAPIView):\n \"\"\"\n API view for ProgramCondition\n \"\"\"\n queryset = ProgramCondition.objects.all()\n serializer_class = ProgramConditionSerializer\n\n def get_object(self):\n return self.get_queryset().first()\n\n\nclass ContactListAPIView(generics.ListAPIView):\n \"\"\"\n API list view for contact\n \"\"\"\n queryset = Contact.objects.all()\n serializer_class = ContactListSerializer\n\n\nclass PromotionAndNewsListAPIView(generics.ListAPIView):\n \"\"\"\n API list view for promotions and news\n \"\"\"\n queryset = (\n PromotionAndNews.objects.filter(is_active=True).prefetch_related(\n Prefetch(\n 'images', PromotionAndNewsImage.objects.filter(is_main=True)\n )\n )\n )\n serializer_class = PromotionAndNewsSerializer\n pagination_class = SmallListPagination\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['information_type']\n permission_classes = [AllowAny]\n\n\nclass PromotionAndNewsRetrieveAPIView(generics.RetrieveAPIView):\n \"\"\"\n API detail view for promotions and news\n \"\"\"\n queryset = PromotionAndNews.objects.all()\n serializer_class = PromotionAndNewsDetailSerializer\n permission_classes = [AllowAny]\n\n @swagger_auto_schema(\n responses={\n 404: '{\"detail\": \"Страница не найдена.\"}',\n }\n )\n def get(self, request, *args, **kwargs):\n SendPushNotification.set_notification_viewed_for_article(\n request, self.get_object()\n )\n return super(PromotionAndNewsRetrieveAPIView, self).get(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.575075089931488, "alphanum_fraction": 0.575075089931488, "avg_line_length": 25.639999389648438, "blob_id": "e027444a16c1e2bffb6ca580ec070e5a574398c6", "content_id": "331e6837b3c756ab3ae8664385346cb042ebc9ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "no_license", "max_line_length": 58, "num_lines": 25, "path": "/apps/notifications/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import json\n\nfrom rest_framework import serializers\n\nfrom apps.notifications.models import Notification\n\n\nclass NotificationSerializer(serializers.ModelSerializer):\n body = serializers.SerializerMethodField()\n\n class Meta:\n model = Notification\n fields = [\n 'id', 'notice_type', 'is_on_credit',\n 'is_viewed', 'body', 'created_at'\n ]\n extra_kwargs = {\n 'notice_type': {'read_only': True},\n 'is_on_credit': {'read_only': True},\n 'body': {'read_only': True},\n 'is_viewed': {'required': True},\n }\n\n def get_body(self, obj):\n return json.loads(obj.body)\n" }, { "alpha_fraction": 0.5711237788200378, "alphanum_fraction": 0.6009957194328308, "avg_line_length": 36, "blob_id": "a041ac17b47c5f802f5734d0d25d39a107a73be4", "content_id": "a5a45946af68170ee72a3722b47cf0188bc6b650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1484, "license_type": "no_license", "max_line_length": 133, "num_lines": 38, "path": "/apps/check/migrations/0003_auto_20210426_1106.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-26 05:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('check', '0002_auto_20210415_1834'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='check',\n name='accrued_point',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True, verbose_name='Начислено бонусов'),\n ),\n migrations.AlterField(\n model_name='check',\n name='bonus_paid',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True, verbose_name='Оплачено бонусами'),\n ),\n migrations.AlterField(\n model_name='check',\n name='money_paid',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True, verbose_name='Оплачено деньгами'),\n ),\n migrations.AlterField(\n model_name='check',\n name='total_paid',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True, verbose_name='Сумма оплаты'),\n ),\n migrations.AlterField(\n model_name='check',\n name='withdrawn_point',\n field=models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True, verbose_name='Снято бонусов (Возврат)'),\n ),\n ]\n" }, { "alpha_fraction": 0.6712871193885803, "alphanum_fraction": 0.6712871193885803, "avg_line_length": 30.5625, "blob_id": "f82c340d0a7f53c218eb30ae1c2e85db0441baf8", "content_id": "739322b10171e76a3b846ef66bc6ac0fca731122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 80, "num_lines": 16, "path": "/apps/brand/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path, include\n\nfrom apps.brand.views import (\n BrandRetrieveAPIView, BrandListAPIView, FilialListAPIView,\n FilialRetrieveAPIView\n)\n\n\nurlpatterns = [\n path('', BrandListAPIView.as_view(), name='brand_list'),\n path('<int:id>/', BrandRetrieveAPIView.as_view(), name='brand_detail'),\n path('filial/', include([\n path('', FilialListAPIView.as_view(), name='filial_list'),\n path('<int:id>/', FilialRetrieveAPIView.as_view(), name='filial_detail')\n ])),\n]\n" }, { "alpha_fraction": 0.6904761791229248, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 27, "blob_id": "b77c5ef7a99a1f69e83efe696c759d3f857151a1", "content_id": "70b65a8195411fe7d7e4b8f5e87cc7fbdc2896d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 75, "num_lines": 12, "path": "/apps/check/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom apps.check.views import (\n QRCodeAPIView, CheckListAPIView, CheckRetrieveAPIView\n)\n\n\nurlpatterns = [\n path('', CheckListAPIView.as_view(), name='check_list'),\n path('<int:pk>/', CheckRetrieveAPIView.as_view(), name='check_detail'),\n path('qr/', QRCodeAPIView.as_view(), name='qr_code'),\n]\n" }, { "alpha_fraction": 0.6800791621208191, "alphanum_fraction": 0.6800791621208191, "avg_line_length": 42.31428527832031, "blob_id": "6103b05241eabbbeabd1cb75f4034446d2a7e51b", "content_id": "b1e6b2206ee0c373cdf0996504a1b2a60cfac211", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 101, "num_lines": 35, "path": "/apps/account/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom fcm_django.api.rest_framework import FCMDeviceAuthorizedViewSet\n\nfrom apps.account.views import (\n AuthAPIView, LoginConfirmAPIView, CityListAPIView,\n UserUpdateAPIView, UserAvatarRetrieveUpdateAPIView,\n SendSmsToOldPhoneAPIView, OldPhoneConfirmAPIView,\n ChangeOldPhoneAPIView, NewPhoneConfirmAPIView, UserRetrieveAPIView\n)\n\nurlpatterns = [\n path('auth/', AuthAPIView.as_view(), name='auth'),\n path('login-confirm/', LoginConfirmAPIView.as_view(), name='login-confirm'),\n path('send-sms-to-old-phone/', SendSmsToOldPhoneAPIView.as_view(), name='send_sms_to_old_phone'),\n path('old-phone-confirm/', OldPhoneConfirmAPIView.as_view(), name='old_phone_confirm'),\n\n path('change-old-phone/', ChangeOldPhoneAPIView.as_view(), name='change_old_phone'),\n path('new-phone-confirm/', NewPhoneConfirmAPIView.as_view(), name='new_phone_confirm'),\n\n path('cities/', CityListAPIView.as_view(), name='cities'),\n path('', UserUpdateAPIView.as_view(), name='update'),\n path('data/', UserRetrieveAPIView.as_view(), name='retrieve'),\n path('avatar/', UserAvatarRetrieveUpdateAPIView.as_view(), name='avatar'),\n\n path(\n 'device/', FCMDeviceAuthorizedViewSet.as_view({'post': 'create'}),\n name='create_fcm_device',\n ),\n path(\n 'device/<str:registration_id>/',\n FCMDeviceAuthorizedViewSet.as_view({'delete': 'destroy',\n 'put': 'update'}),\n name='delete_fcm_device',\n ),\n]\n" }, { "alpha_fraction": 0.5827272534370422, "alphanum_fraction": 0.6045454740524292, "avg_line_length": 39.74074172973633, "blob_id": "251dc44c3a797447a55ab28863d56a04ea119854", "content_id": "dc99de3eb2222d241e4ef373c8d2168cbb1135e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 129, "num_lines": 27, "path": "/apps/setting/migrations/0002_appversion.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-07 07:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('setting', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AppVersion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('android_version', models.CharField(max_length=15, verbose_name='Версия для android приложения')),\n ('android_force_update', models.BooleanField(default=False, verbose_name='Принудительное обновление(Вкл/Выкл)')),\n ('ios_version', models.CharField(max_length=15, verbose_name='Версия для ios приложения')),\n ('ios_force_update', models.BooleanField(default=False, verbose_name='Принудительное обновление(Вкл/Выкл)')),\n ],\n options={\n 'verbose_name': 'Версия мобильного приложения',\n 'verbose_name_plural': 'Версии мобильного приложения',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6194332242012024, "alphanum_fraction": 0.6261808276176453, "avg_line_length": 29.875, "blob_id": "54defd019b718f1e35a1ae77ba39b87466eaa5a1", "content_id": "f25208d8314c116c14897aa42a4034c8a9873641", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/apps/check/admin.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom apps.check.models import Check\n\n\[email protected](Check)\nclass CheckAdmin(admin.ModelAdmin):\n list_display = ('unique_1c_check_code', 'user', 'filial',)\n search_fields = ('unique_1c_check_code',)\n readonly_fields = (\n 'unique_1c_check_code', 'money_paid', 'bonus_paid', 'total_paid',\n 'accrued_point', 'accrued_point_date', 'withdrawn_point',\n 'withdrawn_point_date', 'is_active', 'user', 'filial', 'status',\n 'is_on_credit', 'balance_owed', 'due_date',\n )\n exclude = (\n 'user_1c_code', 'filial_1c_code'\n )\n\n def has_add_permission(self, request):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n" }, { "alpha_fraction": 0.5559304356575012, "alphanum_fraction": 0.5639761090278625, "avg_line_length": 46.567901611328125, "blob_id": "81895c8610eabb861c619cb327db225f315e0d00", "content_id": "f613a5627b553f3134ccf07042326e817830a195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4233, "license_type": "no_license", "max_line_length": 272, "num_lines": 81, "path": "/apps/info/migrations/0001_initial.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2 on 2021-03-29 07:58\n\nimport core.utils\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Banner',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=25, verbose_name='Заголовок баннера')),\n ('image', models.ImageField(upload_to=core.utils.generate_filename, verbose_name='Фото баннера')),\n ],\n options={\n 'verbose_name': 'Баннер',\n 'verbose_name_plural': 'Баннера',\n },\n ),\n migrations.CreateModel(\n name='Contact',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('icon_type', models.CharField(choices=[('email-icon', 'Иконка почты'), ('instagram-icon', 'Иконка instagram'), ('facebook-icon', 'Иконка facebook'), ('website-icon', 'Иконка веб-сайта')], default='website-icon', max_length=20, verbose_name='Тип иконки')),\n ('title', models.CharField(max_length=100, verbose_name='Заголовок ссылки')),\n ('link', models.CharField(max_length=150, verbose_name='Ссылка')),\n ],\n options={\n 'verbose_name': 'Контакт',\n 'verbose_name_plural': 'Контакты',\n },\n ),\n migrations.CreateModel(\n name='ProgramCondition',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50, verbose_name='Заголовок программы лояльности')),\n ('description', models.TextField(verbose_name='Текст программы лояльности')),\n ],\n options={\n 'verbose_name': 'Программа лояльности',\n 'verbose_name_plural': 'Программы лояльности',\n },\n ),\n migrations.CreateModel(\n name='PromotionAndNews',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('create_at', models.DateField(auto_now_add=True)),\n ('information_type', models.CharField(choices=[('news', 'Новость'), ('promotion', 'Акция')], default='news', max_length=15)),\n ('title', models.CharField(max_length=100, verbose_name='Заголовок')),\n ('description', models.TextField(verbose_name='Текст программы лояльности')),\n ('is_active', models.BooleanField(default=False, verbose_name='Активный(Вкл/Выкл)')),\n ],\n options={\n 'verbose_name': 'Акция и новость',\n 'verbose_name_plural': 'Акции и новости',\n },\n ),\n migrations.CreateModel(\n name='PromotionAndNewsImage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.ImageField(upload_to=core.utils.generate_filename, verbose_name='Фото новости или акции')),\n ('is_main', models.BooleanField(default=False, verbose_name='Превью(Вкл/Выкл)')),\n ('information', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='info.PromotionAndNews')),\n ],\n options={\n 'verbose_name': 'Фотография для акции/новости',\n 'verbose_name_plural': 'Фотографии для акций/новости',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.7324841022491455, "alphanum_fraction": 0.7324841022491455, "avg_line_length": 21.428571701049805, "blob_id": "306ad72304e264f2748a9dff6f9ea3c89e6a2df3", "content_id": "5db917a7d53eeb2def3e564c9707776197c1e387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 70, "num_lines": 7, "path": "/apps/setting/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import AppVersionAPIView\n\nurlpatterns = [\n path('version/', AppVersionAPIView.as_view(), name='app-version'),\n]\n" }, { "alpha_fraction": 0.6035978198051453, "alphanum_fraction": 0.6122711300849915, "avg_line_length": 25.952381134033203, "blob_id": "7fadb8745b6a7ac233759aed208a4248f9f8e595", "content_id": "462b71eebb1fb4deca7c4912a9b4f4f547163b2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6226, "license_type": "no_license", "max_line_length": 91, "num_lines": 231, "path": "/core/settings/base.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import os\nimport logging\n\nimport environ\n\nBASE_DIR = os.path.dirname(\n os.path.dirname(os.path.dirname((os.path.abspath(__file__)))))\n\nenv = environ.Env()\n\nINSTALLED_APPS = [\n 'huey.contrib.djhuey',\n 'jet',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'rest_framework.authtoken',\n 'rest_framework',\n 'solo',\n 'ckeditor',\n 'django_2gis_maps',\n 'fcm_django',\n 'drf_yasg',\n 'django_filters',\n 'adminsortable2',\n\n 'apps.account',\n 'apps.brand',\n 'apps.check',\n 'apps.info',\n 'apps.setting',\n 'apps.notifications',\n]\n\nFCM_DJANGO_SETTINGS = {\n # Your firebase API KEY\n \"FCM_SERVER_KEY\": env.str('FCM_SERVER_KEY'),\n # true if you want to have only one active device per registered user at a time\n # default: False\n \"ONE_DEVICE_PER_USER\": False,\n # devices to which notifications cannot be sent,\n # are deleted upon receiving error response from FCM\n # default: False\n \"DELETE_INACTIVE_DEVICES\": True,\n}\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'apps.setting.middleware.ApplicationStatusMiddleware',\n]\n\nROOT_URLCONF = 'core.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'core.wsgi.application'\n\nAUTH_USER_MODEL = 'account.User'\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLANGUAGE_CODE = 'ru'\n\nTIME_ZONE = 'Asia/Bishkek'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\nJET_SIDE_MENU_COMPACT = True\n\n# ckeditor\nCKEDITOR_UPLOAD_PATH = \"uploads/\"\n\nSWAGGER_SETTINGS = {\n 'SECURITY_DEFINITIONS': {\n 'Basic': {\n 'type': 'basic'\n },\n 'Token': {\n 'type': 'apiKey',\n 'name': 'Authorization',\n 'in': 'header'\n }\n }\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n ),\n}\n\nNIKITA_LOGIN = env.str('NIKITA_LOGIN')\nNIKITA_PASSWORD = env.str('NIKITA_PASSWORD')\nNIKITA_SENDER = env.str('NIKITA_SENDER')\nNIKITA_TEST = env.int('NIKITA_TEST', default=1)\n\nBASE_1C_SERVER_DOMAIN = env.str(\n 'BASE_1C_SERVER_DOMAIN', default='http://185.29.184.147:12344'\n)\n\nLINKS_1C = {\n 'SYNC_USER_URL': BASE_1C_SERVER_DOMAIN + '/sendUser',\n 'GET_USER_WALLET_DATA_URL':\n BASE_1C_SERVER_DOMAIN + '/userPoint/',\n 'CHANGE_USER_NUMBER': BASE_1C_SERVER_DOMAIN + '/change_number'\n}\n\nUSER_1C = {\n 'username': env.str('USER_1C_USERNAME'),\n 'password': env.str('USER_1C_PASSWORD')\n}\n\n\nLOGGING = {\n \"version\": 1,\n \"formatters\": {\"simple\": {\"format\": \"{levelname} {message}\", \"style\": \"{\"}},\n \"handlers\": {\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"simple\",\n }\n },\n \"loggers\": {\n \"django\": {\"handlers\": [\"console\"], \"propagate\": True},\n \"django.request\": {\n \"handlers\": [\"console\"],\n \"level\": \"ERROR\",\n \"propagate\": False,\n },\n \"django.db.backends\": {\n \"handlers\": [\"console\"],\n \"level\": \"ERROR\",\n \"propagate\": False,\n },\n },\n}\n\nDATA_UPLOAD_MAX_MEMORY_SIZE = 5242880\n\nHUEY = {\n 'huey_class': 'huey.RedisHuey', # Huey implementation to use.\n 'immediate': False,\n 'connection': {\n 'host': 'localhost',\n 'port': 6379,\n 'db': 0,\n 'connection_pool': None, # Definitely you should use pooling!\n # ... tons of other options, see redis-py for details.\n\n # huey-specific connection parameters.\n 'read_timeout': 1, # If not polling (blocking pop), use timeout.\n 'url': None, # Allow Redis config via a DSN.\n },\n\n 'consumer': {\n 'workers': 5,\n 'worker_type': 'thread',\n 'initial_delay': 0.1, # Smallest polling interval, same as -d.\n 'backoff': 1.15, # Exponential backoff using this rate, -b.\n 'max_delay': 10.0, # Max possible polling interval, -m.\n 'scheduler_interval': 1, # Check schedule every second, -s.\n 'periodic': True, # Enable crontab feature.\n 'check_worker_health': True, # Enable worker health checks.\n 'health_check_interval': 1, # Check worker health every second.\n },\n}\n\ntry:\n from .local import *\n INSTALLED_APPS += ['debug_toolbar']\n MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']\nexcept ImportError:\n try:\n from .prod import *\n except ImportError:\n logging.error('core.settings.prod.py file not found !')\n" }, { "alpha_fraction": 0.5726414918899536, "alphanum_fraction": 0.6216981410980225, "avg_line_length": 34.33333206176758, "blob_id": "a80650610b3c0a0c9772753c33855f389c25b9c7", "content_id": "ce733f317e903fb5e30b945d9c634afb268b0a70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 192, "num_lines": 30, "path": "/apps/notifications/migrations/0002_auto_20210428_1228.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-28 06:28\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0008_auto_20210428_1228'),\n ('check', '0003_auto_20210426_1106'),\n ('notifications', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='notification',\n name='linked_object_id',\n ),\n migrations.AddField(\n model_name='notification',\n name='linked_article',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notice', to='info.PromotionAndNews', verbose_name='Новость или Акция'),\n ),\n migrations.AddField(\n model_name='notification',\n name='linked_check',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notice', to='check.Check', verbose_name='Чек'),\n ),\n ]\n" }, { "alpha_fraction": 0.6067761778831482, "alphanum_fraction": 0.627310037612915, "avg_line_length": 32.58620834350586, "blob_id": "65a88cd948430168604ddf370ab870dce0048b12", "content_id": "ff5ec78b2eec33a3ca2a41451e973ac79778040b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 148, "num_lines": 29, "path": "/apps/info/migrations/0002_auto_20210329_1451.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2 on 2021-03-29 08:51\n\nimport ckeditor_uploader.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='programcondition',\n name='description',\n field=ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Текст программы лояльности'),\n ),\n migrations.AlterField(\n model_name='promotionandnews',\n name='description',\n field=ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Текст программы лояльности'),\n ),\n migrations.AlterField(\n model_name='promotionandnews',\n name='information_type',\n field=models.CharField(choices=[('news', 'Новость'), ('promotion', 'Акция')], default='news', max_length=15, verbose_name='Тип записи'),\n ),\n ]\n" }, { "alpha_fraction": 0.5870967507362366, "alphanum_fraction": 0.6301075220108032, "avg_line_length": 24.83333396911621, "blob_id": "50bee190981efb9aefe96ed693b8454c55bce21e", "content_id": "ba02050654e8727e892fcf2f4fa6387beeda38e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 105, "num_lines": 18, "path": "/apps/setting/migrations/0004_auto_20210505_1513.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-05 09:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('setting', '0003_appversion_ios_build_number'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='appversion',\n name='ios_build_number',\n field=models.PositiveIntegerField(null=True, verbose_name='Build версия для ios приложения'),\n ),\n ]\n" }, { "alpha_fraction": 0.7843137383460999, "alphanum_fraction": 0.7843137383460999, "avg_line_length": 50, "blob_id": "31d0203ddcedff9b66dd263ca0aa8fba99254778", "content_id": "cbd7e0ba2e21af1b41e0d1454b5c08bfa0cf317b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 50, "num_lines": 1, "path": "/apps/brand/__init__.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "default_app_config = 'apps.brand.apps.BrandConfig'\n" }, { "alpha_fraction": 0.7113820910453796, "alphanum_fraction": 0.7235772609710693, "avg_line_length": 25.90625, "blob_id": "1657acd2cfe96bfa5322e6f286a89c58d8f35715", "content_id": "dee8c9a8534e1f6c0041c0a0d7967552c7a3e4f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1722, "license_type": "no_license", "max_line_length": 76, "num_lines": 64, "path": "/apps/info/tests/factories.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from random import choice\n\nimport factory\n\nfrom apps.info.models import (\n Banner, ProgramCondition,\n Contact, PromotionAndNews,\n PromotionAndNewsImage, ContactIcon,\n)\nfrom core.constants import PROMOTION, NEWS\n\n\nclass ContactIconFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = ContactIcon\n\n title = factory.Faker('name')\n image = factory.django.ImageField(width=1024, height=768)\n\n\nclass ContactFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Contact\n\n title = factory.Faker('name')\n link = factory.Faker('url')\n icon_image = factory.SubFactory(ContactIconFactory)\n\n\nclass BannerFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Banner\n\n title = factory.Faker('name')\n image = factory.django.ImageField(width=1024, height=768)\n description = factory.Faker('text')\n\n\nclass ProgramConditionFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = ProgramCondition\n\n title = factory.Faker('name')\n description = factory.Faker('text')\n\n\nclass PromotionAndNewsFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = PromotionAndNews\n\n information_type = factory.Sequence(lambda x: choice([PROMOTION, NEWS]))\n created_at = factory.Faker('date_time')\n title = factory.Faker('city')\n description = factory.Faker('text')\n is_active = True\n\n\nclass PromotionAndNewsImageFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = PromotionAndNewsImage\n\n image = factory.django.ImageField(width=1024, height=768)\n is_main = factory.Sequence(lambda x: choice([True, False]))\n information = factory.SubFactory(PromotionAndNewsFactory)\n" }, { "alpha_fraction": 0.568306028842926, "alphanum_fraction": 0.6357012987136841, "avg_line_length": 26.450000762939453, "blob_id": "0e6e8baf468cff4ac4465755a2b540bd7c591191", "content_id": "26bf8e9abdb954099a6d8d5714b5001835b26fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "no_license", "max_line_length": 141, "num_lines": 20, "path": "/apps/brand/migrations/0009_auto_20210426_1104.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-26 05:04\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0008_auto_20210415_1834'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='filial',\n name='filial_1c_code',\n field=models.CharField(default=django.utils.timezone.now, max_length=255, unique=True, verbose_name='Уникальный 1C код филиала'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.531460702419281, "alphanum_fraction": 0.5328651666641235, "avg_line_length": 28.66666603088379, "blob_id": "a43b89f8417f5fd3c011156edcbcbfa67a3590da", "content_id": "764d5bd0a473b921d1771e6ddbeab934b898cce0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3581, "license_type": "no_license", "max_line_length": 87, "num_lines": 120, "path": "/apps/brand/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom rest_framework import exceptions\n\nfrom haversine import haversine\n\nfrom apps.brand.models import WorkTime\nfrom core.constants import WEEKDAY\n\n\nclass FilialService:\n \"\"\"\n Service for check filial status\n \"\"\"\n\n @staticmethod\n def check_filial_status(filial_obj) -> bool:\n time_now = datetime.now().time()\n weekday_now = datetime.today().weekday() + 1\n work_time = WorkTime.objects.filter(filial=filial_obj, day=weekday_now).first()\n try:\n check_is_filial_open = (\n work_time.start_work <= time_now <= work_time.end_work\n )\n except TypeError:\n return False\n except AttributeError:\n return False\n\n return check_is_filial_open\n\n @staticmethod\n def get_geolocation(request):\n geo_lat = request.GET.get('lat')\n geo_long = request.GET.get('long')\n\n if geo_lat and geo_long:\n try:\n geo_lat = float(geo_lat)\n geo_long = float(geo_long)\n except Exception:\n raise exceptions.ValidationError(\n {'geolocation': 'Неправильный формат query param: lat long'}\n )\n return geo_lat, geo_long\n\n return None\n\n @staticmethod\n def calculate_distance(filial_geolocation, client_geolocation):\n if not client_geolocation:\n return None\n\n filial_geolocation = tuple(map(float, filial_geolocation.split(',')))\n\n return haversine(filial_geolocation, client_geolocation)\n\n\nclass WorkDayService:\n\n @staticmethod\n def create_weekday(filial_obj):\n work_days = []\n for day in range(7):\n works_time_obj = WorkTime(day=day + 1, filial=filial_obj)\n work_days.append(works_time_obj)\n WorkTime.objects.bulk_create(work_days)\n\n @classmethod\n def get_weekday(cls, filial_obj):\n \"\"\" Get workdays data in WorkTime model\"\"\"\n workdays = WorkTime.objects.filter(filial=filial_obj)\n data = cls.get_work_time(workdays)\n return data\n\n @classmethod\n def get_work_time(cls, workdays):\n \"\"\" Getting works time for JSON response \"\"\"\n output_data = workdays\n raw_data = cls.get_raw_data(output_data)\n data = cls.sort_raw_data(raw_data)\n\n return data\n\n @staticmethod\n def get_raw_data(output_data):\n \"\"\" Getting raw data \"\"\"\n raw_data = []\n\n for item in output_data:\n if item.start_work is None or item.end_work is None:\n data = {\n 'days': WEEKDAY[item.day],\n 'time': 'ВЫХ',\n 'isWeekends': True\n }\n raw_data.append(data)\n else:\n data = {\n 'days': WEEKDAY[item.day],\n 'time': f'{str(item.start_work)[:5]} - {str(item.end_work)[:5]}',\n 'isWeekends': False\n }\n raw_data.append(data)\n\n return raw_data\n\n @staticmethod\n def sort_raw_data(raw_data):\n \"\"\" Sorted raw data for JSON response \"\"\"\n raw_data_copy = raw_data.copy()\n for i in raw_data:\n for j in raw_data_copy:\n if i['time'] == j['time']:\n if i['days'] == j['days']:\n continue\n else:\n i['days'] += f\" {j['days']}\"\n raw_data.remove(j)\n return raw_data\n" }, { "alpha_fraction": 0.6252654194831848, "alphanum_fraction": 0.6252654194831848, "avg_line_length": 23.153846740722656, "blob_id": "0a4c8486fa473bde8808addbf4510a9a8a6d6bd5", "content_id": "482494b14a4b224b20e062b9247c6854daebd37b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/apps/info/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import (\n BannerAndPromotionAPIView,\n BannerRetrieveAPIView,\n ProgramConditionAPIView,\n ContactListAPIView,\n PromotionAndNewsListAPIView,\n PromotionAndNewsRetrieveAPIView,\n)\n\nurlpatterns = [\n path(\n 'promotions-news/',\n PromotionAndNewsListAPIView.as_view(),\n name='promotions-news'\n ),\n path(\n 'promotions-news/<int:pk>/',\n PromotionAndNewsRetrieveAPIView.as_view(),\n name='promotions-news-detail'\n ),\n path(\n 'banner-promotions/',\n BannerAndPromotionAPIView.as_view(),\n name='banner-promotions'\n ),\n path(\n 'banner/',\n BannerRetrieveAPIView.as_view(),\n name='banner-detail'\n ),\n path(\n 'program-condition/',\n ProgramConditionAPIView.as_view(),\n name='program_condition'\n ),\n path('contacts/', ContactListAPIView.as_view(), name='contacts')\n]\n" }, { "alpha_fraction": 0.512515664100647, "alphanum_fraction": 0.5369211435317993, "avg_line_length": 37.0476188659668, "blob_id": "13e6eafc9f57be548dc5b1b59a1fabdd43c5c264", "content_id": "a4e6b23e963faf4368144470c3c76aeb64333f7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1690, "license_type": "no_license", "max_line_length": 165, "num_lines": 42, "path": "/apps/brand/migrations/0011_auto_20210601_1549.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-06-01 09:49\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0010_auto_20210512_1145'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='filial',\n name='end_work',\n ),\n migrations.RemoveField(\n model_name='filial',\n name='is_around_the_clock',\n ),\n migrations.RemoveField(\n model_name='filial',\n name='start_work',\n ),\n migrations.CreateModel(\n name='WorkTime',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('day', models.SmallIntegerField(choices=[(1, 'ПН'), (2, 'ВТ'), (3, 'СР'), (4, 'ЧТ'), (5, 'ПТ'), (6, 'СБ'), (7, 'ВС')], verbose_name='День недели')),\n ('start_work', models.TimeField(blank=True, null=True, verbose_name='Начало рабочего времени')),\n ('end_work', models.TimeField(blank=True, null=True, verbose_name='Конец рабочего времени')),\n ('filial', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='works_time', to='brand.Filial', verbose_name='Филиал')),\n ],\n options={\n 'verbose_name': 'Рабочий день',\n 'verbose_name_plural': 'Рабочие дни',\n 'ordering': ['day'],\n 'unique_together': {('day', 'filial')},\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5211480259895325, "alphanum_fraction": 0.5445619225502014, "avg_line_length": 15.974358558654785, "blob_id": "1c3bef263685bc1f711b3e7b5b11aaeda2db97e8", "content_id": "e2a9d0d908acaa6b4bba2649e69250728f152369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1554, "license_type": "no_license", "max_line_length": 55, "num_lines": 78, "path": "/core/constants.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "MALE = 'male'\nFEMALE = 'female'\n\nGENDER_TYPE = (\n (MALE, 'Мужской'),\n (FEMALE, 'Женский')\n)\n\nNEWS = 'news'\nPROMOTION = 'promotion'\n\nINFORMATION_TYPE = (\n (NEWS, 'Новость'),\n (PROMOTION, 'Акция'),\n)\n\nACCRUED = 'accrued'\nWITHDRAW = 'withdrawn'\nACCRUED_AND_WITHDRAW = 'accrued_and_withdrawn'\n\nNOTIFICATION_TYPE = (\n (ACCRUED, 'Начислено бонусов'),\n (WITHDRAW, 'Снято бонусов'),\n (ACCRUED_AND_WITHDRAW, 'Начислено и снято'),\n (PROMOTION, 'Акции'),\n (NEWS, 'Новости')\n)\n\nCHECK_TYPE = (\n (ACCRUED, 'Начислено'),\n (WITHDRAW, 'Снято'),\n (ACCRUED_AND_WITHDRAW, 'Начислено и снято'),\n)\n\nDUE_DATE_CHECK_MESSAGE = 'У вас есть неоплаченный долг'\n\nMONTH_NAMES = {\n '01': 'Январь',\n '02': 'Февраль',\n '03': 'Март',\n '04': 'Апрель',\n '05': 'Май',\n '06': 'Июнь',\n '07': 'Июль',\n '08': 'Август',\n '09': 'Сентябрь',\n '10': 'Октябрь',\n '11': 'Ноябрь',\n '12': 'Декабрь',\n}\n\nMONDAY = 1\nTUESDAY = 2\nWEDNESDAY = 3\nTHURSDAY = 4\nFRIDAY = 5\nSATURDAY = 6\nSUNDAY = 7\n\nWORK_DAYS = (\n (MONDAY, 'ПН'),\n (TUESDAY, 'ВТ'),\n (WEDNESDAY, 'СР'),\n (THURSDAY, 'ЧТ'),\n (FRIDAY, 'ПТ'),\n (SATURDAY, 'СБ'),\n (SUNDAY, 'ВС'),\n)\n\nWEEKDAY = {\n MONDAY: 'ПН',\n TUESDAY: 'ВТ',\n WEDNESDAY: 'СР',\n THURSDAY: 'ЧТ',\n FRIDAY: 'ПТ',\n SATURDAY: 'СБ',\n SUNDAY: 'ВС',\n}\n" }, { "alpha_fraction": 0.5650320053100586, "alphanum_fraction": 0.6183369159698486, "avg_line_length": 25.05555534362793, "blob_id": "5e526c92978c4102560204cc80810f577784be72", "content_id": "6d169fff69499e80b71db0903e287c96c82c1c51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 121, "num_lines": 18, "path": "/apps/account/migrations/0006_user_user_1c_code.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-14 05:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0005_user_is_old_phone_confirmed'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='user_1C_code',\n field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Уникальный 1С код пользователя'),\n ),\n ]\n" }, { "alpha_fraction": 0.7755101919174194, "alphanum_fraction": 0.7755101919174194, "avg_line_length": 48, "blob_id": "bfd595c98c67b18c08b0e0e5b035f4dc9161ab21", "content_id": "0ea4bf8eab3bbd387fa146c22f3557f9ec0a3fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 49, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/apps/info/__init__.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "default_app_config = 'apps.info.apps.InfoConfig'\n" }, { "alpha_fraction": 0.6399132609367371, "alphanum_fraction": 0.6442516446113586, "avg_line_length": 34.46154022216797, "blob_id": "39e53737d8cfc6277de0e5cfd2e75d361da5b8b0", "content_id": "81c1a6b532f7e4afda6c9fb58c533f33f4a486d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 922, "license_type": "no_license", "max_line_length": 95, "num_lines": 26, "path": "/apps/brand/pagination.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework.pagination import PageNumberPagination\n\n\nclass LargeListPagination(PageNumberPagination):\n page_size = 20\n\n def get_paginated_response(self, data):\n return Response({\n 'count': self.page.paginator.count,\n 'next': self.page.next_page_number() if self.page.has_next() else None,\n 'previous': self.page.previous_page_number() if self.page.has_previous() else None,\n 'results': data,\n })\n\n\nclass SmallListPagination(PageNumberPagination):\n page_size = 10\n\n def get_paginated_response(self, data):\n return Response({\n 'count': self.page.paginator.count,\n 'next': self.page.next_page_number() if self.page.has_next() else None,\n 'previous': self.page.previous_page_number() if self.page.has_previous() else None,\n 'results': data,\n })\n" }, { "alpha_fraction": 0.576285719871521, "alphanum_fraction": 0.597428560256958, "avg_line_length": 37.46154022216797, "blob_id": "75bf1c705693957325c27a7eac35729f1ee4a207", "content_id": "bf541360378326002b1b041d1cc4527c8fd214db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3534, "license_type": "no_license", "max_line_length": 85, "num_lines": 91, "path": "/apps/brand/tests/test_views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from collections import OrderedDict\n\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.exceptions import ErrorDetail\nfrom rest_framework.test import APITestCase\n\nfrom apps.brand.models import Brand\n\n\nclass TestBrandListAPIView(APITestCase):\n def setUp(self) -> None:\n Brand.objects.create(\n id=1,\n title=\"brand1\", logo='brand_logo1.img', description='brand1 description',\n address='brand1 address', link='http://localhost:8000'\n )\n Brand.objects.create(\n id=2,\n title=\"brand2\", logo='brand_logo2.img', description='brand2 description',\n address='brand2 address', link='http://localhost:8000'\n )\n self.url = reverse('v1:brand_list')\n\n def test_get_brand_list(self):\n response = self.client.get(self.url)\n expected_data = {\n 'count': 2, 'next': None, 'previous': None,\n 'results': [\n OrderedDict([\n ('id', 1), ('logo', 'http://testserver/media/brand_logo1.img')\n ]),\n OrderedDict([\n ('id', 2), ('logo', 'http://testserver/media/brand_logo2.img')\n ])]\n }\n self.assertEqual(response.data, expected_data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_get_data_if_model_is_empty(self):\n Brand.objects.all().delete()\n response = self.client.get(self.url)\n expected_data = {'count': 0, 'next': None, 'previous': None, 'results': []}\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, expected_data)\n\n\nclass TestBrandRetrieveAPIView(APITestCase):\n\n def setUp(self) -> None:\n Brand.objects.create(\n id=1,\n title=\"brand1\", logo='brand_logo1.img', description='brand1 description',\n address='brand1 address', link='http://localhost:8000'\n )\n Brand.objects.create(\n id=2,\n title=\"brand2\", logo='brand_logo2.img', description='brand2 description',\n address='brand2 address', link='http://localhost:8000'\n )\n\n def test_get_brand_detail(self):\n url = reverse('v1:brand_detail', kwargs={'id': 1})\n response = self.client.get(url)\n expected_data = {\n 'title': 'brand1', 'description': 'brand1 description',\n 'address': 'brand1 address', 'link': 'http://localhost:8000',\n 'images': [],\n }\n self.assertEqual(response.data, expected_data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_get_brand_data_if_model_is_empty(self):\n Brand.objects.all().delete()\n url = reverse('v1:brand_detail', kwargs={'id': 100})\n response = self.client.get(url)\n expected_data = {\n 'detail': ErrorDetail(string='Страница не найдена.', code='not_found'),\n }\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n self.assertEqual(response.data, expected_data)\n\n def test_get_brand_data_if_incorrect_key(self):\n url = reverse('v1:brand_detail', kwargs={'id': 10})\n response = self.client.get(url)\n expected_data = {\n 'detail': ErrorDetail(string='Страница не найдена.', code='not_found'),\n }\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n self.assertEqual(response.data, expected_data)\n" }, { "alpha_fraction": 0.5396825671195984, "alphanum_fraction": 0.6122449040412903, "avg_line_length": 23.5, "blob_id": "e68614aa3166c9319eb8d6719e9e09281a8f9fc6", "content_id": "4e8e6982341a0fb4403d63480024e3460cd9d36c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 92, "num_lines": 18, "path": "/apps/account/migrations/0005_user_is_old_phone_confirmed.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-07 07:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0004_auto_20210402_1044'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='is_old_phone_confirmed',\n field=models.BooleanField(default=False, verbose_name='is old phone confirmed'),\n ),\n ]\n" }, { "alpha_fraction": 0.6788235306739807, "alphanum_fraction": 0.6941176652908325, "avg_line_length": 28.310344696044922, "blob_id": "2ed89c29c89cd2b86170c5f39c38b680ff099d22", "content_id": "f531ca950325d0a6624088892ac7ad4b889452ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/apps/setting/tests/test_middleware.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom apps.setting.tests.factories import SettingFactory\n\n\nclass SettingMiddlewareTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.admin_url = reverse('admin:index')\n cls.default_url = reverse('v1:brand_list')\n SettingFactory()\n\n def setUp(self) -> None:\n self.client = APIClient()\n\n def test_success_get_admin_page_302(self):\n response = self.client.get(self.admin_url)\n\n self.assertEqual(status.HTTP_302_FOUND, response.status_code)\n\n def test_fail_get_non_admin_page_503(self):\n response = self.client.get(self.default_url)\n self.assertEqual(\n status.HTTP_503_SERVICE_UNAVAILABLE, response.status_code\n )\n" }, { "alpha_fraction": 0.5680119395256042, "alphanum_fraction": 0.6158445477485657, "avg_line_length": 26.875, "blob_id": "dd305d8cab57c78dcf3cd43db0292cf5f30aca21", "content_id": "acca79e401759ba86f510068b633c1c270021744", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 102, "num_lines": 24, "path": "/apps/info/migrations/0009_auto_20210506_1458.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-06 08:58\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0008_auto_20210428_1228'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='promotionandnews',\n name='created_at',\n field=models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата публикации'),\n ),\n migrations.AlterField(\n model_name='promotionandnews',\n name='is_active',\n field=models.BooleanField(default=True, verbose_name='Активный(Вкл/Выкл)'),\n ),\n ]\n" }, { "alpha_fraction": 0.5719087719917297, "alphanum_fraction": 0.5745497941970825, "avg_line_length": 29.814815521240234, "blob_id": "7d3db019b5eff64e09d3358d026d64e079ae4802", "content_id": "d78b29b586a8947148d2168d0f9cf8b7e388cca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4334, "license_type": "no_license", "max_line_length": 79, "num_lines": 135, "path": "/apps/brand/admin.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.forms.models import BaseInlineFormSet\n\nfrom adminsortable2.admin import SortableAdminMixin\nfrom django_2gis_maps.admin import DoubleGisAdmin\n\nfrom apps.brand.models import (\n Brand, BrandImage, Filial, FilialImage, FilialPhone, WorkTime\n)\nfrom apps.brand.service import WorkDayService\n\n\nclass ImageInlineFormSet(BaseInlineFormSet):\n \"\"\"\n This formset class is for check main image count\n max count of main image is equal to 1\n \"\"\"\n def clean(self):\n super(ImageInlineFormSet, self).clean()\n main_photo_count = 0\n for form in self.forms:\n is_main_image = (\n form.cleaned_data and not form.cleaned_data.get('DELETE') and\n form.cleaned_data['is_main']\n )\n\n if is_main_image:\n main_photo_count += 1\n\n if main_photo_count > 1 and form.cleaned_data['is_main']:\n form.add_error(\n 'is_main',\n 'Допускается только одно изображение, как основное'\n )\n\n if self.forms and not main_photo_count:\n self.forms[0].add_error(\n 'is_main',\n 'Хотя бы одно изображение должно быть, как основное'\n )\n\n\nclass NumberInlineFormSet(BaseInlineFormSet):\n \"\"\"\n This formset class is for check number\n \"\"\"\n def clean(self):\n super(NumberInlineFormSet, self).clean()\n for form in self.forms:\n is_valid_number_object = (\n form.cleaned_data and not form.cleaned_data.get('DELETE') and (\n form.cleaned_data['is_phone'] or\n form.cleaned_data['is_whatsapp']\n )\n )\n\n if not is_valid_number_object:\n form.add_error(\n 'is_phone',\n 'У номера должна быть включена хотя бы одна функция'\n )\n form.add_error(\n 'is_whatsapp',\n 'У номера должна быть включена хотя бы одна функция'\n )\n\n\nclass WorkTimeInline(admin.TabularInline):\n model = WorkTime\n can_delete = False\n fields = ['day', 'start_work', 'end_work']\n readonly_fields = ['day']\n\n def has_add_permission(self, request, obj=None):\n return False\n\n\nclass BrandImageAdmin(admin.TabularInline):\n model = BrandImage\n extra = 0\n\n\[email protected](Brand)\nclass BrandAdmin(SortableAdminMixin, admin.ModelAdmin):\n inlines = (BrandImageAdmin,)\n list_display = ('position', 'title', 'address', 'link',)\n list_display_links = ['title']\n search_fields = ['title']\n\n\nclass FilialImageAdmin(admin.TabularInline):\n model = FilialImage\n extra = 0\n formset = ImageInlineFormSet\n\n\nclass FilialPhoneAdmin(admin.TabularInline):\n model = FilialPhone\n extra = 0\n formset = NumberInlineFormSet\n\n\[email protected](Filial)\nclass FilialAdmin(SortableAdminMixin, DoubleGisAdmin):\n inlines = (FilialImageAdmin, FilialPhoneAdmin, WorkTimeInline)\n list_display = ('position', 'title', 'address',)\n list_display_links = ['title']\n search_fields = ['title']\n\n def get_inline_instances(self, request, obj=None):\n inline_instances = []\n try:\n work_time_obj = obj.works_time.all()\n if work_time_obj:\n pass\n else:\n WorkDayService.create_weekday(obj)\n\n except Exception:\n pass\n\n for inline_class in self.inlines:\n inline = inline_class(self.model, self.admin_site)\n if request:\n inline_has_add_permission = inline._has_add_permission(request,\n obj)\n if not (inline.has_view_or_change_permission(request, obj) or\n inline_has_add_permission or\n inline.has_delete_permission(request, obj)):\n continue\n if not inline_has_add_permission:\n inline.max_num = 0\n inline_instances.append(inline)\n\n return inline_instances\n\n\n\n\n\n" }, { "alpha_fraction": 0.4879518151283264, "alphanum_fraction": 0.5843373537063599, "avg_line_length": 18.52941131591797, "blob_id": "5df86a9c04feecbd43f77a21df231d5ad9e465b8", "content_id": "c5223d0e6521a17775d4b733385898eea448a5e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/apps/brand/migrations/0003_remove_filial_description.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-03-30 08:10\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0002_auto_20210329_2332'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='filial',\n name='description',\n ),\n ]\n" }, { "alpha_fraction": 0.5423076748847961, "alphanum_fraction": 0.607692301273346, "avg_line_length": 27.88888931274414, "blob_id": "91b2fb228482c787d2d744a5e424cbf2645f043c", "content_id": "9d9e4d8ca326184b14179745805c4d9cae6a2cfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 186, "num_lines": 18, "path": "/apps/check/migrations/0006_auto_20210504_1222.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-04 06:22\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('check', '0005_auto_20210503_1341'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='check',\n name='status',\n field=models.CharField(choices=[('accrued', 'Начислено'), ('withdrawn', 'Снято'), ('accrued_and_withdrawn', 'Начислено и снято')], max_length=25, verbose_name='Статус чека'),\n ),\n ]\n" }, { "alpha_fraction": 0.6377151608467102, "alphanum_fraction": 0.6498435139656067, "avg_line_length": 33.08000183105469, "blob_id": "26fc2e648d9445d7dbeb38f3d1e3c0bed345ed48", "content_id": "facfe9c143658297ab0effb9b813a94429e9e79d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2808, "license_type": "no_license", "max_line_length": 80, "num_lines": 75, "path": "/apps/check/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom apps.account.models import User\nfrom apps.brand.models import Filial\nfrom core.constants import CHECK_TYPE\n\n\nclass Check(models.Model):\n \"\"\"\n Model to save all checks from 1C\n \"\"\"\n unique_1c_check_code = models.CharField(\n max_length=255, unique=True, verbose_name='Уникальный 1C код чека'\n )\n money_paid = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Оплачено деньгами'\n )\n bonus_paid = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Оплачено бонусами'\n )\n total_paid = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Сумма оплаты'\n )\n accrued_point = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Начислено бонусов'\n )\n accrued_point_date = models.DateTimeField(\n null=True, blank=True, verbose_name='Дата начисления'\n )\n withdrawn_point = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Снято бонусов (Возврат)'\n )\n withdrawn_point_date = models.DateTimeField(\n null=True, blank=True, verbose_name='Дата возврата'\n )\n is_active = models.BooleanField(\n default=True, verbose_name='Активность чека'\n )\n user = models.ForeignKey(\n to=User, on_delete=models.CASCADE, related_name='checks',\n verbose_name='Пользователь'\n )\n filial = models.ForeignKey(\n to=Filial, null=True, on_delete=models.SET_NULL, related_name='checks',\n verbose_name='Филиал'\n )\n user_1c_code = models.CharField(\n max_length=255, null=True, verbose_name='Уникальный 1C код пользователя'\n )\n filial_1c_code = models.CharField(\n max_length=255, null=True, verbose_name='Уникальный 1C код филиала'\n )\n status = models.CharField(\n choices=CHECK_TYPE, max_length=25, verbose_name='Статус чека',\n )\n due_date = models.DateTimeField(\n null=True, blank=True, verbose_name='Дата оплаты долга'\n )\n is_on_credit = models.BooleanField(default=False, verbose_name='В долг')\n balance_owed = models.DecimalField(\n null=True, blank=True,\n max_digits=8, decimal_places=2, verbose_name='Остаток долга'\n )\n\n def __str__(self):\n return f'Чек №{self.unique_1c_check_code}'\n\n class Meta:\n verbose_name = 'Чек'\n verbose_name_plural = 'Чеки'\n" }, { "alpha_fraction": 0.7191358208656311, "alphanum_fraction": 0.7191358208656311, "avg_line_length": 26, "blob_id": "d0bb4b93e716884a759efc295b4859bb1ce9f559", "content_id": "73d6fb51173f70f1da4f6a3b5219c157d2c5d2b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/apps/brand/custom_openapi.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg import openapi\n\nlat_param = openapi.Parameter(\n 'lat', openapi.IN_QUERY,\n description=\"Query param lat\", type=openapi.TYPE_NUMBER\n)\nlong_param = openapi.Parameter(\n 'long', openapi.IN_QUERY,\n description=\"Query param long\", type=openapi.TYPE_NUMBER\n)\n\nfilial_extra_params = [lat_param, long_param]\n" }, { "alpha_fraction": 0.5322195887565613, "alphanum_fraction": 0.6085919141769409, "avg_line_length": 22.27777862548828, "blob_id": "6d5640475ac7a71b681650f1e22ef882433685ba", "content_id": "e133f7a796c521e066e2cd19b3e0f97c4d1c4854", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "no_license", "max_line_length": 71, "num_lines": 18, "path": "/apps/info/migrations/0005_auto_20210408_1140.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-08 05:40\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0004_auto_20210406_1501'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='promotionandnews',\n name='created_at',\n field=models.DateTimeField(verbose_name='Дата публикации'),\n ),\n ]\n" }, { "alpha_fraction": 0.6288336515426636, "alphanum_fraction": 0.6339825391769409, "avg_line_length": 28.97986602783203, "blob_id": "ac4f32260fbbc0144696b0c7ee0053d11243ab3a", "content_id": "3d08082623f96bae286767d0e2f950b170726bf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4875, "license_type": "no_license", "max_line_length": 78, "num_lines": 149, "path": "/apps/brand/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.forms import ValidationError\n\nfrom ckeditor_uploader.fields import RichTextUploadingField\nfrom django_2gis_maps import fields as map_fields\n\nfrom core.utils import generate_filename\nfrom core.constants import WORK_DAYS\n\n\nclass Brand(models.Model):\n position = models.PositiveIntegerField(\n default=0, blank=False, null=False,\n verbose_name='№',\n )\n title = models.CharField(max_length=255, verbose_name='Название')\n logo = models.ImageField(upload_to=generate_filename, verbose_name='Лого')\n description = RichTextUploadingField(\n null=True, blank=True, verbose_name='Описание'\n )\n address = models.CharField(\n max_length=100, blank=True, null=True, verbose_name='Адрес'\n )\n link = models.URLField(null=True, blank=True, verbose_name='Ссылка')\n\n def __str__(self):\n return self.title\n\n class Meta:\n ordering = ['position']\n verbose_name = 'Бренд'\n verbose_name_plural = 'Бренды'\n\n\nclass BrandImage(models.Model):\n brand = models.ForeignKey(\n to='Brand', on_delete=models.CASCADE, related_name='images',\n verbose_name='Бренд'\n )\n image = models.ImageField(\n upload_to=generate_filename, verbose_name='Изображение',\n )\n\n def __str__(self):\n return f'Image of {self.brand.title} brand'\n\n class Meta:\n verbose_name = 'Изображение бренда'\n verbose_name_plural = 'Изображения бренда'\n\n\nclass Filial(models.Model):\n position = models.PositiveIntegerField(\n default=0, blank=False, null=False,\n verbose_name='№',\n )\n title = models.CharField(max_length=255, verbose_name='Название')\n address = map_fields.AddressField(max_length=200, verbose_name='Адрес')\n geolocation = map_fields.GeoLocationField(verbose_name='Геолокация')\n filial_1c_code = models.CharField(\n max_length=255, unique=True,\n verbose_name='Уникальный 1C код филиала'\n )\n\n def __str__(self):\n return self.title\n\n class Meta:\n ordering = ['position']\n verbose_name = 'Филиал'\n verbose_name_plural = 'Филиалы'\n\n\nclass FilialImage(models.Model):\n filial = models.ForeignKey(\n to='Filial', on_delete=models.CASCADE, related_name='images',\n verbose_name='Филиал'\n )\n image = models.ImageField(\n upload_to=generate_filename, verbose_name='Изображение'\n )\n is_main = models.BooleanField(default=False, verbose_name='Основная?')\n\n def __str__(self):\n return f'Image of {self.filial.title} filial'\n\n class Meta:\n verbose_name = 'Изображение филиала'\n verbose_name_plural = 'Изображения филиала'\n\n\nclass FilialPhone(models.Model):\n filial = models.ForeignKey(\n to='Filial', on_delete=models.CASCADE, related_name='phone_numbers',\n verbose_name='Филиал'\n )\n phone = models.CharField(max_length=255, verbose_name='Номер телефона')\n is_phone = models.BooleanField(\n default=True, verbose_name='Номер телефона?'\n )\n is_whatsapp = models.BooleanField(\n default=True, verbose_name='Номер Whatsapp?'\n )\n\n def __str__(self):\n return f'Phone of {self.filial.title} filial'\n\n class Meta:\n verbose_name = 'Номер филиала'\n verbose_name_plural = 'Номера филиала'\n\n\nclass WorkTime(models.Model):\n day = models.SmallIntegerField(\n choices=WORK_DAYS, verbose_name='День недели'\n )\n start_work = models.TimeField(\n verbose_name='Начало рабочего времени', null=True, blank=True\n )\n end_work = models.TimeField(\n verbose_name='Конец рабочего времени', null=True, blank=True\n )\n filial = models.ForeignKey(\n to=Filial, on_delete=models.CASCADE, related_name='works_time',\n verbose_name='Филиал'\n )\n\n class Meta:\n ordering = ['day']\n unique_together = ['day', 'filial']\n verbose_name = 'Рабочий день'\n verbose_name_plural = 'Рабочие дни'\n\n def __str__(self):\n return f'{str(self.filial)}, {self.day}'\n\n def clean(self):\n text = ('Нельзя заполнить только время '\n 'конца или начала, рабочего времени')\n if (\n self.start_work is None\n and self.end_work is not None\n ):\n raise ValidationError(text)\n elif (\n self.start_work is not None\n and self.end_work is None\n ):\n raise ValidationError(text)\n" }, { "alpha_fraction": 0.5649241209030151, "alphanum_fraction": 0.5969645977020264, "avg_line_length": 31.054054260253906, "blob_id": "f74757dbacda173b4fb7445da81e582cac4946ca", "content_id": "5847141bda0fdc566b9ab08a62b8f7ee0c27c7b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 118, "num_lines": 37, "path": "/apps/brand/migrations/0005_auto_20210405_1740.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-05 11:40\n\nimport ckeditor_uploader.fields\nimport core.utils\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0004_auto_20210401_1321'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='brand',\n name='address',\n field=models.CharField(blank=True, max_length=100, null=True, verbose_name='Адрес'),\n ),\n migrations.AlterField(\n model_name='brand',\n name='description',\n field=ckeditor_uploader.fields.RichTextUploadingField(blank=True, null=True, verbose_name='Описание'),\n ),\n migrations.AlterField(\n model_name='brand',\n name='logo',\n field=models.ImageField(default='logo.jpeg', upload_to=core.utils.generate_filename, verbose_name='Лого'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='brand',\n name='title',\n field=models.CharField(default='title', max_length=255, verbose_name='Название'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5413534045219421, "alphanum_fraction": 0.5744360685348511, "avg_line_length": 23.629629135131836, "blob_id": "4d6c4f8594c198e430d4af3eee27720eba829d8b", "content_id": "eb5847f77cb7e98082f3a69251ea792e8033681b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 86, "num_lines": 27, "path": "/apps/brand/migrations/0004_auto_20210401_1321.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-01 07:21\n\nfrom django.db import migrations\nimport django_2gis_maps.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0003_remove_filial_description'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='brandimage',\n name='is_main',\n ),\n migrations.RemoveField(\n model_name='filial',\n name='link',\n ),\n migrations.AlterField(\n model_name='filial',\n name='geolocation',\n field=django_2gis_maps.fields.GeoLocationField(verbose_name='Геолокация'),\n ),\n ]\n" }, { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7166666388511658, "avg_line_length": 19, "blob_id": "0647e384651f718f058762915d938ebd5a219c2b", "content_id": "9f341e9007966aec5ebfd5214af6fd46f46e54f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/apps/info/apps.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass InfoConfig(AppConfig):\n name = 'apps.info'\n verbose_name = 'Информация'\n" }, { "alpha_fraction": 0.6531260013580322, "alphanum_fraction": 0.6658203601837158, "avg_line_length": 31.153060913085938, "blob_id": "f8dfb4c45af1ddb38de33e335de17fc0873bb9fc", "content_id": "997c3abb2058423dec472382587039d81cccf19b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3357, "license_type": "no_license", "max_line_length": 78, "num_lines": 98, "path": "/apps/integration/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg.utils import swagger_auto_schema\n\nfrom rest_framework import generics, status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom apps.check.models import Check\nfrom apps.integration.serializers import (\n Auth1cSerializer, Get1cUserSerializer, CheckSerializer,\n Login1cAPIViewResponseSerializer, UpdateCheckSerializer,\n)\nfrom apps.integration.service import User1cAuthService, CreateCheckService\nfrom apps.check.service import CheckNotificationService\n\n\nclass Auth1cAPIView(generics.GenericAPIView):\n \"\"\" Эндпоинт для login 1C пользователя \"\"\"\n serializer_class = Auth1cSerializer\n\n @swagger_auto_schema(\n responses={\n 200: Login1cAPIViewResponseSerializer(),\n 400: \"It will return error type\",\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n return User1cAuthService.get_response(serializer)\n\n\nclass GetUserAPIView(generics.GenericAPIView):\n \"\"\" Эндпоинт для получения unique_1C_ID пользователя по QR коду \"\"\"\n serializer_class = Get1cUserSerializer\n permission_classes = (IsAuthenticated,)\n\n @swagger_auto_schema(\n responses={\n 400: \"Устарел QR код пользователя\",\n 404: \"Пользователь не найден\",\n }\n )\n def get(self, request, *args, **kwargs):\n user = CreateCheckService.get_user_by_qr_code(kwargs.get('qr_code'))\n if not user:\n return Response(\n {'message': 'Пользователь не найден'},\n status=status.HTTP_404_NOT_FOUND\n )\n\n return CreateCheckService.response_user_1c_code(\n self.serializer_class(user), user\n )\n\n\nclass CreateCheckAPIView(generics.CreateAPIView):\n \"\"\" Эндпоинт для создание чека \"\"\"\n serializer_class = CheckSerializer\n permission_classes = (IsAuthenticated,)\n\n @swagger_auto_schema(\n responses={\n 200: CheckSerializer(),\n 400: 'Ошибка при валидации',\n }\n )\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\n def perform_create(self, serializer):\n user, filial = CreateCheckService.get_user_and_filial_from_serializer(\n serializer.validated_data\n )\n\n serializer.validated_data['user'] = user\n serializer.validated_data['filial'] = filial\n\n check = serializer.save()\n CheckNotificationService.send_notification(check, user)\n\n\nclass UpdateCheckAPIView(generics.UpdateAPIView):\n \"\"\" Эндпоинт для обновления чека \"\"\"\n http_method_names = ('patch',)\n serializer_class = UpdateCheckSerializer\n permission_classes = (IsAuthenticated,)\n queryset = Check.objects.all()\n lookup_field = 'unique_1c_check_code'\n\n @swagger_auto_schema(\n responses={\n 200: UpdateCheckSerializer(),\n 404: '\"detail\": \"Страница не найдена.\"',\n }\n )\n def patch(self, request, *args, **kwargs):\n return self.partial_update(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.5615514516830444, "alphanum_fraction": 0.6188870072364807, "avg_line_length": 31.94444465637207, "blob_id": "86baaa06f27444c99d66e318ed4ef1b5e417c703", "content_id": "1ddc5118692a1c40283c43aed71636a776fe6771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 239, "num_lines": 18, "path": "/apps/notifications/migrations/0004_auto_20210504_1810.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-04 12:10\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('notifications', '0003_auto_20210428_1419'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='notification',\n name='notice_type',\n field=models.CharField(choices=[('accrued', 'Начислено бонусов'), ('withdrawn', 'Снято бонусов'), ('accrued_and_withdrawn', 'Начислено и снято'), ('promotion', 'Акции'), ('news', 'Новости')], max_length=25, verbose_name='Тип'),\n ),\n ]\n" }, { "alpha_fraction": 0.6649694442749023, "alphanum_fraction": 0.6700611114501953, "avg_line_length": 33.456138610839844, "blob_id": "7d40ae8786f68c6e5a8ed280ca3fd0ee25a5ce66", "content_id": "5f5f0522a538a503e244ccfddf63703c945f57fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1975, "license_type": "no_license", "max_line_length": 82, "num_lines": 57, "path": "/core/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include, re_path\n\nfrom drf_yasg import openapi\nfrom drf_yasg.views import get_schema_view\n\nadmin.site.site_header = \"Adeliya\"\nadmin.site.site_title = \"Adeliya\"\nadmin.site.index_title = \"Админ-панель Adeliya\"\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Adeliya API\",\n default_version='v1',\n description=\"Adeliya API description\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n contact=openapi.Contact(email=\"[email protected]\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(settings.API_PERMISSION,),\n)\n\nv1_api = ([\n path('account/', include('apps.account.urls')),\n path('brand/', include('apps.brand.urls')),\n path('info/', include('apps.info.urls')),\n path('check/', include('apps.check.urls')),\n path('notification/', include('apps.notifications.urls')),\n path('setting/', include('apps.setting.urls')),\n path('1c/', include('apps.integration.urls'))\n], 'v1')\n\nurlpatterns = [\n path('jet/', include('jet.urls', 'jet')),\n path('admin/', admin.site.urls),\n path('ckeditor/', include('ckeditor_uploader.urls')),\n\n url(r'^docs(?P<format>\\.json|\\.yaml)$',\n schema_view.without_ui(cache_timeout=0), name='schema-json'),\n url(r'^docs/$', schema_view.with_ui('swagger', cache_timeout=0),\n name='schema-swagger-ui'),\n url(r'^redocs/$', schema_view.with_ui('redoc', cache_timeout=0),\n name='schema-redoc'),\n\n re_path(r'api/v1/', include(v1_api, namespace='v1')),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n import debug_toolbar\n urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]\n" }, { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.6452991366386414, "avg_line_length": 23.63157844543457, "blob_id": "c6b26ec9a1b2ace313ddb631b26d04f22d4c0ff5", "content_id": "5dba98581f950f991ecf468bcbec3dfca45eea59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 479, "license_type": "no_license", "max_line_length": 95, "num_lines": 19, "path": "/apps/info/migrations/0008_auto_20210428_1228.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-28 06:28\n\nimport ckeditor_uploader.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0007_banner_description'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='promotionandnews',\n name='description',\n field=ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Текст статьи'),\n ),\n ]\n" }, { "alpha_fraction": 0.6711214184761047, "alphanum_fraction": 0.7024985551834106, "avg_line_length": 28.169490814208984, "blob_id": "ab7a159e80e4e830e5d4ff4e92f9397aead64b66", "content_id": "2a9908ded94c11eff220b4e2fbab1d7700b08de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 75, "num_lines": 59, "path": "/apps/brand/tests/factories.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from random import choice\n\nimport factory\n\nfrom apps.brand.models import (\n Brand, BrandImage,\n Filial, FilialImage, FilialPhone,\n)\n\n\nclass BrandFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Brand\n\n title = factory.Faker('company')\n logo = factory.django.ImageField(width=1024, height=768)\n description = factory.Faker('text')\n address = factory.Faker('address')\n link = factory.Faker('url')\n\n\nclass BrandImageFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = BrandImage\n\n brand = None\n image = factory.django.ImageField(width=1024, height=768)\n\n\nclass FilialFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Filial\n\n position = factory.Sequence(lambda x: '%d' % x)\n title = factory.Faker('name')\n address = factory.Faker('address')\n geolocation = \"42.87962197359586,74.60025385022163\"\n start_work = factory.Faker('time')\n end_work = factory.Faker('time')\n is_around_the_clock = factory.Sequence(lambda x: choice([True, False]))\n filial_1c_code = factory.Faker('random_number')\n\n\nclass FilialImageFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = FilialImage\n\n filial = factory.SubFactory(FilialFactory)\n image = factory.django.ImageField(width=1024, height=768)\n is_main = factory.Sequence(lambda x: choice([True, False]))\n\n\nclass FilialPhoneFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = FilialPhone\n filial = factory.SubFactory(FilialFactory)\n phone = factory.Faker('phone_number')\n is_phone = factory.Sequence(lambda x: choice([True, False]))\n is_whatsapp = factory.Sequence(lambda x: choice([True, False]))\n" }, { "alpha_fraction": 0.6426356434822083, "alphanum_fraction": 0.6776486039161682, "avg_line_length": 43.869564056396484, "blob_id": "17f2b8127c8089726177e85c5b52024b23452f0d", "content_id": "7a997f59143e754e118c40611bf6de7d63677db9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15939, "license_type": "no_license", "max_line_length": 118, "num_lines": 345, "path": "/apps/account/tests/test_views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import json\nfrom unittest import mock\n\nfrom django.test import TestCase, Client\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\nfrom apps.account.service import UserAuthService, ChangeOldPhoneService\nfrom apps.account.tests.factories import UserFactory, CityFactory\nfrom apps.account.tests.mymock import (\n SuccessSmsNikitaResponse, SuccessSmsNikitaInvalidStatusResponse,\n failure_compare_confirmation_time, SuccessChangePhone,\n)\nfrom apps.account.utils import generate_photo_file\nfrom core.constants import MALE\n\n\nclass AuthorizedTestMixin:\n def test_unauthorized_on_401(self):\n client = APIClient()\n response = client.get(self.url)\n expected_data = {'detail': 'Учетные данные не были предоставлены.'}\n self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n def test_get_invalid_token_on_401(self):\n user = UserFactory()\n token = Token.objects.create(user=user)\n client = APIClient()\n client.credentials(HTTP_AUTHORIZATION='Token ' + token.key + 'a')\n response = client.get(self.url)\n expected_data = {'detail': 'Недопустимый токен.'}\n self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n\nclass AuthAPIViewTest(TestCase):\n @classmethod\n def setUpTestData(cls) -> None:\n UserFactory(phone='+996553000117', is_registration_finish=True)\n UserFactory(\n phone='+996553000118', is_active=False, is_registration_finish=True,\n )\n cls.client = Client()\n cls.auth_url = reverse('v1:auth')\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaResponse())\n def test_success_status_on_201(self, mocked):\n phone_data = {'phone': '+996999111222'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'message': 'User создан! Сообщение отправлено'}\n self.assertEqual(status.HTTP_201_CREATED, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaResponse())\n def test_success_status_on_200(self, mocked):\n phone_data = {'phone': '+996553000117'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'message': 'Сообщение отправлено'}\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n def test_is_not_active_user_status_on_400(self):\n phone_data = {'phone': '+996553000118'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'phone': ['Этот номер не активен.']}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaInvalidStatusResponse())\n def test_sms_nikita_with_invalid_status_on_400(self, mocked):\n phone_data = {'phone': '+996999111222'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'message': 'Не удалось отправить сообщение. Попробуйте позже.'}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n @mock.patch.object(UserAuthService, 'compare_confirmation_time', return_value=failure_compare_confirmation_time())\n def test_failure_too_many_requests_on_429(self, mocked):\n phone_data = {'phone': '+996999111222'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'message': 'Вы слишком часто отправляете сообщение.'}\n self.assertEqual(status.HTTP_429_TOO_MANY_REQUESTS, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n def test_failure_phone_validate_on_400(self):\n phone_data = {'phone': '+996999111222a'}\n response = self.client.post(self.auth_url, data=phone_data)\n expected_data = {'phone': ['phone is not valid!']}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n\nclass LoginConfirmAPIViewTest(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n UserFactory(phone='+996999111222', is_active=True, confirmation_code='123456')\n UserFactory(phone='+996701626702', is_active=False, confirmation_code='123456')\n UserFactory(phone='+996701626700', confirmation_code='123456',)\n cls.url = reverse('v1:login-confirm')\n\n def test_success_login_confirmation_with_profile_completed_on_200(self):\n data = {'phone': '+996701626700', 'confirmation_code': '123456'}\n response = self.client.post(self.url, data=data)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual(True, response.data.get('is_profile_completed'))\n\n def test_success_login_confirmation_without_profile_completed_on_200(self):\n data = {'phone': '+996999111222', 'confirmation_code': '123456'}\n response = self.client.post(self.url, data=data)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n def test_failure_not_valid_confirmation_code_on_403(self):\n data = {'phone': '+996999111222', 'confirmation_code': '123455'}\n expected_data = {'message': 'Неверный код'}\n response = self.client.post(self.url, data=data)\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n def test_is_not_active_user_on_400(self):\n data = {'phone': '+996701626702', 'confirmation_code': '123456'}\n response = self.client.post(self.url, data=data)\n expected_data = {'phone': ['Этот номер не активен.']}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n def test_not_exist_user_on_404(self):\n data = {'phone': '+996701626705', 'confirmation_code': '123456'}\n response = self.client.post(self.url, data=data)\n expected_data = {'detail': 'user not found'}\n self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n def test_failure_phone_validate_on_400(self):\n phone_data = {'phone': '+996999111222a', 'confirmation_code': '123456'}\n response = self.client.post(self.url, data=phone_data)\n expected_data = {'phone': ['phone is not valid!']}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, json.loads(response.content))\n\n\nclass CityListAPIViewTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n CityFactory()\n CityFactory()\n cls.url = reverse('v1:cities')\n cls.client = Client()\n\n def test_city_list_api(self):\n response = self.client.get(self.url)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n\nclass UserRetrieveUpdateAPIViewTest(AuthorizedTestMixin, TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:retrieve-update')\n user = UserFactory()\n cls.token = Token.objects.create(user=user)\n cls.city = user.city\n\n def setUp(self) -> None:\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n def test_get_success_on_200(self):\n response = self.client.get(self.url)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n def test_put_bad_request_on_400(self):\n response = self.client.put(self.url, {})\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n\n def test_put_success_on_200(self):\n data = {\n 'first_name': 'Aman',\n 'last_name': 'Kalmanbetov',\n 'gender': MALE,\n 'birth_date': '1975-05-09',\n 'city': self.city.id,\n }\n response = self.client.put(self.url, data)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual('Aman', response.data.get('first_name'))\n self.assertEqual('Kalmanbetov', response.data.get('last_name'))\n\n def test_patch_success_on_200(self):\n data = {'first_name': 'Amanbek'}\n response = self.client.patch(self.url, data)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual('Amanbek', response.data.get('first_name'))\n\n\nclass UserAvatarRetrieveUpdateAPIViewTest(AuthorizedTestMixin, TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:avatar')\n user = UserFactory()\n cls.token = Token.objects.create(user=user)\n\n def setUp(self) -> None:\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n def test_success_update_avatar_on_200(self):\n data = {'avatar': generate_photo_file()}\n response = self.client.patch(self.url, data)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n\nclass SendSmsToOldPhoneAPIViewTest(AuthorizedTestMixin, TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:send_sms_to_old_phone')\n cls.user = UserFactory()\n cls.token = Token.objects.create(user=cls.user)\n\n def setUp(self) -> None:\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n @mock.patch.object(UserAuthService, 'compare_confirmation_time', return_value=failure_compare_confirmation_time())\n def test_failure_too_many_requests_on_429(self, mocked):\n response = self.client.get(self.url)\n expected_data = {'message': 'Вы слишком часто отправляете сообщение.'}\n self.assertEqual(status.HTTP_429_TOO_MANY_REQUESTS, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaResponse())\n def test_success_status_on_200(self, mocked):\n response = self.client.get(self.url)\n expected_data = {'message': 'Сообщение отправлено'}\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaInvalidStatusResponse())\n def test_sms_nikita_with_invalid_status_on_400(self, mocked):\n response = self.client.get(self.url)\n expected_data = {'message': 'Не удалось отправить сообщение. Попробуйте позже.'}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n\nclass OldPhoneConfirmAPIViewTest(AuthorizedTestMixin, TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:old_phone_confirm')\n\n def setUp(self) -> None:\n self.user = UserFactory(confirmation_code='123456')\n self.token = Token.objects.create(user=self.user)\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n def test_failure_not_valid_confirmation_code_on_403(self):\n data = {'confirmation_code': '123455'}\n expected_data = {'message': 'Неверный код'}\n response = self.client.post(self.url, data=data)\n self.user.refresh_from_db()\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n self.assertEqual(expected_data, response.data)\n self.assertEqual(False, self.user.is_old_phone_confirmed)\n\n def test_success_confirmation_on_200(self):\n data = {'confirmation_code': '123456'}\n response = self.client.post(self.url, data=data)\n expected_data = {\"message\": \"Old phone is confirmed\"}\n self.user.refresh_from_db()\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual(expected_data, response.data)\n self.assertEqual(True, self.user.is_old_phone_confirmed)\n\n\nclass SendSmsToNewPhoneAPIVewTest(TestCase):\n @classmethod\n def setUpTestData(cls) -> None:\n cls.user = UserFactory(phone='+996553000117', is_registration_finish=True)\n cls.url = reverse('v1:change_old_phone')\n cls.token = Token.objects.create(user=cls.user)\n\n def setUp(self) -> None:\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n @mock.patch('requests.post', return_value=SuccessSmsNikitaResponse())\n def test_success_status_on_200(self, mocked):\n phone_data = {'phone': '+996553000119'}\n response = self.client.post(self.url, data=phone_data)\n expected_data = {'message': 'Сообщение отправлено'}\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n @mock.patch('requests.post',\n return_value=SuccessSmsNikitaInvalidStatusResponse())\n def test_sms_nikita_with_invalid_status_on_400(self, mocked):\n phone_data = {'phone': '+996999111222'}\n response = self.client.post(self.url, data=phone_data)\n expected_data = {\n 'message': 'Не удалось отправить сообщение. Попробуйте позже.'}\n self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n def test_checking_for_uniqueness_with_status_on_406(self):\n phone_data = {'phone': '+996553000117'}\n response = self.client.post(self.url, data=phone_data)\n expected_data = {'message': 'Такой номер телефона уже существует'}\n self.assertEqual(status.HTTP_406_NOT_ACCEPTABLE, response.status_code)\n self.assertEqual(expected_data, response.data)\n\n def test_failure_too_many_requests_on_429(self):\n phone_data = {'phone': '+996999111222'}\n response = self.client.post(self.url, phone_data)\n response = self.client.post(self.url, phone_data)\n expected_data = {'message': 'Вы слишком часто отправляете сообщение.'}\n self.assertEqual(status.HTTP_429_TOO_MANY_REQUESTS,\n response.status_code)\n self.assertEqual(expected_data, response.data)\n\n\nclass NewPhoneConfirmAPIViewTest(AuthorizedTestMixin, TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:new_phone_confirm')\n cls.user = UserFactory(confirmation_code='123456')\n cls.token = Token.objects.create(user=cls.user)\n\n def setUp(self) -> None:\n self.client = APIClient()\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n\n def test_failure_not_valid_confirmation_code_on_403(self):\n data = {'confirmation_code': '123455'}\n expected_data = {'message': 'Неверный код'}\n response = self.client.post(self.url, data=data)\n self.user.refresh_from_db()\n self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)\n self.assertEqual(expected_data, response.data)\n self.assertEqual(False, self.user.is_old_phone_confirmed)\n\n \"\"\" Don't forget to added test for ChangePhoneSerializer \"\"\"\n" }, { "alpha_fraction": 0.625693142414093, "alphanum_fraction": 0.6321626901626587, "avg_line_length": 24.761905670166016, "blob_id": "cf989c796dc1d995ab069f29c21f569da99be059", "content_id": "a1fa21d23ba79b0e0bc48ff2ae8ee01058379584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/core/utils.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport uuid\n\nfrom django.utils import timezone\n\n\ndef slugify_camelcase(string: str, sep: str = \"-\") -> str:\n \"\"\"\n Converts camelcase string to lowercase string divided with given\n separator\n\n :param string: string to slugify\n :param sep: separator\n :return: slugified string\n\n With sep='_':\n 'CamelCase' -> 'camel_case'\n \"\"\"\n repl = r\"\\1{}\\2\".format(sep)\n s1 = re.sub(\"(.)([A-Z][a-z]+)\", repl, string)\n\n return re.sub(\"([a-z0-9])([A-Z])\", repl, s1).lower()\n\n\ndef generate_filename(instance, filename: str) -> str:\n \"\"\"\n Generates a filename for a model's instance\n\n :param instance: Django model's instance\n :param filename: filename\n :return: generated filename\n\n Filename consist of slugified model name, current datetime and time\n and uuid\n \"\"\"\n f, ext = os.path.splitext(filename)\n model_name = slugify_camelcase(instance._meta.model.__name__, \"_\")\n strftime = timezone.datetime.now().strftime(\"%Y/%m/%d\")\n hex_ = uuid.uuid4().hex\n\n return f\"{model_name}/{strftime}/{hex_}{ext}\"\n" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.5951219797134399, "avg_line_length": 21.77777862548828, "blob_id": "5b505de4ae4ec6a3c8420dcc97fa8c47f0aae472", "content_id": "c10ee6e6a1a78ab3841ce1d8957f3a31c8ab33ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/apps/account/migrations/0010_auto_20210630_1621.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-06-30 10:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0009_auto_20210527_1151'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='discount',\n field=models.CharField(max_length=20, verbose_name='Скидка'),\n ),\n ]\n" }, { "alpha_fraction": 0.6690349578857422, "alphanum_fraction": 0.6696270108222961, "avg_line_length": 28.120689392089844, "blob_id": "e4133ee2fa47e4acab57b167d9a4e50c05c2e29b", "content_id": "51f7712cf57365f454e10c3afadcbed2aa9004b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1689, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/apps/info/admin.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom solo.admin import SingletonModelAdmin\n\nfrom apps.brand.admin import ImageInlineFormSet\nfrom .models import (\n Banner, ProgramCondition, Contact,\n PromotionAndNews, PromotionAndNewsImage, ContactIcon,\n)\nfrom apps.notifications.tasks import save_notification_and_send_fcm_for_article\n\n\nclass PromotionAndNewsImageInline(admin.StackedInline):\n model = PromotionAndNewsImage\n extra = 0\n formset = ImageInlineFormSet\n\n\[email protected](Banner)\nclass BannerAdmin(SingletonModelAdmin):\n list_display = ('title',)\n\n\[email protected](ProgramCondition)\nclass ProgramConditionAdmin(SingletonModelAdmin):\n list_display = ('title', 'description',)\n\n\[email protected](Contact)\nclass ContactAdmin(admin.ModelAdmin):\n list_display = ('title', 'icon_image', 'link',)\n\n\[email protected](ContactIcon)\nclass ContactIconAdmin(admin.ModelAdmin):\n pass\n\n\[email protected](PromotionAndNews)\nclass PromotionAndNewsAdmin(admin.ModelAdmin):\n list_display = ('title', 'information_type', 'is_active',)\n fields = [\n 'created_at', 'title', 'description',\n 'information_type', 'is_active',\n ]\n inlines = (PromotionAndNewsImageInline,)\n\n def save_model(self, request, obj, form, change):\n is_old = obj.pk # checking for existence in the database\n super().save_model(request, obj, form, change)\n if not is_old:\n if obj.is_active:\n body = {\n 'object_id': obj.id,\n 'title': obj.title,\n 'information_type': obj.information_type,\n }\n save_notification_and_send_fcm_for_article(body, obj)\n" }, { "alpha_fraction": 0.5666892528533936, "alphanum_fraction": 0.5676370859146118, "avg_line_length": 34.16666793823242, "blob_id": "9bacc954633edb7b9cc1819b3b7d25048e719756", "content_id": "9adff3509da8412004bfe1ff3a2b2828c3077c77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7435, "license_type": "no_license", "max_line_length": 79, "num_lines": 210, "path": "/apps/notifications/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import json\nimport datetime\n\nfrom fcm_django.models import FCMDevice\nfrom loguru import logger\n\nfrom core.constants import DUE_DATE_CHECK_MESSAGE, MONTH_NAMES\n\n\nclass SendPushNotification:\n\n @classmethod\n def send_fcm(cls, user, notice_obj, body, badge_count):\n responses, full_notification, data = cls.message_generate(\n user, notice_obj, body, badge_count\n )\n try:\n for response in responses:\n if response.type and response.type == 'android':\n response.send_message(data=data)\n else:\n full_notification['click_action'] = notice_obj.notice_type\n response.send_message(**full_notification)\n\n from apps.notifications.tasks import create_notification_for_db\n create_notification_for_db(notice_obj)\n\n except Exception as e:\n logger.error('Error on sending push notification to fcm service')\n logger.exception(e)\n else:\n logger.success('Success sending push notification')\n\n @classmethod\n def send_fcm_for_debtors(cls, user, notice_obj, body, badge_count):\n responses, full_notification, data = cls.message_generate(\n user, notice_obj, body, badge_count\n )\n data['body'] = body['description']\n full_notification['data'] = data\n try:\n for response in responses:\n if response.type and response.type == 'android':\n response.send_message(data=data)\n else:\n full_notification['click_action'] = notice_obj.notice_type\n response.send_message(**full_notification)\n\n except Exception as e:\n logger.error('Error on sending push notification to fcm service')\n logger.exception(e)\n else:\n logger.success('Success sending push notification')\n\n @staticmethod\n def set_notification_viewed_for_check(request, obj):\n user = request.user\n if user.is_authenticated:\n from apps.notifications.models import Notification\n notices = (\n Notification.objects.filter(\n user=user, linked_check_id=obj.id, is_viewed=False\n )\n )\n notices.update(is_viewed=True)\n\n @staticmethod\n def set_notification_viewed_for_article(request, obj):\n user = request.user\n if user.is_authenticated:\n from apps.notifications.models import Notification\n notice = (\n Notification.objects.filter(\n user=user, linked_article_id=obj.id\n ).first()\n )\n if notice and not notice.is_viewed:\n notice.is_viewed = True\n notice.save(update_fields=['is_viewed'])\n\n @classmethod\n def checking_debtors(cls):\n from apps.check.models import Check\n from apps.notifications.models import Notification\n\n checks = (\n Check.objects.filter(\n is_on_credit=True,\n due_date__date=datetime.datetime.now() + datetime.timedelta(\n days=3)\n ).select_related('user')\n )\n for check in checks:\n body = {\n 'object_id': check.id,\n 'title': str(check.filial),\n 'status': check.status,\n 'accrued_point': check.accrued_point,\n 'withdrawn_point': check.withdrawn_point,\n 'description': DUE_DATE_CHECK_MESSAGE,\n }\n notice_obj = cls.save_notification_for_debtor(check, body)\n badge_count = Notification.objects.filter(\n user=check.user, is_viewed=False\n ).count()\n cls.send_fcm_for_debtors(check.user, notice_obj, body, badge_count)\n\n @staticmethod\n def save_notification_for_debtor(check, body):\n from apps.notifications.models import Notification\n from django.core.serializers.json import DjangoJSONEncoder\n\n notice_obj = Notification.objects.create(\n user=check.user,\n notice_type=check.status,\n linked_check=check,\n body=json.dumps(body, cls=DjangoJSONEncoder),\n is_on_credit=True,\n )\n return notice_obj\n\n @staticmethod\n def message_generate(user, notice_obj, body, badge_count):\n responses = FCMDevice.objects.filter(user=user, active=True)\n data_msg = dict(\n title=notice_obj.NOTIFICATION_TITLE,\n body=notice_obj.get_message,\n click_action=notice_obj.notice_type,\n id=body['object_id'],\n type=notice_obj.notice_type,\n badge_count=badge_count,\n )\n full_notification = {\n 'data': data_msg, 'title': notice_obj.NOTIFICATION_TITLE,\n 'body': notice_obj.get_message,\n 'sound': \"default\",\n }\n return responses, full_notification, data_msg\n\n @classmethod\n def send_notice_for_delete(cls, devices, is_corporate_account) -> None:\n data = dict(\n title='TruckParts',\n body='Вы зашли с другого устройства!',\n click_action='TruckPartsKick',\n id=6699, # not necessarily\n is_kicked=True,\n )\n full_notification = {\n 'data': data, 'title': 'TruckParts',\n 'body': 'Вы зашли с другого устройства!',\n 'sound': \"default\",\n }\n if is_corporate_account:\n device = devices.last()\n cls.send_kick_notice(device, data)\n else:\n for device in devices:\n cls.send_kick_notice(device, data, full_notification)\n\n @staticmethod\n def send_kick_notice(device, data, full_notification=None):\n try:\n if device.type and device.type == 'android':\n device.send_message(data=data)\n else:\n device.send_message(**full_notification)\n except Exception as e:\n logger.error('Error on sending push notification to fcm service')\n logger.exception(e)\n device.delete()\n else:\n logger.success('Success sending push notification')\n device.delete()\n\n\nclass NotificationResponseService:\n @classmethod\n def reformat(cls, notifications):\n notification_list = []\n month_list = []\n\n last_month = None\n last_year = None\n\n if len(notifications) == 0:\n return notification_list\n\n for notification in notifications:\n notification_date = notification['created_at'].split('T')[0]\n year, month, _ = notification_date.split('-')\n\n if last_month == month and last_year == year:\n month_list['notifications'].append(notification)\n else:\n if month_list:\n notification_list.append(month_list)\n month_list = {\n 'month': cls.get_month_name(month), 'year': year,\n 'notifications': [notification]\n }\n last_month, last_year = month, year\n\n notification_list.append(month_list)\n\n return notification_list\n\n @staticmethod\n def get_month_name(month_number):\n return MONTH_NAMES.get(month_number)\n" }, { "alpha_fraction": 0.6960784196853638, "alphanum_fraction": 0.7102396488189697, "avg_line_length": 31.785715103149414, "blob_id": "9478a34f7581053ee5c8d691e3d2cc2a0aa14f0d", "content_id": "dc04a6bbd83171cbe29d40f9801c1b9edc2ca44e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "no_license", "max_line_length": 77, "num_lines": 28, "path": "/apps/check/tests/test_views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\nfrom apps.account.tests.factories import UserFactory\n\n\nclass QRCodeAPIViewTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.url = reverse('v1:qr_code')\n user = UserFactory()\n cls.token = Token.objects.create(user=user)\n\n def setUp(self) -> None:\n self.client = APIClient()\n\n def test_success_get_qr_code_on_200(self):\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)\n response = self.client.get(self.url)\n self.assertEqual(status.HTTP_200_OK, response.status_code)\n\n def test_fail_get_qr_code_on_401(self):\n response = self.client.get(self.url)\n self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code)\n" }, { "alpha_fraction": 0.6861110925674438, "alphanum_fraction": 0.6861110925674438, "avg_line_length": 29, "blob_id": "f58bf7752ef8b85eb872dd8b41a6123c46e8e9a6", "content_id": "f13f3c9204c668a2e6e311a0bea61fae82bf5b44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 65, "num_lines": 12, "path": "/apps/setting/middleware.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from apps.setting.service import ApplicationStatusService\n\n\nclass ApplicationStatusMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n return ApplicationStatusService.check_application_status(\n request, response\n )\n" }, { "alpha_fraction": 0.6832298040390015, "alphanum_fraction": 0.6845607757568359, "avg_line_length": 29.45945930480957, "blob_id": "5897ea8261aa55d8f6cdfc8ee1f2ad0b361385c5", "content_id": "e4c374fe42b09ac5a66c274fbf7dcbf72094870f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2254, "license_type": "no_license", "max_line_length": 79, "num_lines": 74, "path": "/apps/notifications/tasks.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import json\n\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom huey.contrib.djhuey import task, periodic_task, db_task\nfrom huey import crontab\nfrom loguru import logger\n\nfrom apps.notifications.models import Notification\nfrom apps.notifications.service import SendPushNotification\nfrom core.constants import DUE_DATE_CHECK_MESSAGE\n\n\n@task()\ndef save_notification_and_send_fcm_for_article(body, obj):\n from apps.account.models import User\n users_qs = User.objects.filter(is_registration_finish=True, is_active=True)\n for user in users_qs:\n notice_obj = Notification(\n user=user,\n notice_type=body['information_type'],\n linked_article=obj,\n body=json.dumps(body, cls=DjangoJSONEncoder),\n )\n badge_count = Notification.objects.filter(\n user=user, is_viewed=False\n ).count()\n SendPushNotification.send_fcm(user, notice_obj, body, badge_count)\n\n\n@db_task(retries=5)\ndef create_notification_for_db(notice_obj):\n try:\n notice_obj.save()\n except Exception as e:\n logger.error('Didn\\'t created notification')\n logger.exception(e)\n else:\n logger.success('Success create notification')\n\n\n@task()\ndef save_notification_and_send_fcm_for_check(body, user, obj):\n notice_obj = Notification(\n user=user,\n notice_type=body['status'],\n linked_check=obj,\n body=json.dumps(body, cls=DjangoJSONEncoder)\n )\n if obj.is_on_credit:\n body['description'] = DUE_DATE_CHECK_MESSAGE\n notice_obj.is_on_credit = True\n\n else:\n body['description'] = f'{user.first_name}, {notice_obj.get_message}'\n\n notice_obj.body = json.dumps(body, cls=DjangoJSONEncoder)\n badge_count = Notification.objects.filter(\n user=user, is_viewed=False\n ).count()\n SendPushNotification.send_fcm(user, notice_obj, body, badge_count)\n\n\n@periodic_task(crontab(hour='*/24'))\ndef send_notification_for_debtors():\n \"\"\"Everyday sending push notification for debtor\"\"\"\n SendPushNotification.checking_debtors()\n\n\n@task()\ndef send_notice_for_deleted_fcm_device(device, is_corporate_account):\n SendPushNotification.send_notice_for_delete(\n device, is_corporate_account\n )\n" }, { "alpha_fraction": 0.6650185585021973, "alphanum_fraction": 0.6650185585021973, "avg_line_length": 31.360000610351562, "blob_id": "d428664f3bd26526b11bb488c620fdf22f35c1bb", "content_id": "fbfd0d414c770a381fcc1484018703223ca6321a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 809, "license_type": "no_license", "max_line_length": 71, "num_lines": 25, "path": "/apps/check/filters.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import django_filters\n\nfrom apps.check.models import Check\n\n\nclass CheckFilter(django_filters.FilterSet):\n start_date = django_filters.CharFilter(\n field_name='accrued_point_date', method='start_date_filter'\n )\n end_date = django_filters.CharFilter(\n field_name='accrued_point_date', method='end_date_filter'\n )\n\n class Meta:\n model = Check\n fields = ['start_date', 'end_date']\n\n def start_date_filter(self, queryset, name, value):\n if 'end_date' in self.request.GET:\n return queryset.filter(accrued_point_date__date__gte=value)\n return queryset.filter(accrued_point_date__date=value)\n\n def end_date_filter(self, queryset, name, value):\n self.end_date = value\n return queryset.filter(accrued_point_date__date__lte=value)\n" }, { "alpha_fraction": 0.707025408744812, "alphanum_fraction": 0.7100149393081665, "avg_line_length": 38.35293960571289, "blob_id": "50306e1f1a936b759de7a5a5c87b90f484ff44be", "content_id": "689a9c4b571c45187994aac51defbf3513571de3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 95, "num_lines": 17, "path": "/apps/notifications/pagination.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\n\nfrom apps.notifications.service import NotificationResponseService\n\n\nclass LargeListNotificationPagination(PageNumberPagination):\n page_size = 20\n\n def get_paginated_response(self, data):\n reformat_data = NotificationResponseService.reformat(data)\n return Response({\n 'count': self.page.paginator.count,\n 'next': self.page.next_page_number() if self.page.has_next() else None,\n 'previous': self.page.previous_page_number() if self.page.has_previous() else None,\n 'results': reformat_data,\n })\n" }, { "alpha_fraction": 0.6556233763694763, "alphanum_fraction": 0.6586747765541077, "avg_line_length": 26.975608825683594, "blob_id": "f2160834988def49581cdd66ed347e2aa44f9796", "content_id": "abed6690bb264de5795c2f13c6de10ac13424f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2677, "license_type": "no_license", "max_line_length": 79, "num_lines": 82, "path": "/apps/setting/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.db import models\n\nfrom solo.models import SingletonModel\n\n\nclass TimeStampAbstractModel(models.Model):\n\n created_at = models.DateTimeField(\n verbose_name='Создано', auto_now_add=True, null=True\n )\n updated_at = models.DateTimeField(\n verbose_name='Обновлено', auto_now=True, null=True\n )\n\n def __unicode__(self):\n pass\n\n def __str__(self):\n return self.__unicode__()\n\n class Meta:\n abstract = True\n\n\nclass Setting(SingletonModel):\n qr_code_expiration_date = models.DurationField(\n default=datetime.timedelta(minutes=3),\n verbose_name='Срок активности QR кода',\n help_text=' QR код будет недействителен при истечений срока активности'\n )\n is_service_active = models.BooleanField(\n default=True, verbose_name='Статус сервиса',\n help_text='Убрав галочку, вы можете отключить сервис'\n )\n\n def __str__(self):\n return f'Статус сайта: {self.is_service_active}'\n\n class Meta:\n verbose_name = 'Настройка сайта'\n verbose_name_plural = 'Настройки сайта'\n\n\nclass AppVersion(SingletonModel):\n android_version = models.CharField(\n max_length=15, verbose_name='Версия для android приложения',\n )\n android_force_update = models.BooleanField(\n default=False, verbose_name='Принудительное обновление(Вкл/Выкл)',\n )\n ios_build_number = models.PositiveIntegerField(\n verbose_name='Build версия для ios приложения', null=True\n )\n ios_version = models.CharField(\n max_length=15, verbose_name='Версия для ios приложения',\n )\n ios_force_update = models.BooleanField(\n default=False, verbose_name='Принудительное обновление(Вкл/Выкл)',\n )\n\n def __str__(self):\n return f'Android v{self.android_version}, ios v{self.ios_version}'\n\n class Meta:\n verbose_name = 'Версия мобильного приложения'\n verbose_name_plural = 'Версии мобильного приложения'\n\n\nclass HelpPage(SingletonModel):\n title = models.CharField(\n max_length=50, verbose_name=\"Заголовок справки\",\n )\n text = models.TextField(verbose_name=\"Текст справки\")\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = 'Справка'\n verbose_name_plural = 'Справки'\n" }, { "alpha_fraction": 0.5421412587165833, "alphanum_fraction": 0.6150341629981995, "avg_line_length": 23.38888931274414, "blob_id": "4fa9f11128ba4966768df1d1f9bb79c26aecd397", "content_id": "b6f5e35ea1291e2884cee92dc00368ec1e63fc16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 92, "num_lines": 18, "path": "/apps/account/migrations/0008_user_is_corporate_account.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-29 05:00\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0007_auto_20210414_1630'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='is_corporate_account',\n field=models.BooleanField(default=False, verbose_name='Корпоративный аккаунт?'),\n ),\n ]\n" }, { "alpha_fraction": 0.5925893783569336, "alphanum_fraction": 0.6015063524246216, "avg_line_length": 35.43848419189453, "blob_id": "c019f4cb290c2a5657c10a3aef79c36a43e2f89d", "content_id": "b5c21452fee34e5385aea321a158d25048a50746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11997, "license_type": "no_license", "max_line_length": 92, "num_lines": 317, "path": "/apps/account/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import random\nimport re\nimport string\nimport requests\nimport xmltodict\n\nfrom datetime import timedelta, datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\nfrom django.conf import settings\n\nfrom rest_framework import exceptions, status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\nfrom rest_framework import serializers\n\nfrom dicttoxml import dicttoxml\n\nfrom apps.integration.service import User1CNumberChangeService\nfrom apps.notifications.tasks import send_notice_for_deleted_fcm_device\n\n\nUser = get_user_model()\n\n\nclass UserAuthService:\n \"\"\" Service for handling AUTH methods \"\"\"\n\n @classmethod\n def get_response(cls, serializer) -> Response:\n \"\"\"Method для login или создания пользователя и отсылки SMS \"\"\"\n user = serializer.user\n if not cls.compare_confirmation_time(user):\n return Response(\n {'message': 'Вы слишком часто отправляете сообщение.'},\n status=status.HTTP_429_TOO_MANY_REQUESTS\n )\n if not cls.send_confirmation_sms(user):\n return Response(\n {'message': 'Не удалось отправить сообщение. Попробуйте позже.'},\n status=status.HTTP_400_BAD_REQUEST\n )\n if serializer.created:\n return Response(\n {'message': 'User создан! Сообщение отправлено'},\n status=status.HTTP_201_CREATED\n )\n return Response(\n {'message': 'Сообщение отправлено'}, status=status.HTTP_200_OK\n )\n\n @classmethod\n def send_to_old_phone(cls, user: User) -> Response:\n \"\"\"method for send sms to old phone number\"\"\"\n if not cls.compare_confirmation_time(user):\n return Response(\n {'message': 'Вы слишком часто отправляете сообщение.'},\n status=status.HTTP_429_TOO_MANY_REQUESTS\n )\n if not cls.send_confirmation_sms(user):\n return Response(\n {'message': 'Не удалось отправить сообщение. Попробуйте позже.'},\n status=status.HTTP_400_BAD_REQUEST\n )\n return Response(\n {'message': 'Сообщение отправлено'}, status=status.HTTP_200_OK\n )\n\n @staticmethod\n def generate_new_code():\n \"\"\" Method for generating random confirmation code \"\"\"\n code = ''.join(random.choice(string.digits) for i in range(6))\n return code\n\n @staticmethod\n def compare_confirmation_time(user_obj) -> bool:\n \"\"\" Method for checking if 1 minute left from last request \"\"\"\n result = (\n not user_obj.confirmation_date\n or (timezone.now() - user_obj.confirmation_date)\n > timedelta(minutes=1)\n )\n\n return result\n\n @staticmethod\n def check_format_user_phone(phone):\n \"\"\" Method for formation user phone (+ and only digits) \"\"\"\n match = re.match(r'^\\+[0-9]{10,}$', phone)\n if not match:\n raise exceptions.ValidationError('phone is not valid!')\n return phone\n\n @staticmethod\n def get_or_create_user_instance(phone_number):\n \"\"\" Getting or creating user instance \"\"\"\n try:\n user = User.objects.get(phone=phone_number)\n except User.DoesNotExist:\n user = User.objects.create(\n phone=phone_number,\n is_active=True,\n is_registration_finish=False,\n )\n created = not user.is_registration_finish\n\n return user, created\n\n @classmethod\n def set_confirmation_code(cls, user_obj: User) -> str:\n \"\"\" Method for setting confirmation sms code to user \"\"\"\n confirmation_code = cls.generate_new_code()\n if user_obj.phone == '+996553000117' or user_obj.phone == '+996999111222':\n confirmation_code = '123456'\n user_obj.confirmation_code = confirmation_code\n user_obj.confirmation_date = timezone.now()\n user_obj.save(\n update_fields=['confirmation_code', 'confirmation_date'])\n return confirmation_code\n\n @classmethod\n def send_confirmation_sms(cls, user_obj: User) -> bool:\n \"\"\" Method for sending confirmation sms to a new or old user \"\"\"\n confirmation_code = cls.set_confirmation_code(user_obj)\n id_string = '%s%d' % (user_obj.id, datetime.now().timestamp())\n\n data = {\n 'login': settings.NIKITA_LOGIN,\n 'pwd': settings.NIKITA_PASSWORD,\n 'id': id_string,\n 'sender': settings.NIKITA_SENDER,\n 'text': f'Ваш код активации: {confirmation_code}',\n 'phones': [str(user_obj.phone).replace('+', '')],\n 'test': settings.NIKITA_TEST\n }\n page = dicttoxml(data, custom_root='message',\n item_func=lambda x: x[:-1], attr_type=False)\n response = requests.post(\n 'https://smspro.nikita.kg/api/message',\n data=page, headers={'Content-Type': 'application/xml'}\n )\n response_dict = xmltodict.parse(response.text)\n status = response_dict['response']['status']\n return True if status in ('0', '11') else False\n\n\nclass PhoneConfirmationService:\n \"\"\" Service for handling phone confirmation on create or login \"\"\"\n\n @classmethod\n def get_response(cls, serializer) -> Response:\n phone = serializer.validated_data['phone']\n # exists of user is checked before\n user = User.objects.get(phone=phone)\n confirmation_code = serializer.validated_data['confirmation_code']\n if not cls.check_confirmation_code(user, confirmation_code):\n return Response(\n {'message': 'Неверный код'}, status=status.HTTP_403_FORBIDDEN,\n )\n cls.check_corporate_account(user)\n cls.finish_registration(user)\n token = cls.create_or_refresh_user_token(user)\n from apps.account.serializers import LoginConfirmAPIViewResponseSerializer\n response = LoginConfirmAPIViewResponseSerializer({\n 'token': token.key,\n 'is_profile_completed': cls.check_is_profile_completed(user),\n }).data\n return Response(\n response,\n status=status.HTTP_200_OK,\n )\n\n @classmethod\n def get_response_for_old_phone_confirmation(cls, user: User, serializer) -> Response:\n confirmation_code = serializer.validated_data['confirmation_code']\n if not cls.check_confirmation_code(user, confirmation_code):\n return Response(\n {'message': 'Неверный код'}, status=status.HTTP_403_FORBIDDEN,\n )\n cls.confirm_old_phone(user)\n cls.set_confirmation_date(user)\n return Response(\n {'message': 'Old phone is confirmed'}, status=status.HTTP_200_OK,\n )\n\n @classmethod\n def check_confirmation_code(cls, user: User, confirmation_code: str) -> bool:\n return user.confirmation_code == confirmation_code\n\n @staticmethod\n def finish_registration(user: User) -> None:\n user.is_active = True\n user.is_registration_finish = True\n user.save(update_fields=['is_active', 'is_registration_finish'])\n\n @staticmethod\n def create_or_refresh_user_token(user: User) -> Token:\n token, created = Token.objects.get_or_create(user=user)\n\n return token\n\n @staticmethod\n def check_is_profile_completed(user: User) -> bool:\n return all(\n [user.first_name, user.last_name, user.gender, user.birth_date]\n )\n\n @staticmethod\n def check_is_user_exists(phone: str) -> None:\n if not User.objects.filter(phone=phone).exists():\n raise exceptions.NotFound('user not found')\n\n @staticmethod\n def set_confirmation_date(user_obj: User) -> None:\n user_obj.confirmation_date = None\n user_obj.save(update_fields=['confirmation_date'])\n\n @staticmethod\n def confirm_old_phone(user: User) -> None:\n user.is_old_phone_confirmed = True\n user.save(update_fields=['is_old_phone_confirmed'])\n\n @classmethod\n def check_corporate_account(cls, user) -> None:\n from fcm_django.models import FCMDevice\n\n user_active_device = (\n FCMDevice.objects.filter(active=True, user=user)\n )\n if user.is_corporate_account:\n if len(user_active_device) < 5:\n pass\n else:\n send_notice_for_deleted_fcm_device(\n user_active_device,\n user.is_corporate_account\n )\n elif len(user_active_device) < 1:\n pass\n else:\n send_notice_for_deleted_fcm_device(\n user_active_device,\n user.is_corporate_account\n )\n\n\nclass ChangeOldPhoneService(UserAuthService, PhoneConfirmationService):\n \"\"\" Service for changing old phone number \"\"\"\n\n @classmethod\n def get_response(cls, serializer) -> Response:\n \"\"\"Method для login пользователя и отсылки SMS \"\"\"\n user = serializer.user\n new_phone = serializer.data['phone']\n response_data = {\n 'message': {'message': 'Сообщение отправлено'},\n 'status': status.HTTP_200_OK\n }\n if not cls.compare_confirmation_time(user):\n response_data = {\n 'message': {'message': 'Вы слишком часто отправляете сообщение.'},\n 'status': status.HTTP_429_TOO_MANY_REQUESTS\n }\n elif not cls.send_confirmation_sms(user):\n response_data = {\n 'message': {'message': 'Не удалось отправить сообщение. Попробуйте позже.'},\n 'status': status.HTTP_400_BAD_REQUEST\n }\n elif cls.new_phone_not_unique(new_phone):\n response_data = {\n 'message': {'message': 'Такой номер телефона уже существует'},\n 'status': status.HTTP_406_NOT_ACCEPTABLE,\n }\n return Response(\n response_data['message'], response_data['status']\n )\n\n @classmethod\n def get_response_for_new_phone_confirmation(\n cls, user: User,\n serializer: serializers.Serializer) -> Response:\n\n confirmation_code = serializer.validated_data['confirmation_code']\n if not cls.check_confirmation_code(user, confirmation_code):\n return Response(\n {'message': 'Неверный код'}, status=status.HTTP_403_FORBIDDEN,\n )\n response_1c_status, response_1c_data = (\n User1CNumberChangeService.sync_user_phone(user)\n )\n if not response_1c_status:\n return Response(\n {'message': response_1c_data},\n status=status.HTTP_400_BAD_REQUEST,\n )\n cls.confirm_new_phone(user)\n return Response(\n {'message': 'New phone is confirmed'}, status=status.HTTP_200_OK,\n )\n\n @staticmethod\n def new_phone_not_unique(new_phone) -> bool:\n return User.objects.filter(phone=new_phone).exists()\n\n @staticmethod\n def confirm_new_phone(user: User) -> None:\n user.phone, user.tmp_phone = user.tmp_phone, user.phone\n user.is_old_phone_confirmed = False\n user.save(update_fields=['phone', 'tmp_phone', 'is_old_phone_confirmed'])\n\n @staticmethod\n def set_tmp_phone_number(phone_number, user):\n \"\"\" Getting user instance \"\"\"\n user.tmp_phone = phone_number\n user.save(update_fields=['tmp_phone'])\n return user\n" }, { "alpha_fraction": 0.703342616558075, "alphanum_fraction": 0.714484691619873, "avg_line_length": 28.91666603088379, "blob_id": "c06f83421711a264c02279ffbf1771fb74743763", "content_id": "c859c3e0d6f5e24e4a9235eb948cb16f306184c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 718, "license_type": "no_license", "max_line_length": 76, "num_lines": 24, "path": "/apps/setting/tests/factories.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from random import choice\nimport datetime\n\nimport factory\n\nfrom apps.setting.models import AppVersion, Setting\n\n\nclass AppVersionFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = AppVersion\n\n android_version = factory.Sequence(lambda n: '1.%d' % choice([1, 2, 3]))\n android_force_update = factory.Sequence(lambda x: choice([True, False]))\n ios_version = factory.Sequence(lambda n: '1.%d' % choice([1, 2, 3]))\n ios_force_update = factory.Sequence(lambda x: choice([True, False]))\n\n\nclass SettingFactory(factory.django.DjangoModelFactory):\n qr_code_expiration_date = factory.LazyFunction(datetime.timedelta)\n is_service_active = False\n\n class Meta:\n model = Setting\n" }, { "alpha_fraction": 0.5546995401382446, "alphanum_fraction": 0.5901386737823486, "avg_line_length": 27.217391967773438, "blob_id": "0aa6aa7d8e087bfa56ade1f4e0dd99d9945e6d9f", "content_id": "3a67c0a0fb15d7e2e5ca169ae78209015387ef1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 97, "num_lines": 23, "path": "/apps/account/migrations/0009_auto_20210527_1151.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-27 05:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0008_user_is_corporate_account'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='qr_code',\n field=models.CharField(blank=True, max_length=255, null=True, verbose_name='QR-код'),\n ),\n migrations.AlterField(\n model_name='user',\n name='qr_code_updated_at',\n field=models.DateTimeField(blank=True, null=True, verbose_name='QR-код обновлен в'),\n ),\n ]\n" }, { "alpha_fraction": 0.7010628581047058, "alphanum_fraction": 0.7037200927734375, "avg_line_length": 29.513513565063477, "blob_id": "eb6609c74d39375a1c6ad538810bc24103056673", "content_id": "04f4c5c367aeb5614c573bcd25549dca67511d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2258, "license_type": "no_license", "max_line_length": 78, "num_lines": 74, "path": "/apps/check/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django_filters.rest_framework import DjangoFilterBackend\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom apps.account.custom_openapi import AuthRetrieveAPIView, auth_param\nfrom apps.account.serializers import AuthErrorSerializer\nfrom apps.brand.pagination import LargeListPagination\nfrom apps.check.models import Check\nfrom apps.check.serializers import (\n QRCodeSerializer, CheckListSerializer, CheckDetailSerializer\n)\nfrom apps.check.service import QRCodeService\nfrom apps.check.filters import CheckFilter\nfrom apps.notifications.service import SendPushNotification\n\n\nclass QRCodeAPIView(AuthRetrieveAPIView):\n \"\"\"\n Api view for get QR code\n \"\"\"\n serializer_class = QRCodeSerializer\n\n def get_object(self):\n return QRCodeService.update_user_data(self.request.user)\n\n\nclass CheckListAPIView(generics.ListAPIView):\n \"\"\"\n API View for get check list\n \"\"\"\n permission_classes = (IsAuthenticated,)\n pagination_class = LargeListPagination\n serializer_class = CheckListSerializer\n filter_backends = [DjangoFilterBackend]\n filter_class = CheckFilter\n\n def get_queryset(self):\n queryset = (\n Check.objects.filter(user=self.request.user)\n ).order_by('-accrued_point_date')\n\n return queryset\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 401: AuthErrorSerializer(),\n }\n )\n def get(self, request, *args, **kwargs):\n return super(CheckListAPIView, self).get(request, *args, **kwargs)\n\n\nclass CheckRetrieveAPIView(AuthRetrieveAPIView):\n \"\"\"\n API View for get check detail\n \"\"\"\n serializer_class = CheckDetailSerializer\n\n def get_queryset(self):\n return Check.objects.filter(user=self.request.user)\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 401: AuthErrorSerializer(),\n }\n )\n def get(self, request, *args, **kwargs):\n SendPushNotification.set_notification_viewed_for_check(\n request, self.get_object()\n )\n return super(CheckRetrieveAPIView, self).get(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.5726141333580017, "alphanum_fraction": 0.6161825656890869, "avg_line_length": 24.36842155456543, "blob_id": "6b0b9b123fabffdbdb2c8d5f07ffbe41a177ace7", "content_id": "5d9461b3cefe7dc3016c8fcd0e9655c365b6fede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 105, "num_lines": 19, "path": "/apps/setting/migrations/0003_appversion_ios_build_number.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-30 08:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('setting', '0002_appversion'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='appversion',\n name='ios_build_number',\n field=models.PositiveIntegerField(default=1, verbose_name='Build версия для ios приложения'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5982142686843872, "alphanum_fraction": 0.6553571224212646, "avg_line_length": 25.66666603088379, "blob_id": "65bd5e509a0945115b8c15bc4ef20f98f1cc90e9", "content_id": "b47dee73c26f54e028870bf53f5334d773f9c236", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "no_license", "max_line_length": 134, "num_lines": 21, "path": "/apps/info/migrations/0007_banner_description.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-09 04:33\n\nimport ckeditor_uploader.fields\nfrom django.db import migrations\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0006_auto_20210408_1352'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='banner',\n name='description',\n field=ckeditor_uploader.fields.RichTextUploadingField(default=django.utils.timezone.now, verbose_name='Описание баннера'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7843137383460999, "alphanum_fraction": 0.7843137383460999, "avg_line_length": 50, "blob_id": "90de0d4586958fd1ef3d315a020a7154a8572136", "content_id": "8a4d5265ff23b71992406a046bc27adea4c81a18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 50, "num_lines": 1, "path": "/apps/check/__init__.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "default_app_config = 'apps.check.apps.CheckConfig'\n" }, { "alpha_fraction": 0.6330182552337646, "alphanum_fraction": 0.6336934566497803, "avg_line_length": 26.68224334716797, "blob_id": "9087a60adfd7b24a7170e3bfa3e2e60a97f02b8d", "content_id": "92ca4098738ec330c06898da238df40f7bba1d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2962, "license_type": "no_license", "max_line_length": 83, "num_lines": 107, "path": "/apps/info/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom drf_yasg.utils import swagger_serializer_method\n\nfrom .models import (\n Banner, ProgramCondition, Contact,\n PromotionAndNews, PromotionAndNewsImage, ContactIcon,\n)\nfrom apps.notifications.models import Notification\n\n\nclass PromotionAndNewsSerializer(serializers.ModelSerializer):\n image = serializers.SerializerMethodField()\n\n class Meta:\n model = PromotionAndNews\n fields = (\n 'id',\n 'created_at',\n 'information_type',\n 'title',\n 'description',\n 'is_active',\n 'image',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.ImageField)\n def get_image(self, obj) -> str:\n image_obj = obj.images.all()\n request = self.context['request']\n image_url = request.build_absolute_uri(\n image_obj[0].image.url) if image_obj else None\n return image_url\n\n\nclass PromotionAndNewsImageSerializers(serializers.ModelSerializer):\n class Meta:\n model = PromotionAndNewsImage\n fields = ('id', 'image', 'is_main',)\n\n\nclass PromotionAndNewsDetailSerializer(serializers.ModelSerializer):\n images = PromotionAndNewsImageSerializers(many=True)\n badge_count = serializers.SerializerMethodField()\n\n class Meta:\n model = PromotionAndNews\n fields = (\n 'id',\n 'created_at',\n 'information_type',\n 'title',\n 'description',\n 'is_active',\n 'images',\n 'badge_count',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.IntegerField)\n def get_badge_count(self, obj):\n user = self.context['request'].user\n if user.is_anonymous:\n count = 0\n return count\n else:\n count = Notification.objects.filter(user=user, is_viewed=False).count()\n return count\n\n\nclass BannerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Banner\n fields = ('id', 'title', 'description', 'image',)\n\n\nclass BannerDetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = Banner\n fields = ('id', 'title', 'image', 'description',)\n\n\nclass ProgramConditionSerializer(serializers.ModelSerializer):\n class Meta:\n model = ProgramCondition\n fields = ('id', 'title', 'description',)\n\n\nclass ContactIconSerializer(serializers.ModelSerializer):\n class Meta:\n model = ContactIcon\n fields = ('id', 'title', 'image')\n\n\nclass ContactListSerializer(serializers.ModelSerializer):\n icon_image = ContactIconSerializer()\n\n class Meta:\n model = Contact\n fields = ('id', 'icon_image', 'title', 'link',)\n\n\nclass BannerAndPromotionSerializer(serializers.Serializer):\n banner = BannerSerializer()\n promotion = PromotionAndNewsSerializer(many=True)\n\n class Meta:\n field = ('banner', 'promotion',)\n" }, { "alpha_fraction": 0.5668073296546936, "alphanum_fraction": 0.5668073296546936, "avg_line_length": 19.91176414489746, "blob_id": "57e642221f78ded16f5ae690b4f27d9843cd9ea9", "content_id": "5d3c0daa1f4a6aca2a974d0b3ab851b18d03c083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/apps/setting/admin.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom solo.admin import SingletonModelAdmin\n\nfrom apps.setting.models import Setting, AppVersion, HelpPage\n\n\[email protected](Setting)\nclass SettingAdmin(SingletonModelAdmin):\n pass\n\n\[email protected](HelpPage)\nclass HelpPageAdmin(SingletonModelAdmin):\n pass\n\n\[email protected](AppVersion)\nclass AppVersionAdmin(SingletonModelAdmin):\n fieldsets = (\n ('Android', {\n 'fields': (\n 'android_version',\n 'android_force_update',\n )\n }),\n ('Ios', {\n 'fields': (\n 'ios_build_number',\n 'ios_version',\n 'ios_force_update',\n )\n })\n )\n" }, { "alpha_fraction": 0.5952625870704651, "alphanum_fraction": 0.6148300766944885, "avg_line_length": 34.96296310424805, "blob_id": "139033138bf0786c81325bd905b18b372d265981", "content_id": "bb241d2e3da972f680fee548bf79b008ce47baa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 220, "num_lines": 27, "path": "/apps/setting/migrations/0001_initial.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-06 10:20\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Setting',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('qr_code_expiration_date', models.DurationField(default=datetime.timedelta(seconds=180), help_text=' QR код будет недействителен при истечений срока активности', verbose_name='Срок активности QR кода')),\n ('is_service_active', models.BooleanField(default=True, help_text='Убрав галочку, вы можете отключить сервис', verbose_name='Статус сервиса')),\n ],\n options={\n 'verbose_name': 'Настройка сайта',\n 'verbose_name_plural': 'Настройки сайта',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.746268630027771, "alphanum_fraction": 0.746268630027771, "avg_line_length": 21.33333396911621, "blob_id": "ae864dedfac3bd1f18216e422ed77f88aaf86c22", "content_id": "53c579c0dd683fc977a2f796a9000745a1ed1a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/apps/integration/apps.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass IntegrationConfig(AppConfig):\n name = 'apps.integration'\n verbose_name = 'Интеграция'\n" }, { "alpha_fraction": 0.6137565970420837, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 28.076923370361328, "blob_id": "424ad88eebd13cdb9e2eeede968a8149ef705e72", "content_id": "3e2238bc94e93479592e68bf21e3fa5cef02e28e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 69, "num_lines": 26, "path": "/apps/setting/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.http import JsonResponse\nfrom rest_framework import status\n\nfrom apps.setting.models import Setting\n\n\nclass ApplicationStatusService:\n @classmethod\n def check_application_status(cls, request, response):\n app_setting = Setting.objects.first()\n is_service_off = (\n app_setting and\n not app_setting.is_service_active and\n cls.is_api_path(request)\n )\n if is_service_off:\n return JsonResponse(\n {'message': 'Сервис временно недоступен'},\n status=status.HTTP_503_SERVICE_UNAVAILABLE,\n )\n\n return response\n\n @staticmethod\n def is_api_path(request):\n return True if request.path.split('/')[1] == 'api' else False\n" }, { "alpha_fraction": 0.7584269642829895, "alphanum_fraction": 0.7584269642829895, "avg_line_length": 21.25, "blob_id": "b7f96fbb2fd464df553fa2cd8392d4a43ce6a164", "content_id": "0167d160ef7e0575764e3e258f401f87c63aed9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "no_license", "max_line_length": 70, "num_lines": 8, "path": "/apps/notifications/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom apps.notifications.views import NotificationAPIView\n\n\nurlpatterns = [\n path('', NotificationAPIView.as_view(), name='notification_list'),\n]\n" }, { "alpha_fraction": 0.5489949584007263, "alphanum_fraction": 0.5917085409164429, "avg_line_length": 32.16666793823242, "blob_id": "92d05c7a8644352475992b41ea75fb2857ce43fc", "content_id": "e1afd966aabd60aeb0fc9c9d7844d1460aa24149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 230, "num_lines": 24, "path": "/apps/check/migrations/0004_auto_20210429_1835.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-29 12:35\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('check', '0003_auto_20210426_1106'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='check',\n name='due_date',\n field=models.DateTimeField(blank=True, null=True, verbose_name='Дата оплаты долга'),\n ),\n migrations.AddField(\n model_name='check',\n name='status',\n field=models.CharField(choices=[('accrued', 'Начислено'), ('withdrawn', 'Снято'), ('accrued_and_withdrawn', 'Начислено и снято'), ('on_credit', 'В долг')], default='accrued', max_length=10, verbose_name='Статус чека'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.668225884437561, "alphanum_fraction": 0.6735716462135315, "avg_line_length": 30.17708396911621, "blob_id": "bde8f2c4a497df8ee2c418a10f64b78578316064", "content_id": "f141575519ffd5f97003ec4b682a8be5aaebc94b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3063, "license_type": "no_license", "max_line_length": 80, "num_lines": 96, "path": "/apps/brand/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.db.models import Prefetch\n\nfrom rest_framework import generics\n\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom apps.brand import custom_openapi\nfrom apps.brand.models import Brand, Filial, FilialImage\nfrom apps.brand.pagination import LargeListPagination, SmallListPagination\nfrom apps.brand.serializers import (\n BrandListSerializer, BrandDetailSerializer, FilialListSerializer,\n FilialSerializer,\n)\nfrom apps.brand.service import FilialService\n\n\nclass BrandListAPIView(generics.ListAPIView):\n \"\"\"\n Api view for get all brand list page by 20\n \"\"\"\n serializer_class = BrandListSerializer\n queryset = Brand.objects.all()\n pagination_class = LargeListPagination\n\n\nclass BrandRetrieveAPIView(generics.RetrieveAPIView):\n \"\"\"\n Api view for get brand by id\n \"\"\"\n serializer_class = BrandDetailSerializer\n queryset = Brand.objects.all()\n lookup_field = 'id'\n\n @swagger_auto_schema(\n responses={\n 404: '{\"detail\": \"Страница не найдена.\"}',\n }\n )\n def get(self, request, *args, **kwargs):\n return super(BrandRetrieveAPIView, self).get(request, *args, **kwargs)\n\n\nclass FilialListAPIView(generics.ListAPIView):\n \"\"\"\n Api view for get all filial list page by 10\n \"\"\"\n serializer_class = FilialListSerializer\n pagination_class = SmallListPagination\n queryset = (\n Filial.objects.all()\n .prefetch_related(\n Prefetch('images', FilialImage.objects.filter(is_main=True))\n )\n )\n\n def get_serializer_context(self):\n context = super(FilialListAPIView, self).get_serializer_context()\n client_geolocation = FilialService.get_geolocation(self.request)\n context['client_geolocation'] = client_geolocation\n\n return context\n\n @swagger_auto_schema(\n manual_parameters=custom_openapi.filial_extra_params,\n responses={\n 400: '{\"geolocation\": \"Неправильный формат query param: lat long\"}',\n }\n )\n def get(self, request, *args, **kwargs):\n return super(FilialListAPIView, self).get(request, *args, **kwargs)\n\n\nclass FilialRetrieveAPIView(generics.RetrieveAPIView):\n \"\"\"\n Api view for get filial by id\n \"\"\"\n serializer_class = FilialSerializer\n queryset = Filial.objects.all()\n lookup_field = 'id'\n\n def get_serializer_context(self):\n context = super(FilialRetrieveAPIView, self).get_serializer_context()\n client_geolocation = FilialService.get_geolocation(self.request)\n context['client_geolocation'] = client_geolocation\n\n return context\n\n @swagger_auto_schema(\n manual_parameters=custom_openapi.filial_extra_params,\n responses={\n 400: '{\"geolocation\": \"Неправильный формат query param: lat long\"}',\n 404: '{\"detail\": \"Страница не найдена.\"}',\n }\n )\n def get(self, request, *args, **kwargs):\n return super(FilialRetrieveAPIView, self).get(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.7361563444137573, "alphanum_fraction": 0.7719869613647461, "avg_line_length": 24.58333396911621, "blob_id": "cdec88197f9e14998e943b32a185e82c21ce17a0", "content_id": "8c74d00cbb1bd94c3d72cb48781906988bed4692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 307, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/.envs/.env.example", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "DJANGO_SECRET_KEY=secret-key\nDJANGO_DEBUG=on/off\nDJANGO_ALLOWED_HOSTS=[]\nDATABASE_URL=postgres://db_user:db_password@localhost:5432/db_name\nFCM_SERVER_KEY=\nNIKITA_LOGIN=\nNIKITA_PASSWORD=\nNIKITA_SENDER=\nNIKITA_TEST=1 or 0 1 for test, 0 for prod\nBASE_1C_SERVER_DOMAIN=\nUSER_1C_USERNAME=\nUSER_1C_PASSWORD=\n" }, { "alpha_fraction": 0.5957977175712585, "alphanum_fraction": 0.6011396050453186, "avg_line_length": 27.948453903198242, "blob_id": "35bd07eb6945423d3649eb229d069eece999545e", "content_id": "c345d6da9705fe3e07fa93324f784568c9b6fd99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3055, "license_type": "no_license", "max_line_length": 78, "num_lines": 97, "path": "/apps/integration/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib.auth import authenticate\nfrom rest_framework import serializers\n\nfrom apps.account.models import User\nfrom apps.brand.models import Filial\nfrom apps.check.models import Check\n\n\nclass Auth1cSerializer(serializers.ModelSerializer):\n \"\"\"Сериалайзер для валидации пользователя 1c\"\"\"\n\n phone = serializers.CharField(required=True)\n password = serializers.CharField(required=True)\n\n def validate(self, data):\n phone = data.get('phone')\n password = data.get('password')\n if phone and password:\n user = authenticate(request=self.context.get('request'),\n phone=phone, password=password)\n if not user:\n raise serializers.ValidationError(\n {'Сообщение': 'Некорректные данные'})\n else:\n raise serializers.ValidationError(\n {'Сообщение': 'Неверный формат данных'})\n\n self.user = user\n\n return data\n\n class Meta:\n model = User\n fields = ('phone', 'password')\n\n\nclass Login1cAPIViewResponseSerializer(serializers.Serializer):\n \"\"\"\n Сериалайзер для токена пользователя 1c\n \"\"\"\n token = serializers.CharField()\n\n\nclass Get1cUserSerializer(serializers.ModelSerializer):\n \"\"\"\n Сериализатор 1С данных пользователя\n \"\"\"\n\n class Meta:\n model = User\n fields = ('user_1C_code', 'phone')\n extra_kwargs = {\n 'user_1C_code': {'required': True},\n 'phone': {'required': True}\n }\n\n\nclass CheckSerializer(serializers.ModelSerializer):\n \"\"\"Сериалайзер для чека\"\"\"\n user_1c_code = serializers.CharField(required=True)\n filial_1c_code = serializers.CharField(required=True)\n\n class Meta:\n model = Check\n fields = (\n 'unique_1c_check_code', 'money_paid', 'bonus_paid', 'total_paid',\n 'accrued_point', 'accrued_point_date', 'withdrawn_point',\n 'withdrawn_point_date', 'is_active', 'user_1c_code',\n 'filial_1c_code', 'status', 'is_on_credit', 'balance_owed',\n 'due_date',\n )\n\n\nclass UpdateCheckSerializer(serializers.ModelSerializer):\n \"\"\"Сериалайзер обновления для чека\"\"\"\n\n class Meta:\n model = Check\n fields = (\n 'money_paid', 'bonus_paid', 'total_paid',\n 'accrued_point', 'accrued_point_date',\n 'withdrawn_point', 'withdrawn_point_date',\n 'is_active', 'status', 'is_on_credit', 'balance_owed','due_date',\n )\n\n\nclass Sync1cUserSerializer(serializers.ModelSerializer):\n \"\"\"\n Сериализатор для синхронизации 1С данных пользователя\n \"\"\"\n\n class Meta:\n model = User\n fields = (\n 'phone', 'first_name', 'last_name', 'gender',\n 'birth_date'\n )\n" }, { "alpha_fraction": 0.5325581431388855, "alphanum_fraction": 0.6069767475128174, "avg_line_length": 22.88888931274414, "blob_id": "1db32c1087be5f55a4b47ec5126d0aa7d6fa70ad", "content_id": "784ba48912520fee6de912a7793a5092ea645f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/apps/notifications/migrations/0005_notification_is_on_credit.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-06 08:19\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('notifications', '0004_auto_20210504_1810'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='notification',\n name='is_on_credit',\n field=models.BooleanField(default=False, verbose_name='В долг?'),\n ),\n ]\n" }, { "alpha_fraction": 0.6665055751800537, "alphanum_fraction": 0.6674721837043762, "avg_line_length": 31.841270446777344, "blob_id": "6b504d47e5aecf32598aa93ce71235cbb0458380", "content_id": "aea67a092f8695976f43116154687405239fa079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2234, "license_type": "no_license", "max_line_length": 106, "num_lines": 63, "path": "/apps/notifications/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import ast\n\nfrom django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom fcm_django.models import FCMDevice\n\nfrom apps.account.models import User\nfrom core.constants import (\n ACCRUED, WITHDRAW, ACCRUED_AND_WITHDRAW,\n NEWS, PROMOTION\n)\nfrom core.constants import NOTIFICATION_TYPE\nfrom apps.setting.models import TimeStampAbstractModel\n\n\nclass Notification(TimeStampAbstractModel):\n NOTIFICATION_TITLE = 'Уведомление'\n NOTIFICATION_MESSAGE = {\n ACCRUED: 'Вам начислено {accrued_point} баллов',\n WITHDRAW: 'Вы использовали {withdrawn_point} баллов',\n ACCRUED_AND_WITHDRAW: 'Вы использовали {withdrawn_point} и Вам начисленно {accrued_point} баллов',\n PROMOTION: '{title}',\n NEWS: '{title}',\n }\n\n user = models.ForeignKey(\n User, related_name='notifications',\n on_delete=models.CASCADE, verbose_name='Пользователь'\n )\n notice_type = models.CharField(\n choices=NOTIFICATION_TYPE, max_length=25,\n verbose_name='Тип',\n )\n is_on_credit = models.BooleanField(\n default=False, verbose_name='В долг?',\n )\n linked_article = models.ForeignKey(\n 'info.PromotionAndNews', null=True, blank=True,\n related_name='notice', on_delete=models.CASCADE,\n verbose_name='Новость или Акция'\n )\n linked_check = models.ForeignKey(\n 'check.Check', null=True, blank=True,\n related_name='notice', on_delete=models.CASCADE,\n verbose_name='Чек'\n )\n body = JSONField(null=True, blank=True, verbose_name='Тело')\n is_viewed = models.BooleanField(verbose_name='Просмотрено?', default=False)\n is_active = models.BooleanField(verbose_name='Активен?', default=True)\n\n def __str__(self):\n return f'ID: {self.id}'\n\n @property\n def get_message(self):\n return self.NOTIFICATION_MESSAGE[self.notice_type].format(\n **ast.literal_eval(self.body)\n )\n\n class Meta:\n verbose_name = 'Уведомление'\n verbose_name_plural = 'Уведомления'\n ordering = ['-created_at']\n" }, { "alpha_fraction": 0.5558982491493225, "alphanum_fraction": 0.5828835964202881, "avg_line_length": 34.054054260253906, "blob_id": "da9ad616df108dae6dd329937e33b75e3b330681", "content_id": "c5e412f73c7dd8a8899ccb52a81774a12a039ec0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1376, "license_type": "no_license", "max_line_length": 163, "num_lines": 37, "path": "/apps/info/migrations/0006_auto_20210408_1352.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-08 07:52\n\nimport core.utils\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0005_auto_20210408_1140'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ContactIcon',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=70, verbose_name='Заголовок иконки')),\n ('image', models.ImageField(upload_to=core.utils.generate_filename, verbose_name='Фото иконки для контактов')),\n ],\n options={\n 'verbose_name': 'Иконка для контактов',\n 'verbose_name_plural': 'Иконки для контактов',\n },\n ),\n migrations.RemoveField(\n model_name='contact',\n name='icon_type',\n ),\n migrations.AddField(\n model_name='contact',\n name='icon_image',\n field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='contacts', to='info.ContactIcon', verbose_name='Иконка'),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6589861512184143, "alphanum_fraction": 0.671380877494812, "avg_line_length": 33.96111297607422, "blob_id": "47f5e76d7efe30b7dc1452af6831dac6e79dfed9", "content_id": "964f0919d54dafa9209c0222e7fbf012855b2956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6669, "license_type": "no_license", "max_line_length": 97, "num_lines": 180, "path": "/apps/account/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import generics, status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom apps.account.custom_openapi import (\n AuthRetrieveAPIView, AuthUpdateAPIView, auth_param,\n)\nfrom apps.account.models import City\nfrom apps.account.serializers import (\n PhoneAuthSerializer, LoginConfirmationCodeSerializer, CitySerializer,\n UserUpdateSerializer, LoginConfirmAPIViewResponseSerializer,\n UserAvatarUpdateSerializer, AuthErrorSerializer, ConfirmationCodeSerializer,\n ChageOldPhoneSerializer, UserRetrieveSerializer,\n)\nfrom apps.account.service import (\n UserAuthService, PhoneConfirmationService, ChangeOldPhoneService\n)\nfrom apps.integration.service import User1cUpdateService\n\n\nclass AuthAPIView(generics.GenericAPIView):\n \"\"\" Эндпоинт для login или создания пользователя и отсылки SMS \"\"\"\n serializer_class = PhoneAuthSerializer\n\n @swagger_auto_schema(\n responses={\n 200: '{\"message\": \"Сообщение отправлено\"}',\n 201: '{\"message\": \"User создан! Сообщение отправлено\"}',\n 400: \"It will return error type\",\n 429: '{\"message\": \"Вы слишком часто отправляете сообщение.\"}',\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n return UserAuthService.get_response(serializer)\n\n\nclass LoginConfirmAPIView(generics.GenericAPIView):\n \"\"\" Endpoint для подтверждения номера и авторизации пользователя \"\"\"\n serializer_class = LoginConfirmationCodeSerializer\n\n @swagger_auto_schema(\n responses={\n 200: LoginConfirmAPIViewResponseSerializer(),\n 400: 'It will return error type',\n 403: '{\"message\": \"Неверный код\"}',\n 404: '{\"detail\": \"user not found\"}',\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n return PhoneConfirmationService.get_response(serializer)\n\n\nclass SendSmsToOldPhoneAPIView(generics.GenericAPIView):\n \"\"\" Endpoint for send sms to old phone number \"\"\"\n permission_classes = (IsAuthenticated,)\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 200: '{\"message\": \"Сообщение отправлено\"}',\n 400: \"It will return error type\",\n 401: AuthErrorSerializer(),\n 429: '{\"message\": \"Вы слишком часто отправляете сообщение.\"}',\n }\n )\n def get(self, request, *args, **kwargs):\n user = request.user\n return UserAuthService.send_to_old_phone(user)\n\n\nclass OldPhoneConfirmAPIView(generics.GenericAPIView):\n \"\"\" Endpoint для подтверждения old phone number \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = ConfirmationCodeSerializer\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 200: '{\"message\": \"Old phone is confirmed\"}',\n 400: 'It will return error type',\n 401: AuthErrorSerializer(),\n 403: '{\"message\": \"Неверный код\"}',\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = request.user\n return PhoneConfirmationService.get_response_for_old_phone_confirmation(user, serializer)\n\n\nclass ChangeOldPhoneAPIView(generics.GenericAPIView):\n \"\"\" Endpoint для смены old phone number \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = ChageOldPhoneSerializer\n\n @swagger_auto_schema(\n responses={\n 200: '{\"message\": \"Сообщение отправлено\"}',\n 400: \"It will return error type\",\n 406: \"{'message': 'Такой номер телефона уже существует'}\",\n 429: '{\"message\": \"Вы слишком часто отправляете сообщение.\"}',\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(\n data=request.data, context={'request': request}\n )\n serializer.is_valid(raise_exception=True)\n\n return ChangeOldPhoneService.get_response(serializer)\n\n\nclass NewPhoneConfirmAPIView(generics.GenericAPIView):\n \"\"\" Endpoint для подтверждения new phone number \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = ConfirmationCodeSerializer\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 200: '{\"message\": \"New phone is confirmed\"}',\n 400: 'It will return error type',\n 401: AuthErrorSerializer(),\n 403: '{\"message\": \"Неверный код\"}',\n }\n )\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = request.user\n return ChangeOldPhoneService.get_response_for_new_phone_confirmation(user, serializer)\n\n\nclass CityListAPIView(generics.ListAPIView):\n \"\"\"Endpoint for get city list\"\"\"\n queryset = City.objects.all()\n serializer_class = CitySerializer\n\n\nclass UserUpdateAPIView(AuthUpdateAPIView):\n \"\"\"Endpoint for update user\"\"\"\n serializer_class = UserUpdateSerializer\n\n def get_object(self):\n return self.request.user\n\n def perform_update(self, serializer):\n user = serializer.save()\n User1cUpdateService.update_1c_user_id(user)\n\n\nclass UserRetrieveAPIView(AuthRetrieveAPIView):\n \"\"\"Endpoint for update user\"\"\"\n serializer_class = UserRetrieveSerializer\n\n def get_object(self):\n return self.request.user\n\n\nclass UserAvatarRetrieveUpdateAPIView(AuthRetrieveAPIView, AuthUpdateAPIView,\n generics.DestroyAPIView):\n \"\"\"Endpoint for update user image\"\"\"\n serializer_class = UserAvatarUpdateSerializer\n\n def get_object(self):\n return self.request.user\n\n def destroy(self, request, *args, **kwargs):\n instance = self.get_object()\n instance.avatar = None\n instance.save(update_fields=['avatar'])\n return Response(status=status.HTTP_204_NO_CONTENT)\n" }, { "alpha_fraction": 0.7043478488922119, "alphanum_fraction": 0.7043478488922119, "avg_line_length": 18.16666603088379, "blob_id": "6fb82cc0baf44077dcddbec38f85c5424abe2be4", "content_id": "4e660fac552f54ff05bc480bd137b9ad9107c598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/apps/check/apps.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass CheckConfig(AppConfig):\n name = 'apps.check'\n verbose_name = 'Чек'\n" }, { "alpha_fraction": 0.6232638955116272, "alphanum_fraction": 0.6232638955116272, "avg_line_length": 32.882354736328125, "blob_id": "f5553799a7f59ab24c0ca618126c0bdf57f63b1e", "content_id": "319e9841cf0b61abeb3b6f61f64bfa7713283fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/apps/notifications/admin.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom apps.notifications.models import Notification\n\n\[email protected](Notification)\nclass NotificationAdmin(admin.ModelAdmin):\n list_display = ['__str__', 'notice_type', 'user', 'is_viewed', 'is_active']\n list_filter = ['user', 'notice_type', 'is_active']\n fields = [\n 'user', 'notice_type', 'linked_check', 'linked_article',\n 'is_viewed', 'is_active', 'is_on_credit',\n ]\n readonly_fields = [\n 'user', 'notice_type', 'linked_check', 'linked_article',\n 'is_viewed', 'is_active', 'is_on_credit',\n ]\n" }, { "alpha_fraction": 0.6963965892791748, "alphanum_fraction": 0.697192907333374, "avg_line_length": 33.170066833496094, "blob_id": "d2862820d10f98c469c4592108a2ff2a738931f3", "content_id": "0e0f9a86d842e482ba6472b65fe61ed39a2950c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5163, "license_type": "no_license", "max_line_length": 87, "num_lines": 147, "path": "/apps/account/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg.utils import swagger_serializer_method\nfrom rest_framework import serializers\n\nfrom apps.account.models import User, City\nfrom apps.account.service import (\n UserAuthService, PhoneConfirmationService, ChangeOldPhoneService,\n)\nfrom apps.integration.service import UserGetWalletDataService\nfrom apps.notifications.models import Notification\nfrom apps.setting.models import HelpPage\nfrom apps.setting.serializers import HelpPageSerializer\n\n\nclass PhoneAuthSerializer(serializers.Serializer):\n \"\"\"Сериалайзер для валидации и создания пользователя \"\"\"\n phone = serializers.CharField(required=True)\n\n def validate(self, data):\n self.user, self.created = (\n UserAuthService.get_or_create_user_instance(phone_number=data.get('phone'))\n )\n if not self.created:\n self.confirm_login_allowed(self.user)\n return data\n\n def validate_phone(self, value):\n UserAuthService.check_format_user_phone(value)\n return value\n\n @staticmethod\n def confirm_login_allowed(user):\n if not user.is_active:\n raise serializers.ValidationError({'phone': 'Этот номер не активен.'})\n\n\nclass ConfirmationCodeSerializer(serializers.Serializer):\n \"\"\"Serializer for phone code confirmation\"\"\"\n confirmation_code = serializers.CharField(max_length=6, required=True)\n\n\nclass LoginConfirmationCodeSerializer(PhoneAuthSerializer, ConfirmationCodeSerializer):\n \"\"\" Сериалайзер для login код подтверждения \"\"\"\n\n def validate(self, data):\n PhoneConfirmationService.check_is_user_exists(data.get('phone'))\n self.confirm_login_allowed(data.get('phone'))\n return data\n\n def validate_phone(self, value):\n super(LoginConfirmationCodeSerializer, self).validate_phone(value)\n PhoneConfirmationService.check_is_user_exists(value)\n return value\n\n @staticmethod\n def confirm_login_allowed(phone: str) -> None:\n if not User.objects.filter(phone=phone, is_active=True).exists():\n raise serializers.ValidationError({'phone': 'Этот номер не активен.'})\n\n\nclass ChageOldPhoneSerializer(PhoneAuthSerializer):\n \"\"\" Сериалайзер для login код подтверждения \"\"\"\n\n def validate(self, data):\n request = self.context['request']\n self.user = (\n ChangeOldPhoneService.set_tmp_phone_number(\n phone_number=data.get('phone'),\n user=request.user,\n )\n )\n return data\n\n def validate_phone(self, value):\n return ChangeOldPhoneService.check_format_user_phone(value)\n\n\nclass LoginConfirmAPIViewResponseSerializer(serializers.Serializer):\n token = serializers.CharField()\n is_profile_completed = serializers.BooleanField()\n\n\nclass CitySerializer(serializers.ModelSerializer):\n class Meta:\n model = City\n fields = ['id', 'title']\n\n\nclass UserUpdateSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ['first_name', 'last_name', 'gender', 'birth_date', 'city']\n extra_kwargs = {\n field: {'required': True} for field in fields\n }\n\n\nclass UserAvatarUpdateSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ['avatar']\n extra_kwargs = {'avatar': {'required': True}}\n\n\nclass AuthErrorSerializer(serializers.Serializer):\n \"\"\" Error response on status.HTTP_401_UNAUTHORIZED \"\"\"\n detail = serializers.CharField(help_text='This is error text')\n\n\nclass UserGetWalletSerializer(serializers.Serializer):\n \"\"\" Serializer for user wallet data \"\"\"\n discount = serializers.CharField(required=True)\n active_point = serializers.CharField(required=True)\n inactive_point = serializers.CharField(required=True)\n\n\nclass UserRetrieveSerializer(serializers.ModelSerializer):\n city = serializers.SerializerMethodField()\n has_notification = serializers.SerializerMethodField()\n wallet = serializers.SerializerMethodField()\n help_page = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = [\n 'first_name', 'phone', 'avatar', 'last_name', 'gender',\n 'birth_date', 'city', 'has_notification', 'wallet', 'help_page',\n ]\n\n @swagger_serializer_method(serializer_or_field=UserGetWalletSerializer)\n def get_wallet(self, obj):\n user_wallet_data = UserGetWalletDataService.update_user_wallet_data(obj)\n serializer = UserGetWalletSerializer(data=user_wallet_data)\n serializer.is_valid(raise_exception=True)\n\n return serializer.data\n\n @swagger_serializer_method(serializer_or_field=HelpPageSerializer)\n def get_help_page(self, obj):\n help_page_obj = HelpPage.objects.first()\n serializer = HelpPageSerializer(help_page_obj)\n return serializer.data\n\n def get_city(self, obj):\n return obj.city.title if obj.city else None\n\n def get_has_notification(self, obj):\n return Notification.objects.filter(user=obj, is_viewed=False).exists()\n" }, { "alpha_fraction": 0.6140127182006836, "alphanum_fraction": 0.6140127182006836, "avg_line_length": 30.399999618530273, "blob_id": "75d7878fe5d114dde9c114158304dcb4249925c7", "content_id": "f39738f1991091de7cb353c277abee4eaf08f8f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/apps/brand/forms.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom apps.brand.models import Filial\n\n\nclass FilialForm(forms.ModelForm):\n class Meta:\n model = Filial\n fields = '__all__'\n\n def clean(self):\n super().clean()\n errors = {}\n start_work = self.cleaned_data['start_work']\n end_work = self.cleaned_data['end_work']\n is_around_the_clock = self.cleaned_data['is_around_the_clock']\n\n if not (is_around_the_clock or (start_work and end_work)):\n errors['is_around_the_clock'] = ValidationError(\n 'Обязательно заполнить дату начала и конца рабочего времени'\n 'или указать как круглосуточно'\n )\n if errors:\n raise ValidationError(errors)\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 54, "blob_id": "90096bb9f75c5153157528ef1746058fcdc26600", "content_id": "5cd28fad89f5916f60412a64ea92c9e8d5098d11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 55, "license_type": "no_license", "max_line_length": 54, "num_lines": 1, "path": "/apps/setting/__init__.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "default_app_config = 'apps.setting.apps.SettingConfig'\n" }, { "alpha_fraction": 0.7085828185081482, "alphanum_fraction": 0.7365269660949707, "avg_line_length": 30.3125, "blob_id": "b568bbbc9c08088095df6162c57b97a25396eff6", "content_id": "cf44256038d839df763bcb3c340bf503a428af3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 81, "num_lines": 16, "path": "/apps/account/tests/mymock.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework import status\nfrom rest_framework.response import Response\n\nfrom apps.account.tests import constants\n\n\nclass SuccessSmsNikitaResponse:\n def __init__(self):\n self.status_code = status.HTTP_200_OK\n self.text = constants.SMS_NIKITA_TEXT_ON_200_WITH_RESPONSE_STATUS_11\n\n\nclass SuccessSmsNikitaInvalidStatusResponse:\n def __init__(self):\n self.status_code = status.HTTP_200_OK\n self.text = constants.SMS_NIKITA_TEXT_ON_200_WITH_INVALID_RESPONSE_STATUS\n" }, { "alpha_fraction": 0.5006622672080994, "alphanum_fraction": 0.5456953644752502, "avg_line_length": 29.200000762939453, "blob_id": "2e748bd6b8fc286763528c6085a2f3504bfaafee", "content_id": "2b6978a0b16f6b27f1147361ef81a7664e016a25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 114, "num_lines": 25, "path": "/apps/setting/migrations/0005_helppage.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-17 10:35\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('setting', '0004_auto_20210505_1513'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='HelpPage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=50, verbose_name='Заголовок справки')),\n ('text', models.TextField(verbose_name='Текст справки')),\n ],\n options={\n 'verbose_name': 'Справка',\n 'verbose_name_plural': 'Справки',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6514175534248352, "alphanum_fraction": 0.6610824465751648, "avg_line_length": 28.846153259277344, "blob_id": "4676e2a55b168a3fac5e886aadaf2e6df702b5f5", "content_id": "ebe2c7cb4ee6b675e87341a26c0a5dabcbd2e381", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1552, "license_type": "no_license", "max_line_length": 77, "num_lines": 52, "path": "/apps/account/custom_openapi.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom apps.account.serializers import AuthErrorSerializer\n\nauth_param = openapi.Parameter(\n 'Authorization',\n openapi.IN_HEADER,\n description='Token ...',\n type=openapi.TYPE_STRING\n)\n\n\nclass AuthUpdateAPIView(generics.UpdateAPIView):\n \"\"\"UpdateAPIView for Authenticated endpoints\"\"\"\n permission_classes = (IsAuthenticated,)\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 401: AuthErrorSerializer(),\n 400: 'It will return error type',\n }\n )\n def put(self, request, *args, **kwargs):\n return super(AuthUpdateAPIView, self).put(request, *args, **kwargs)\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 401: AuthErrorSerializer(),\n 400: 'It will return error type',\n }\n )\n def patch(self, request, *args, **kwargs):\n return super(AuthUpdateAPIView, self).patch(request, *args, **kwargs)\n\n\nclass AuthRetrieveAPIView(generics.RetrieveAPIView):\n \"\"\"RetrieveAPIView for Authenticated endpoints\"\"\"\n permission_classes = (IsAuthenticated,)\n\n @swagger_auto_schema(\n manual_parameters=[auth_param],\n responses={\n 401: AuthErrorSerializer(),\n }\n )\n def get(self, request, *args, **kwargs):\n return super(AuthRetrieveAPIView, self).get(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.5366379022598267, "alphanum_fraction": 0.6163793206214905, "avg_line_length": 24.77777862548828, "blob_id": "732ac87e94f881122f47504bbd50018e75653123", "content_id": "25ae04bb7f5a49d89bddd4f147ff7024abf307bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 116, "num_lines": 18, "path": "/apps/brand/migrations/0007_filial_unique_1c_filial_code.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-12 11:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0006_auto_20210407_1607'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='filial',\n name='unique_1c_filial_code',\n field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Уникальный 1C код филиала'),\n ),\n ]\n" }, { "alpha_fraction": 0.6406133770942688, "alphanum_fraction": 0.6467969417572021, "avg_line_length": 33.85344696044922, "blob_id": "9eef1721fd1a7e30770f05d91af12a52cd817932", "content_id": "5418f64074eea253c2679300fdefb7fc91415e0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4227, "license_type": "no_license", "max_line_length": 80, "num_lines": 116, "path": "/apps/account/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import AbstractUser, UserManager\nfrom django.db import models\nfrom django.db.models import Q, UniqueConstraint\n\nfrom core.constants import GENDER_TYPE, MALE\nfrom core.utils import generate_filename\n\n\nclass CustomUserManager(UserManager):\n def _create_user(self, phone, password, **extra_fields):\n \"\"\"\n Create and save a user with the given phone, and password.\n \"\"\"\n if not phone:\n raise ValueError('The given username must be set')\n user = self.model(phone=phone, **extra_fields)\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_user(self, phone, password=None, **extra_fields):\n extra_fields.setdefault('is_staff', False)\n extra_fields.setdefault('is_superuser', False)\n return self._create_user(phone, password, **extra_fields)\n\n def create_superuser(self, phone, password, **extra_fields):\n extra_fields.setdefault('is_staff', True)\n extra_fields.setdefault('is_superuser', True)\n\n if extra_fields.get('is_staff') is not True:\n raise ValueError('Superuser must have is_staff=True.')\n if extra_fields.get('is_superuser') is not True:\n raise ValueError('Superuser must have is_superuser=True.')\n\n return self._create_user(phone, password, **extra_fields)\n\n\nclass User(AbstractUser):\n username = None\n phone = models.CharField(max_length=25, unique=True, verbose_name='Телефон')\n avatar = models.ImageField(\n upload_to=generate_filename, null=True, blank=True,\n verbose_name='Аватар',\n )\n tmp_phone = models.CharField(\n max_length=25, verbose_name='Временный телефон', null=True, blank=True,\n )\n birth_date = models.DateField(null=True, verbose_name='Дата рождения',)\n gender = models.CharField(\n choices=GENDER_TYPE, default=MALE, max_length=10, verbose_name='Пол',\n )\n city = models.ForeignKey(\n to='City', verbose_name='Город', null=True, on_delete=models.SET_NULL,\n related_name='users',\n )\n active_point = models.PositiveIntegerField(\n default=0, verbose_name='Активные баллы',\n )\n inactive_point = models.PositiveIntegerField(\n default=0, verbose_name='Неактивные баллы',\n )\n discount = models.CharField(\n max_length=20, verbose_name='Скидка',\n )\n qr_code = models.CharField(\n max_length=255, blank=True, null=True, verbose_name='QR-код',\n )\n qr_code_updated_at = models.DateTimeField(\n blank=True, null=True, verbose_name='QR-код обновлен в',\n )\n is_registration_finish = models.BooleanField(\n default=False, verbose_name='is_registration_finish',\n )\n confirmation_code = models.CharField(\n verbose_name='confirmation code', max_length=6, null=True, blank=True,\n )\n confirmation_date = models.DateTimeField(\n verbose_name='confirmation date', null=True, blank=True,\n )\n is_old_phone_confirmed = models.BooleanField(\n verbose_name='is old phone confirmed', default=False,\n )\n user_1C_code = models.CharField(\n max_length=255, null=True, blank=True,\n verbose_name='Уникальный 1С код пользователя'\n )\n is_corporate_account = models.BooleanField(\n default=False, verbose_name='Корпоративный аккаунт?'\n )\n objects = CustomUserManager()\n\n USERNAME_FIELD = 'phone'\n REQUIRED_FIELDS = []\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n constraints = [\n UniqueConstraint(\n fields=['user_1C_code'], condition=~Q(user_1C_code=None),\n name='unique_user_1C_code_exp_null')\n ]\n\n def __str__(self):\n return f'{self.phone} {self.first_name}'\n\n\nclass City(models.Model):\n title = models.CharField(max_length=200, verbose_name='Город')\n\n class Meta:\n verbose_name = 'Город'\n verbose_name_plural = 'Города'\n\n def __str__(self):\n return self.title\n" }, { "alpha_fraction": 0.5478395223617554, "alphanum_fraction": 0.5941358208656311, "avg_line_length": 27.173913955688477, "blob_id": "9b922baafb529aedd62b76901605497d942c0ee3", "content_id": "e7cdee1ca40ff80dc53c3fa925fe13cf89330c62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "no_license", "max_line_length": 109, "num_lines": 23, "path": "/apps/check/migrations/0002_auto_20210415_1834.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-15 12:34\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('check', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='check',\n name='filial_1c_code',\n field=models.CharField(max_length=255, null=True, verbose_name='Уникальный 1C код филиала'),\n ),\n migrations.AddField(\n model_name='check',\n name='user_1c_code',\n field=models.CharField(max_length=255, null=True, verbose_name='Уникальный 1C код пользователя'),\n ),\n ]\n" }, { "alpha_fraction": 0.5583333373069763, "alphanum_fraction": 0.574999988079071, "avg_line_length": 30.578947067260742, "blob_id": "38aa0a0df724d6f1b9f11c156f5302a19d7f5db8", "content_id": "96187b27feef11c8be3d47095082693f031fcc2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1262, "license_type": "no_license", "max_line_length": 98, "num_lines": 38, "path": "/apps/brand/migrations/0002_auto_20210329_2332.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-03-29 17:32\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='brandimage',\n name='is_main',\n field=models.BooleanField(default=False, verbose_name='Основная?'),\n ),\n migrations.AlterField(\n model_name='filial',\n name='end_work',\n field=models.TimeField(blank=True, null=True, verbose_name='Конец рабочего времени'),\n ),\n migrations.AlterField(\n model_name='filial',\n name='start_work',\n field=models.TimeField(blank=True, null=True, verbose_name='Начало рабочего времени'),\n ),\n migrations.AlterField(\n model_name='filialimage',\n name='is_main',\n field=models.BooleanField(default=False, verbose_name='Основная?'),\n ),\n migrations.AlterField(\n model_name='filialphone',\n name='is_whatsapp',\n field=models.BooleanField(default=True, verbose_name='Номер Whatsapp?'),\n ),\n ]\n" }, { "alpha_fraction": 0.5707547068595886, "alphanum_fraction": 0.5770440101623535, "avg_line_length": 27.909090042114258, "blob_id": "07d2c02a7ffba2928c4f2eb9e0e24887c5e5c812", "content_id": "b413587c02482428816d6b6b3b56877058b37e60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 636, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/apps/integration/urls.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import path, include\n\nfrom apps.integration.views import (\n Auth1cAPIView, GetUserAPIView, CreateCheckAPIView, UpdateCheckAPIView\n)\n\nurlpatterns = [\n path('user/', include([\n path('login/', Auth1cAPIView.as_view(), name='login-1c'),\n path(\n '<str:qr_code>/', GetUserAPIView.as_view(),\n name='get_user_by_qr_code'\n ),\n ])),\n path('check/', include([\n path('', CreateCheckAPIView.as_view(), name='create_check'),\n path(\n '<str:unique_1c_check_code>/', UpdateCheckAPIView.as_view(),\n name='update_check_view'\n ),\n ])),\n]\n" }, { "alpha_fraction": 0.5673892498016357, "alphanum_fraction": 0.5890669226646423, "avg_line_length": 31.15151596069336, "blob_id": "571dcedcf102294f6c17f9856ed173ca58acbdd7", "content_id": "67f3066859b3668c829826df7c07dcfeae0b2296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 107, "num_lines": 33, "path": "/apps/account/migrations/0002_auto_20210330_1214.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-03-30 06:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='confirmation_code',\n field=models.CharField(blank=True, max_length=6, null=True, verbose_name='confirmation code'),\n ),\n migrations.AddField(\n model_name='user',\n name='confirmation_date',\n field=models.DateTimeField(blank=True, null=True, verbose_name='confirmation date'),\n ),\n migrations.AddField(\n model_name='user',\n name='is_registration_finish',\n field=models.BooleanField(default=False, verbose_name='is_registration_finish'),\n ),\n migrations.AddField(\n model_name='user',\n name='tmp_phone',\n field=models.CharField(blank=True, max_length=25, null=True, verbose_name='Временный телефон'),\n ),\n ]\n" }, { "alpha_fraction": 0.7275132536888123, "alphanum_fraction": 0.7275132536888123, "avg_line_length": 24.200000762939453, "blob_id": "a74fb7c32a38d9aa2f3b8072ded2dedc2a0a2a3e", "content_id": "e7bca65187d5227926c087a93373387ca149fc4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 50, "num_lines": 15, "path": "/apps/setting/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework import generics\n\nfrom .models import AppVersion\nfrom .serializers import AppVersionSerializer\n\n\nclass AppVersionAPIView(generics.RetrieveAPIView):\n \"\"\"\n API view for app version control\n \"\"\"\n queryset = AppVersion.objects.all()\n serializer_class = AppVersionSerializer\n\n def get_object(self):\n return self.get_queryset().first()\n" }, { "alpha_fraction": 0.5736150145530701, "alphanum_fraction": 0.5802974700927734, "avg_line_length": 49.978023529052734, "blob_id": "07aede4e0e3fa96111a5fb6ec3947a9218c408a4", "content_id": "5c90f782a98fd6e35f2f1a97d0022144fbac8363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4956, "license_type": "no_license", "max_line_length": 163, "num_lines": 91, "path": "/apps/brand/migrations/0001_initial.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2 on 2021-03-29 07:58\n\nimport ckeditor_uploader.fields\nimport core.utils\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django_2gis_maps.fields\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Brand',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(blank=True, max_length=255, null=True, verbose_name='Название')),\n ('logo', models.ImageField(blank=True, null=True, upload_to=core.utils.generate_filename, verbose_name='Лого')),\n ('description', ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Описание')),\n ('address', models.CharField(blank=True, max_length=50, null=True, verbose_name='Адрес')),\n ('link', models.URLField(blank=True, null=True, verbose_name='Ссылка')),\n ],\n options={\n 'verbose_name': 'Бренд',\n 'verbose_name_plural': 'Бренды',\n },\n ),\n migrations.CreateModel(\n name='Filial',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='Название')),\n ('address', django_2gis_maps.fields.AddressField(max_length=200, verbose_name='Адрес')),\n ('geolocation', django_2gis_maps.fields.GeoLocationField()),\n ('start_work', models.TimeField(auto_now_add=True, verbose_name='Начало рабочего времени')),\n ('end_work', models.TimeField(auto_now_add=True, verbose_name='Конец рабочего времени')),\n ('is_around_the_clock', models.BooleanField(default=False, verbose_name='Круглосуточно?')),\n ('description', ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Описание')),\n ('link', models.URLField(blank=True, null=True, verbose_name='Ссылка')),\n ],\n options={\n 'verbose_name': 'Филиал',\n 'verbose_name_plural': 'Филиалы',\n },\n ),\n migrations.CreateModel(\n name='FilialPhone',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('phone', models.CharField(max_length=255, verbose_name='Номер телефона')),\n ('is_phone', models.BooleanField(default=True, verbose_name='Номер телефона?')),\n ('is_whatsapp', models.BooleanField(default=True, verbose_name='Номер Whatsapp')),\n ('filial', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='brand.Filial', verbose_name='Филиал')),\n ],\n options={\n 'verbose_name': 'Номер филиала',\n 'verbose_name_plural': 'Номера филиала',\n },\n ),\n migrations.CreateModel(\n name='FilialImage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.ImageField(upload_to=core.utils.generate_filename, verbose_name='Изображение')),\n ('is_main', models.BooleanField(default=False, verbose_name='Основная')),\n ('filial', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='brand.Filial', verbose_name='Филиал')),\n ],\n options={\n 'verbose_name': 'Изображение филиала',\n 'verbose_name_plural': 'Изображения филиала',\n },\n ),\n migrations.CreateModel(\n name='BrandImage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.ImageField(upload_to=core.utils.generate_filename, verbose_name='Изображение')),\n ('is_main', models.BooleanField(default=False, verbose_name='Основная')),\n ('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='brand.Brand', verbose_name='Бренд')),\n ],\n options={\n 'verbose_name': 'Изображение бренда',\n 'verbose_name_plural': 'Изображения бренда',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6111757755279541, "alphanum_fraction": 0.6484283804893494, "avg_line_length": 34.79166793823242, "blob_id": "314c43d4e712bfaa2b229899a0caca2ab8616809", "content_id": "fc88f3afa44b49fbbb88dca092f0bbd708ec2abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 877, "license_type": "no_license", "max_line_length": 189, "num_lines": 24, "path": "/apps/notifications/migrations/0003_auto_20210428_1419.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-28 08:19\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('notifications', '0002_auto_20210428_1228'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='notification',\n name='linked_article',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notice', to='info.PromotionAndNews', verbose_name='Новость или Акция'),\n ),\n migrations.AlterField(\n model_name='notification',\n name='linked_check',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notice', to='check.Check', verbose_name='Чек'),\n ),\n ]\n" }, { "alpha_fraction": 0.5684830546379089, "alphanum_fraction": 0.61561119556427, "avg_line_length": 31.33333396911621, "blob_id": "32728d18d3ccf5d8d5360748c04ff460b8d85a1e", "content_id": "f8ff25772dfc4d46b69ba8be193f5a3f4530aa97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 150, "num_lines": 21, "path": "/apps/info/migrations/0004_auto_20210406_1501.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-06 09:01\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0003_auto_20210331_1540'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='promotionandnews',\n options={'ordering': ['-created_at'], 'verbose_name': 'Акция и новость', 'verbose_name_plural': 'Акции и новости'},\n ),\n migrations.AlterModelOptions(\n name='promotionandnewsimage',\n options={'ordering': ['-is_main'], 'verbose_name': 'Фотография для акции/новости', 'verbose_name_plural': 'Фотографии для акций/новости'},\n ),\n ]\n" }, { "alpha_fraction": 0.49470898509025574, "alphanum_fraction": 0.579365074634552, "avg_line_length": 20, "blob_id": "1a7ebd89564769aed6155579c80c7523b7873791", "content_id": "afd24ceaab6ef0316a5bc332ad3759ce3ab42954", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/apps/info/migrations/0003_auto_20210331_1540.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-03-31 09:40\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('info', '0002_auto_20210329_1451'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='promotionandnews',\n old_name='create_at',\n new_name='created_at',\n ),\n ]\n" }, { "alpha_fraction": 0.6715750694274902, "alphanum_fraction": 0.6718380451202393, "avg_line_length": 31.22881317138672, "blob_id": "e2ef139f012776fba9fd89fbfc2b038ed86248bc", "content_id": "b311ff45ef4493d228d7994cda91c565ba6bafae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3803, "license_type": "no_license", "max_line_length": 93, "num_lines": 118, "path": "/apps/brand/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from drf_yasg.utils import swagger_serializer_method\nfrom rest_framework import serializers\n\nfrom apps.brand.models import (\n Brand, BrandImage, FilialImage, FilialPhone, Filial\n)\nfrom apps.brand.service import FilialService, WorkDayService\n\n\nclass BrandListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Brand\n fields = ('id', 'logo')\n\n\nclass BrandImageSerializer(serializers.ModelSerializer):\n class Meta:\n model = BrandImage\n fields = ('id', 'image')\n\n\nclass BrandDetailSerializer(serializers.ModelSerializer):\n images = BrandImageSerializer(many=True, required=False)\n\n class Meta:\n model = Brand\n fields = ('title', 'description', 'address', 'link', 'images')\n\n\nclass FilialImageSerializer(serializers.ModelSerializer):\n class Meta:\n model = FilialImage\n fields = ('id', 'image', 'is_main')\n\n\nclass FilialPhoneSerializer(serializers.ModelSerializer):\n class Meta:\n model = FilialPhone\n fields = ('id', 'phone', 'is_phone', 'is_whatsapp')\n\n\nclass GeolocationSerializer(serializers.Serializer):\n lat = serializers.FloatField()\n long = serializers.FloatField()\n\n\nclass FilialSerializer(serializers.ModelSerializer):\n images = FilialImageSerializer(many=True, required=False)\n phone_numbers = FilialPhoneSerializer(many=True, required=False)\n is_filial_open = serializers.SerializerMethodField()\n distance = serializers.SerializerMethodField()\n geolocation = serializers.SerializerMethodField()\n week_days = serializers.SerializerMethodField()\n\n class Meta:\n model = Filial\n fields = (\n 'title', 'address', 'geolocation', 'distance', 'images',\n 'phone_numbers', 'is_filial_open', 'week_days',\n )\n\n def get_is_filial_open(self, obj) -> bool:\n return FilialService.check_filial_status(obj)\n\n def get_distance(self, obj) -> float:\n client_geolocation = self.context.get('client_geolocation')\n\n return FilialService.calculate_distance(\n filial_geolocation=obj.geolocation,\n client_geolocation=client_geolocation\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.ListField)\n def get_week_days(self, obj):\n data = WorkDayService.get_weekday(obj)\n return data\n\n @swagger_serializer_method(serializer_or_field=GeolocationSerializer)\n def get_geolocation(self, obj):\n if obj.geolocation:\n lat, long = tuple(map(float, obj.geolocation.split(',')))\n data = {'lat': lat, 'long': long}\n serializer = GeolocationSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n return serializer.data\n\n return None\n\n\nclass FilialListSerializer(serializers.ModelSerializer):\n image = serializers.SerializerMethodField()\n is_filial_open = serializers.SerializerMethodField()\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model = Filial\n fields = (\n 'position', 'id', 'title', 'address', 'distance',\n 'is_filial_open', 'image'\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.ImageField)\n def get_image(self, obj):\n image_obj = obj.images.all()\n request = self.context['request']\n image_url = request.build_absolute_uri(image_obj[0].image.url) if image_obj else None\n return image_url\n\n def get_is_filial_open(self, obj) -> bool:\n return FilialService.check_filial_status(obj)\n\n def get_distance(self, obj) -> float:\n client_geolocation = self.context.get('client_geolocation')\n\n return FilialService.calculate_distance(\n filial_geolocation=obj.geolocation,\n client_geolocation=client_geolocation\n )\n" }, { "alpha_fraction": 0.5220338702201843, "alphanum_fraction": 0.5779660940170288, "avg_line_length": 25.81818199157715, "blob_id": "e60492f9c041555c2a51ddd2d705430116030ec8", "content_id": "e33c8481c804b7cb9d0c00f69a25e7aec56b1846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 105, "num_lines": 22, "path": "/apps/brand/migrations/0010_auto_20210512_1145.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-05-12 05:45\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0009_auto_20210426_1104'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='brand',\n options={'ordering': ['position'], 'verbose_name': 'Бренд', 'verbose_name_plural': 'Бренды'},\n ),\n migrations.AddField(\n model_name='brand',\n name='position',\n field=models.PositiveIntegerField(default=0, verbose_name='№'),\n ),\n ]\n" }, { "alpha_fraction": 0.6188026070594788, "alphanum_fraction": 0.6337698698043823, "avg_line_length": 53.82051467895508, "blob_id": "41eb8c13a202f7921f7d7346fa9181604775e630", "content_id": "8eae8bfec494bbdda50837859e48bb8de79c3d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2298, "license_type": "no_license", "max_line_length": 169, "num_lines": 39, "path": "/apps/check/migrations/0001_initial.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-12 11:38\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('brand', '0007_filial_unique_1c_filial_code'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Check',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('unique_1c_check_code', models.CharField(max_length=255, unique=True, verbose_name='Уникальный 1C код чека')),\n ('money_paid', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Оплачено деньгами')),\n ('bonus_paid', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Оплачено бонусами')),\n ('total_paid', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Сумма оплаты')),\n ('accrued_point', models.PositiveIntegerField(blank=True, null=True, verbose_name='Начислено бонусов')),\n ('accrued_point_date', models.DateTimeField(blank=True, null=True, verbose_name='Дата начисления')),\n ('withdrawn_point', models.PositiveIntegerField(blank=True, null=True, verbose_name='Снято бонусов (Возврат)')),\n ('withdrawn_point_date', models.DateTimeField(blank=True, null=True, verbose_name='Дата возврата')),\n ('is_active', models.BooleanField(default=True, verbose_name='Активность чека')),\n ('filial', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='users', to='brand.Filial', verbose_name='Филиал')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users', to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),\n ],\n options={\n 'verbose_name': 'Чек',\n 'verbose_name_plural': 'Чеки',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5784270167350769, "alphanum_fraction": 0.5877231955528259, "avg_line_length": 28.46521759033203, "blob_id": "bdcb6e3ac10adf90c275978c97c8dd68afc6d6b4", "content_id": "70e7d69c0e2c43ae325ef4ededc2ce09e378b9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7005, "license_type": "no_license", "max_line_length": 86, "num_lines": 230, "path": "/apps/integration/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import datetime\nimport json\nimport requests\nfrom requests.auth import HTTPBasicAuth\nfrom requests.exceptions import Timeout\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom rest_framework import status, serializers, exceptions\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nfrom apps.account.models import User\nfrom apps.brand.models import Filial\nfrom apps.integration.serializers import Sync1cUserSerializer\nfrom apps.setting.models import Setting\n\n\nclass User1cAuthService:\n @classmethod\n def get_response(cls, serializer) -> Response:\n \"\"\"Method для login пользователя 1С\"\"\"\n user = serializer.user\n\n token = cls.create_or_refresh_user_token(user)\n from apps.integration.serializers import (\n Login1cAPIViewResponseSerializer\n )\n response = Login1cAPIViewResponseSerializer({\n 'token': token.key,\n }).data\n return Response(\n response,\n status=status.HTTP_200_OK,\n )\n\n @staticmethod\n def create_or_refresh_user_token(user: User) -> Token:\n token, created = Token.objects.get_or_create(user=user)\n\n return token\n\n\nclass CreateCheckService:\n @classmethod\n def response_user_1c_code(cls, serializer, user):\n if cls.check_qr_code_expiration_date(user):\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(\n {'message': 'Устарел QR код пользователя'},\n status=status.HTTP_400_BAD_REQUEST\n )\n\n @staticmethod\n def get_user_by_qr_code(qr_code):\n user = None\n if qr_code:\n try:\n user = User.objects.get(qr_code=qr_code)\n except User.DoesNotExist:\n pass\n\n return user\n\n @staticmethod\n def check_qr_code_expiration_date(user):\n setting = Setting.objects.first()\n exp_date_limit = (\n setting.qr_code_expiration_date\n if setting else datetime.timedelta(minutes=3)\n )\n\n return timezone.now() - user.qr_code_updated_at <= exp_date_limit\n\n @staticmethod\n def get_user_and_filial_from_serializer(validated_data):\n try:\n user = User.objects.get(\n user_1C_code=validated_data['user_1c_code']\n )\n except User.DoesNotExist:\n raise serializers.ValidationError(\n {'user_1c_code': 'Пользователь не найден'}\n )\n try:\n filial = Filial.objects.get(\n filial_1c_code=validated_data['filial_1c_code']\n )\n except Filial.DoesNotExist:\n raise serializers.ValidationError(\n {'filial_1c_code': 'Филиал не найден'}\n )\n\n return user, filial\n\n\nREQUEST_PARAMS = {\n \"auth\": HTTPBasicAuth(settings.USER_1C['username'], settings.USER_1C['password']),\n \"headers\": {'Content-Type': 'application/json'},\n \"timeout\": 3\n}\n\n\nclass User1cUpdateService:\n @classmethod\n def update_1c_user_id(cls, user):\n serialized_user = Sync1cUserSerializer(user).data\n response = cls.send_user_to_1c(serialized_user)\n response_data = cls.check_response(response, user)\n\n user.user_1C_code = response_data['unique_1c_user_code']\n user.save(update_fields=['user_1C_code'])\n\n @classmethod\n def check_response(cls, response, user):\n if response.status_code not in (200, 201):\n cls.clean_user_sign_up_data(user)\n raise exceptions.NotAcceptable(\n '1С сервер временно недоступен'\n )\n response_data = json.loads(response.text)\n if not response_data.get('unique_1c_user_code'):\n cls.clean_user_sign_up_data(user)\n raise exceptions.ValidationError(\n 'Не верный формат данных из 1С сервера'\n )\n\n return response_data\n\n @staticmethod\n def send_user_to_1c(data):\n try:\n response = requests.post(\n settings.LINKS_1C['SYNC_USER_URL'],\n data=json.dumps(data),\n **REQUEST_PARAMS\n )\n except Timeout:\n raise exceptions.NotAcceptable(\n '1С сервер не отвечает'\n )\n\n return response\n\n @staticmethod\n def clean_user_sign_up_data(user):\n user.first_name = ''\n user.last_name = ''\n user.birth_date = None\n user.city = None\n user.save(update_fields=[\n 'first_name', 'last_name', 'birth_date', 'city'\n ])\n\n\nclass UserGetWalletDataService:\n @classmethod\n def update_user_wallet_data(cls, user):\n response_data = cls.get_user_wallet_data(user)\n return response_data\n\n @staticmethod\n def get_user_wallet_data(user):\n response_error_data = {\n \"active_point\": '-',\n \"inactive_point\": '-',\n \"discount\": '-'\n }\n\n try:\n response = requests.get(\n settings.LINKS_1C['GET_USER_WALLET_DATA_URL'],\n params={'unique_1c_user_code': user.user_1C_code},\n **REQUEST_PARAMS\n )\n except Timeout:\n return response_error_data\n\n if response.status_code not in (200, 201):\n return response_error_data\n\n response_data = json.loads(response.text)\n if hasattr(response_data, 'err_text'):\n return response_error_data\n\n return response_data\n\n\nclass User1CNumberChangeService:\n @classmethod\n def sync_user_phone(cls, user):\n response = cls.send_user_phone(user)\n return cls.check_response(response)\n\n @staticmethod\n def send_user_phone(user):\n data = {\n 'new_phone': user.tmp_phone,\n 'unique_1c_user_code': user.user_1C_code,\n }\n\n try:\n response = requests.post(\n settings.LINKS_1C['CHANGE_USER_NUMBER'],\n data=json.dumps(data),\n **REQUEST_PARAMS\n )\n except Timeout:\n raise exceptions.NotAcceptable(\n '1С сервер не отвечает'\n )\n\n return response\n\n @classmethod\n def check_response(cls, response):\n if response.status_code != status.HTTP_200_OK:\n return False, 'Номер не изменен. 1C сервер не доступен'\n\n response_data = json.loads(response.text)\n response_is_not_success = (\n hasattr(response_data, 'err_text') or\n not response_data.get('is_changed')\n )\n if response_is_not_success:\n return False, 'Номер не изменен. Ошибка при синхронизации с 1C'\n\n return True, response_data\n" }, { "alpha_fraction": 0.6603849530220032, "alphanum_fraction": 0.6611868739128113, "avg_line_length": 29.790122985839844, "blob_id": "33c4574c7085cc8a95fb61939633fa2cadd4cd62", "content_id": "227d86d7fd821b70e2adbf87939d076727b3f2b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2553, "license_type": "no_license", "max_line_length": 79, "num_lines": 81, "path": "/apps/check/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom rest_framework import serializers\n\nfrom drf_yasg.utils import swagger_serializer_method\n\nfrom apps.account.models import User\nfrom apps.brand.models import Filial\nfrom apps.brand.serializers import FilialImageSerializer\nfrom apps.check.models import Check\nfrom apps.setting.models import Setting\nfrom apps.notifications.models import Notification\n\n\nclass QRCodeSerializer(serializers.ModelSerializer):\n \"\"\"\n Сериализатор для QR code\n Если не найден объект Setting или не указано exp date -\n по умолчанию 3 мин\n \"\"\"\n expiration_date = serializers.SerializerMethodField()\n\n def get_expiration_date(self, obj):\n setting = Setting.objects.first()\n if setting and setting.qr_code_expiration_date:\n return setting.qr_code_expiration_date\n\n return datetime.timedelta(minutes=3)\n\n class Meta:\n model = User\n fields = ('qr_code', 'expiration_date')\n extra_kwargs = {\n 'qr_code': {'required': True},\n 'expiration_date': {'required': True},\n }\n\n\nclass FilialListCheckSerializer(serializers.ModelSerializer):\n class Meta:\n model = Filial\n fields = ('id', 'title', 'address')\n\n\nclass FilialDetailCheckSerializer(serializers.ModelSerializer):\n images = FilialImageSerializer(many=True, required=False)\n\n class Meta:\n model = Filial\n fields = ('id', 'title', 'address', 'images')\n\n\nclass CheckListSerializer(serializers.ModelSerializer):\n filial = FilialListCheckSerializer()\n\n class Meta:\n model = Check\n fields = (\n 'id', 'filial', 'accrued_point', 'accrued_point_date',\n 'withdrawn_point', 'withdrawn_point_date', 'status'\n )\n\n\nclass CheckDetailSerializer(serializers.ModelSerializer):\n filial = FilialDetailCheckSerializer()\n badge_count = serializers.SerializerMethodField()\n\n class Meta:\n model = Check\n fields = (\n 'id', 'filial', 'money_paid', 'bonus_paid', 'total_paid',\n 'accrued_point', 'accrued_point_date', 'withdrawn_point',\n 'withdrawn_point_date', 'is_active', 'status',\n 'is_on_credit', 'balance_owed', 'due_date', 'badge_count',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.IntegerField)\n def get_badge_count(self, obj):\n user = self.context['request'].user\n count = Notification.objects.filter(user=user, is_viewed=False).count()\n return count\n" }, { "alpha_fraction": 0.5265823006629944, "alphanum_fraction": 0.5848101377487183, "avg_line_length": 20.94444465637207, "blob_id": "9998624eaadb2304058f07caf0740bbd895fc15f", "content_id": "ca828bd064e90cda4d08a021488519b36f5c6f85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/apps/brand/migrations/0008_auto_20210415_1834.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-15 12:34\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('brand', '0007_filial_unique_1c_filial_code'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='filial',\n old_name='unique_1c_filial_code',\n new_name='filial_1c_code',\n ),\n ]\n" }, { "alpha_fraction": 0.6787401437759399, "alphanum_fraction": 0.6976377964019775, "avg_line_length": 23.423076629638672, "blob_id": "b6b18e3442234a8d9debccc73979e084f8f3fd66", "content_id": "6231ce16549b0af130700bb9b2db652ab2df80db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "no_license", "max_line_length": 61, "num_lines": 26, "path": "/apps/account/tests/factories.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import factory\nfrom django.contrib.auth import get_user_model\n\nfrom apps.account.models import City\n\nUser = get_user_model()\n\n\nclass CityFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = City\n\n title = factory.Faker('city')\n\n\nclass UserFactory(factory.django.DjangoModelFactory):\n phone = factory.Sequence(lambda x: '+9967001112%02d' % x)\n is_registration_finish = False\n is_active = True\n first_name = factory.Faker('first_name')\n last_name = factory.Faker('last_name')\n birth_date = factory.Faker('date')\n city = factory.SubFactory(CityFactory)\n\n class Meta:\n model = User\n" }, { "alpha_fraction": 0.6439215540885925, "alphanum_fraction": 0.6537255048751831, "avg_line_length": 34.41666793823242, "blob_id": "c4100e31b8eea495d6c5720cc764d868bf92a468", "content_id": "bec984df314b15cd90d4a5baf90e8607642f106b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5117, "license_type": "no_license", "max_line_length": 82, "num_lines": 144, "path": "/apps/info/tests/test_views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom apps.info.models import (\n Banner,\n ProgramCondition,\n Contact, PromotionAndNews,\n)\nfrom .factories import (\n BannerFactory,\n ProgramConditionFactory,\n ContactFactory,\n PromotionAndNewsImageFactory,\n PromotionAndNewsFactory,\n)\n\n\nclass BannerAndPromotionTest(APITestCase):\n\n def setUp(self) -> None:\n self.banner = BannerFactory()\n self.url = reverse('v1:banner-promotions')\n\n def test_get_banner(self) -> None:\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn(self.banner.title, response.data['banner']['title'])\n\n def test_get_banner_on_empty_db_table(self) -> None:\n Banner.objects.all().delete()\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['banner'], None)\n self.assertEqual(response.data['promotion'], [])\n\n\nclass BannerTest(APITestCase):\n\n def setUp(self) -> None:\n self.banner = BannerFactory()\n self.url = reverse('v1:banner-detail')\n\n def test_get_banner(self) -> None:\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn(response.data['title'], self.banner.title)\n self.assertIn(\n response.data['description'], self.banner.description\n )\n\n def test_get_banner_on_empty_db_table(self) -> None:\n Banner.objects.all().delete()\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn(response.data['title'], '')\n self.assertIn(\n response.data['description'], ''\n )\n\n\nclass ProgramConditionTest(APITestCase):\n\n def setUp(self) -> None:\n self.program_condition = ProgramConditionFactory()\n self.url = reverse('v1:program_condition')\n\n def test_get_program_condition(self) -> None:\n response = self.client.get(self.url)\n expected_data = {\n 'id': 1,\n 'title': self.program_condition.title,\n 'description': self.program_condition.description\n }\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, expected_data)\n\n def test_get_program_condition_on_empty_db_table(self) -> None:\n ProgramCondition.objects.all().delete()\n response = self.client.get(self.url)\n expected_data = {\n 'title': '',\n 'description': '',\n }\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, expected_data)\n\n\nclass TestContactListAPIView(APITestCase):\n\n def setUp(self) -> None:\n self.insta = ContactFactory()\n self.vk = ContactFactory()\n self.url = reverse('v1:contacts')\n\n def test_get_contacts(self) -> None:\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn(self.insta.title, response.data[0]['title'])\n self.assertIn(self.vk.title, response.data[1]['title'])\n\n def test_get_contacts_on_empty_db_table(self) -> None:\n Contact.objects.all().delete()\n response = self.client.get(self.url)\n expected_data = []\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, expected_data)\n\n\nclass PromotionAndNewsListTest(APITestCase):\n def setUp(self) -> None:\n self.article = PromotionAndNewsImageFactory()\n self.url = reverse('v1:promotions-news')\n\n def test_get_promotion_and_news(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(\n self.article.information.title,\n response.data['results'][0]['title']\n )\n\n def test_get_promotions_news_list_on_empty_db_table(self):\n PromotionAndNews.objects.all().delete()\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['results'], [])\n\n\nclass PromotionAndNewsDetail(APITestCase):\n def setUp(self) -> None:\n self.article = PromotionAndNewsFactory()\n\n def test_get_promotions_and_news_detail(self):\n url = reverse('v1:promotions-news-detail', kwargs={'pk': self.article.id})\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['title'], self.article.title)\n\n def test_get_promotions_and_news_detail_on_empty_db_table(self):\n url = reverse('v1:promotions-news-detail', kwargs={'pk': 260})\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n self.assertEqual(response.data['detail'], 'Страница не найдена.')\n" }, { "alpha_fraction": 0.7872670888900757, "alphanum_fraction": 0.7872670888900757, "avg_line_length": 32.894737243652344, "blob_id": "843886451f794aded9ad2771d4f6ceb6221eb8d2", "content_id": "2290e2cc898c3c4ae936e90eb7fdc54bd160fa62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "no_license", "max_line_length": 79, "num_lines": 19, "path": "/apps/notifications/views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework import generics\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom apps.notifications.models import Notification\nfrom apps.notifications.pagination import LargeListNotificationPagination\nfrom apps.notifications.serializers import NotificationSerializer\n\n\nclass NotificationAPIView(generics.ListAPIView):\n serializer_class = NotificationSerializer\n pagination_class = LargeListNotificationPagination\n permission_classes = (IsAuthenticated,)\n\n def get_queryset(self):\n queryset = (\n Notification.objects.filter(is_active=True, user=self.request.user)\n )\n\n return queryset\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6261160969734192, "avg_line_length": 26.15151596069336, "blob_id": "9e0e806a99fd1feb5871d5c015b3e0846ebff7a2", "content_id": "cf0d2d845300de127a58373c7d5b8e01c57ad328", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 896, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/apps/check/service.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import uuid\nimport datetime\n\nfrom apps.notifications.tasks import save_notification_and_send_fcm_for_check\n\n\nclass QRCodeService:\n @staticmethod\n def generate_qr_code():\n unique_code = uuid.uuid4().int\n\n return unique_code\n\n @classmethod\n def update_user_data(cls, user):\n user.qr_code = cls.generate_qr_code()\n user.qr_code_updated_at = datetime.datetime.now()\n user.save(update_fields=['qr_code', 'qr_code_updated_at'])\n\n return user\n\n\nclass CheckNotificationService:\n @classmethod\n def send_notification(cls, check, user):\n body = {\n 'object_id': check.id,\n 'title': str(check.filial),\n 'status': check.status,\n 'accrued_point': check.accrued_point,\n 'withdrawn_point': check.withdrawn_point,\n }\n save_notification_and_send_fcm_for_check(body, user, check)\n" }, { "alpha_fraction": 0.6415441036224365, "alphanum_fraction": 0.6415441036224365, "avg_line_length": 24.904762268066406, "blob_id": "e712387c85e6d070e76fc72251435b954c51d089", "content_id": "bb5cd5cce05a264a6fb867186421d03039c8b7cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 56, "num_lines": 21, "path": "/apps/setting/serializers.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom .models import AppVersion\n\n\nclass AppVersionSerializer(serializers.ModelSerializer):\n class Meta:\n model = AppVersion\n fields = (\n 'android_version',\n 'android_force_update',\n 'ios_build_number',\n 'ios_version',\n 'ios_force_update',\n )\n\n\nclass HelpPageSerializer(serializers.Serializer):\n \"\"\"Serializer for help page\"\"\"\n title = serializers.CharField(required=True)\n text = serializers.CharField(required=True)\n" }, { "alpha_fraction": 0.6232837438583374, "alphanum_fraction": 0.6281464695930481, "avg_line_length": 24.33333396911621, "blob_id": "58e7efef8e82a6a798d5fb9f99771479b35c55be", "content_id": "6174057df85463c747485d742ec4a88de0dc5c1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3922, "license_type": "no_license", "max_line_length": 76, "num_lines": 138, "path": "/apps/info/models.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nfrom django.db import models\n\nfrom solo.models import SingletonModel\nfrom ckeditor_uploader.fields import RichTextUploadingField\n\nfrom core.constants import INFORMATION_TYPE, NEWS\nfrom core.utils import generate_filename\n\n\nclass Banner(SingletonModel):\n title = models.CharField(\n max_length=25,\n verbose_name='Заголовок баннера',\n )\n image = models.ImageField(\n upload_to=generate_filename,\n verbose_name='Фото баннера',\n )\n description = RichTextUploadingField(\n verbose_name='Описание баннера',\n )\n\n class Meta:\n verbose_name_plural = 'Баннера'\n verbose_name = 'Баннер'\n\n def __str__(self):\n return f'{self.title}'\n\n\nclass ProgramCondition(SingletonModel):\n title = models.CharField(\n max_length=50,\n verbose_name='Заголовок программы лояльности',\n )\n description = RichTextUploadingField(\n verbose_name='Текст программы лояльности',\n )\n\n class Meta:\n verbose_name_plural = 'Программы лояльности'\n verbose_name = 'Программа лояльности'\n\n def __str__(self):\n return f'{self.title}'\n\n\nclass ContactIcon(models.Model):\n title = models.CharField(max_length=70, verbose_name='Заголовок иконки')\n image = models.ImageField(\n upload_to=generate_filename,\n verbose_name='Фото иконки для контактов',\n )\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = 'Иконка для контактов'\n verbose_name_plural = 'Иконки для контактов'\n\n\nclass Contact(models.Model):\n icon_image = models.ForeignKey(\n 'ContactIcon',\n on_delete=models.CASCADE,\n related_name='contacts',\n verbose_name='Иконка',\n )\n title = models.CharField(\n max_length=100,\n verbose_name='Заголовок ссылки',\n )\n link = models.CharField(\n max_length=150,\n verbose_name='Ссылка',\n )\n\n class Meta:\n verbose_name_plural = 'Контакты'\n verbose_name = 'Контакт'\n\n def __str__(self):\n return f'{self.title} {str(self.icon_image)}'\n\n\nclass PromotionAndNews(models.Model):\n created_at = models.DateTimeField(\n default=datetime.now, verbose_name=\"Дата публикации\",\n )\n information_type = models.CharField(\n max_length=15,\n choices=INFORMATION_TYPE,\n default=NEWS,\n verbose_name='Тип записи',\n )\n title = models.CharField(\n max_length=100,\n verbose_name='Заголовок',\n )\n description = RichTextUploadingField(\n verbose_name='Текст статьи',\n )\n is_active = models.BooleanField(\n default=True,\n verbose_name='Активный(Вкл/Выкл)',\n )\n\n class Meta:\n verbose_name_plural = 'Акции и новости'\n verbose_name = 'Акция и новость'\n ordering = ['-created_at']\n\n def __str__(self):\n return f'{self.title} {self.information_type}'\n\n\nclass PromotionAndNewsImage(models.Model):\n image = models.ImageField(\n upload_to=generate_filename,\n verbose_name='Фото новости или акции',\n )\n is_main = models.BooleanField(\n default=False,\n verbose_name='Превью(Вкл/Выкл)',\n )\n information = models.ForeignKey(\n 'PromotionAndNews',\n on_delete=models.CASCADE,\n related_name=\"images\"\n )\n\n class Meta:\n verbose_name_plural = 'Фотографии для акций/новости'\n verbose_name = 'Фотография для акции/новости'\n ordering = ['-is_main']\n" }, { "alpha_fraction": 0.6600000262260437, "alphanum_fraction": 0.671999990940094, "avg_line_length": 18.230770111083984, "blob_id": "40dfeadc9c378ebcafb4754b58d51460eef562b4", "content_id": "be5baa8a72ffbe3e083e9474d5ae4c6000fa7650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 64, "num_lines": 26, "path": "/core/settings/local.example.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "import environ\nfrom rest_framework import permissions\n\nenv = environ.Env()\n\n\nSECRET_KEY = env.str('DJANGO_SECRET_KEY', default='not secret)')\n\nDEBUG = env.bool('DJANGO_DEBUG', default=True)\n\nDATABASES = {\n 'default': env.db(\n 'DATABASE_URL', default='sqlite:///db.sqlite'\n )\n}\n\nALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['*'])\n\nif DEBUG:\n API_PERMISSION = permissions.AllowAny\nelse:\n API_PERMISSION = permissions.IsAuthenticated\n\nINTERNAL_IPS = [\n '127.0.0.1',\n]\n" }, { "alpha_fraction": 0.6132625937461853, "alphanum_fraction": 0.624403178691864, "avg_line_length": 49.945945739746094, "blob_id": "051fb29dd4b6998f975188817b7a62caebb78f9a", "content_id": "aea81bcde7f72883058ad79c22ce9266bebee8e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2039, "license_type": "no_license", "max_line_length": 261, "num_lines": 37, "path": "/apps/notifications/migrations/0001_initial.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.16 on 2021-04-21 09:24\n\nfrom django.conf import settings\nimport django.contrib.postgres.fields.jsonb\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Notification',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Создано')),\n ('updated_at', models.DateTimeField(auto_now=True, null=True, verbose_name='Обновлено')),\n ('notice_type', models.CharField(choices=[('bonus_accrued', 'Начислено бонусов'), ('bonus_paid', 'Снято бонусов'), ('bonus_withdraw', 'Снято бонусов неактивных'), ('promotion', 'Акции'), ('news', 'Новости')], max_length=25, verbose_name='Тип')),\n ('linked_object_id', models.CharField(blank=True, max_length=120, null=True, verbose_name='ID связанного объекта')),\n ('body', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True, verbose_name='Тело')),\n ('is_viewed', models.BooleanField(default=False, verbose_name='Просмотрено?')),\n ('is_active', models.BooleanField(default=True, verbose_name='Активен?')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notifications', to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),\n ],\n options={\n 'verbose_name': 'Уведомление',\n 'verbose_name_plural': 'Уведомления',\n 'ordering': ['-created_at'],\n },\n ),\n ]\n" }, { "alpha_fraction": 0.70540851354599, "alphanum_fraction": 0.7134637236595154, "avg_line_length": 33.7599983215332, "blob_id": "d7cf00ee3cf69393556fd8501bb327c7301d0d45", "content_id": "6d66934d299e84297aecce04f7178e24127e8c5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 92, "num_lines": 25, "path": "/apps/setting/tests/test_views.py", "repo_name": "TimurAbdymazhinov/adeliya-backend", "src_encoding": "UTF-8", "text": "from django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom apps.setting.models import AppVersion\nfrom .factories import AppVersionFactory\n\n\nclass AppVersionTest(APITestCase):\n\n def setUp(self) -> None:\n self.app_version = AppVersionFactory()\n self.url = reverse('v1:app-version')\n\n def test_get_app_version(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(self.app_version.android_version, response.data['android_version'])\n\n def test_get_app_version_on_empty_db_table(self):\n AppVersion.objects.all().delete()\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual('', response.data['android_version'])\n" } ]
110
mohkale/HollowAether
https://github.com/mohkale/HollowAether
5c01a5205b86b7aa9fbbaf1c301a5d5294e3b792
d9a0c10f785ec8a76259840b9c9fb04d6dc74a64
54cfd6caae05372ffd322f15130bd480d18bf82d
refs/heads/master
2022-12-15T22:39:07.962069
2020-09-13T22:26:11
2020-09-13T22:26:11
295,243,635
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7436057329177856, "alphanum_fraction": 0.7436057329177856, "avg_line_length": 36.16666793823242, "blob_id": "188eb6dd2cfa683a485c518730c30bda63ab56dc", "content_id": "7dbfd28400fc920f7107efafabbddebaef0b376d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1605, "license_type": "no_license", "max_line_length": 103, "num_lines": 42, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/AnimationException.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tclass AnimationException : HollowAetherException {\r\n\t\tpublic AnimationException() : base() { }\r\n\r\n\t\tpublic AnimationException(String msg) : base(msg) { }\r\n\r\n\t\tpublic AnimationException(String msg, Exception inner) : base(msg, inner) { }\r\n\r\n\t\tpublic AnimationException(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t}\r\n\r\n\tclass AnimationFileNotFoundException : AnimationException {\r\n\t\tpublic AnimationFileNotFoundException(String fpath) \r\n\t\t\t: base($\"Animation File '{fpath}' Not Found\") {}\r\n\r\n\t\tpublic AnimationFileNotFoundException(String fpath, Exception inner) \r\n\t\t\t: base($\"Animation File '{fpath}' Not Found\", inner) {}\r\n\t}\r\n\r\n\tclass AnimationIncorrectHeaderException : AnimationException {\r\n\t\tpublic AnimationIncorrectHeaderException(String fpath)\r\n\t\t\t: base($\"Animation File '{fpath}' Lacks The Correct Header\") { }\r\n\t\tpublic AnimationIncorrectHeaderException(String fpath, Exception inner)\r\n\t\t\t: base($\"Animation File '{fpath}' Lacks The Correct Header\", inner) { }\r\n\t}\r\n\r\n\tclass AnimationFrameDefinitionFormatException : AnimationException {\r\n\t\tpublic AnimationFrameDefinitionFormatException(String line)\r\n\t\t\t: base($\"Couldn't Extract Frame From Line '{line}'\") { }\r\n\t\tpublic AnimationFrameDefinitionFormatException(String line, Exception inner)\r\n\t\t\t: base($\"Couldn't Extract Frame From Line '{line}'\", inner) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7278798222541809, "alphanum_fraction": 0.7278798222541809, "avg_line_length": 21.038461685180664, "blob_id": "04647e7cd120193a7c8b4735a6d446c033129a73", "content_id": "1c69288f0cbea6ba4a4437b1748d14cd1972195b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 601, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/HollowAether/Lib/Interfaces/IInteractable.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib {\r\n\r\n\tpublic interface IInteractable {\r\n\t\tvoid Interact();\r\n\t\tbool Interacted { get; }\r\n\t\tbool CanInteract { get; }\r\n\t}\r\n\r\n\tpublic interface ITimeoutSupportedInteractable : IInteractable {\r\n\t\tint InteractionTimeout { get; set; }\r\n\t}\r\n\r\n\tpublic interface IAutoInteractable : IInteractable {\r\n\t\tbool InteractCondition();\r\n\t}\r\n\r\n\tpublic interface ITimeoutSupportedAutoInteractable : IAutoInteractable {\r\n\t\tint InteractionTimeout { get; set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7447552680969238, "alphanum_fraction": 0.7447552680969238, "avg_line_length": 21.83333396911621, "blob_id": "081e53f93cba3f49980b2153c5e20469fadacd14", "content_id": "cf74e440b90894968382275cc945873790c1bc52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 288, "license_type": "no_license", "max_line_length": 69, "num_lines": 12, "path": "/HollowAether/Lib/Interfaces/IBlock.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary>Interface for any class which acts as a block</summary>\r\n\tinterface IBlock { }\r\n}\r\n" }, { "alpha_fraction": 0.7204724550247192, "alphanum_fraction": 0.7317913174629211, "avg_line_length": 30.774192810058594, "blob_id": "c998f5df3ba31a4c29c5d94664c02207d79765ab", "content_id": "a890ff2c9ca2d60769fb7ad20ed4d75f19263764", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2034, "license_type": "no_license", "max_line_length": 121, "num_lines": 62, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Assist/EnemyProjectile.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic abstract class EnemyProjectile : VolatileCollideableSprite, IDamagingToPlayer {\r\n\t\tpublic EnemyProjectile(Vector2 position, Vector2 target, float velocity, int width, int height, bool animationRunning) \r\n\t\t\t: base(position, width, height, animationRunning) {\r\n\t\t\tVector2 widthHeight = target - position; // Get width height dimensions for object travel\r\n\r\n\t\t\tfloat theta = (float)Math.Atan2(widthHeight.Y, widthHeight.X); // Get angle towards target\r\n\r\n\t\t\tVelocity = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * new Vector2(velocity);\r\n\r\n\t\t\tInitializeVolatility(VolatilityType.Other, new ImplementVolatility(ReadyToDeleteCheck));\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\r\n\t\t\tOffsetSpritePosition(Velocity * elapsedTime);\r\n\t\t}\r\n\r\n\t\tpublic abstract int GetDamage();\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(Position.X, Position.Y, Width, Height));\r\n\t\t}\r\n\r\n\t\tprivate static bool ReadyToDeleteCheck(IMonoGameObject self) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tprotected Vector2 Velocity;\r\n\t}\r\n\r\n\tpublic class Fireball : EnemyProjectile {\r\n\t\tpublic Fireball(Vector2 position, Vector2 target, float velocity) \r\n\t\t\t: base(position, target, velocity, 15, 15, true) {\r\n\t\t\tInitialize(@\"fx\\fireball\");\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(\r\n\t\t\t\tFRAME_WIDTH, FRAME_HEIGHT, 0, 0, 4, FRAME_WIDTH, FRAME_HEIGHT, 2, true, 0\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic override int GetDamage() {\r\n\t\t\treturn 2;\r\n\t\t}\r\n\r\n\t\tpublic const int FRAME_WIDTH = 35, FRAME_HEIGHT = 35;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7305389046669006, "alphanum_fraction": 0.7353293299674988, "avg_line_length": 24.935483932495117, "blob_id": "653d1ef8c7e66197492cf87a05b4bea35ad27929", "content_id": "6e0c60b349b82213cfc1f5286b350f0eaea7a592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 837, "license_type": "no_license", "max_line_length": 105, "num_lines": 31, "path": "/HollowAether/Lib/GAssets/Effects/FX.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.FX {\r\n\tpublic abstract class FXSprite : VolatileSprite {\r\n\t\tpublic FXSprite(Vector2 position, int width, int height, int timeout) : base(position, width, height) {\r\n\t\t\tInitializeVolatility(VolatilityType.Timeout, timeout);\r\n\t\t\tLayer = 0.75f; // Above player, below HUD\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t\tImplementEffect();\r\n\r\n\t\t\t// Check if FX is in camera here\r\n\t\t}\r\n\r\n\t\tprotected abstract void ImplementEffect();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6648522615432739, "alphanum_fraction": 0.6798859238624573, "avg_line_length": 41.34831619262695, "blob_id": "6d473f07952b08dcfdbaa47f96530b9982b393d3", "content_id": "86ddff659bf6f9274360dac7b0174d3abd342c13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3860, "license_type": "no_license", "max_line_length": 145, "num_lines": 89, "path": "/HollowAether/Lib/Global/GameWindow/(Window).cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic static class GameWindows {\r\n\t\tpublic static void WindowSizeChanged() {\r\n\t\t\tGV.MonoGameImplement.backgrounds[\"GW_HOME_SCREEN\"] = new Background(GetMovingHSCESLayers()) {\r\n\t\t\t\tnew StretchedBackgroundLayer(@\"backgrounds\\misc\\bg07_alt\", new Frame(0, 0, 400, 240, 1, 1, 1), 0.5f),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate static IEnumerable<MovingBackgroundLayer> GetMovingHSCESLayers(float scale=1.5f) {\r\n\t\t\tint HSCES_Width = 640, HSCES_Height = 125; // Determine home screen cloud sprite dimensions\r\n\r\n\t\t\tint cloudHeight\t = (int)(scale * HSCES_Height), yOffset = (int)(0.35f * cloudHeight);\r\n\t\t\tVector2 bottom\t = new Vector2(0, (GV.Variables.windowHeight - cloudHeight));\r\n\t\t\tString HSCES_Key = @\"backgrounds\\homescreencloudeffect\"; // Path to texture\r\n\r\n\t\t\tvar frames = (from int X in Enumerable.Range(0, 4) select new Frame(0, X, HSCES_Width, HSCES_Height, HSCES_Width, HSCES_Height, 1)).ToArray();\r\n\t\t\t// Frames order = { Light, Medium Light, Medium Dark, Dark } from indexes { 0, 1, 2, 3 }. Easier to use LINQ instead of manually.\r\n\r\n\t\t\tFunc<int, Vector2> GetPos = (X) => bottom - new Vector2(GV.Variables.random.Next(0, 720), X * yOffset);\r\n\r\n\t\t\tVector2[] positions = (from X in Enumerable.Range(0, 4) select GetPos(X)).ToArray(); // Get all position-vars\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, positions.Length)) {\r\n\t\t\t\tyield return new MovingBackgroundLayer(HSCES_Key, frames[X], (int)(scale * HSCES_Width), cloudHeight, 1.0f - (X * 0.1f)) {\r\n\t\t\t\t\tOffset = positions[X], Velocity = new Vector2(250 - (50 * X), 0), RepeatHorizontally = true // General variables \r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void DrawCurrentGameWindow() {\r\n\t\t\tswitch (GlobalVars.MonoGameImplement.gameState) {\r\n\t\t\t\tcase (GameState.Home): Home.Draw();\t\t\tbreak;\r\n\t\t\t\tcase (GameState.Settings): Settings.Draw();\t\tbreak;\r\n\t\t\t\tcase (GameState.SaveLoad): SaveLoad.Draw();\t\tbreak;\r\n\t\t\t\tcase (GameState.GameRunning): GameRunning.Draw();\tbreak;\r\n\t\t\t\tcase (GameState.GamePaused): GamePaused.Draw(); break;\r\n\t\t\t\tcase (GameState.PlayerDeceased): PlayerDeceased.Draw(); break;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tthrow new FatalException(\"No Game Window For Current Game State\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void UpdateCurrentGameWindow() {\r\n\t\t\tswitch (GV.MonoGameImplement.gameState) {\r\n\t\t\t\tcase (GameState.Home):\t\t\t Home.Update(); break;\r\n\t\t\t\tcase (GameState.Settings):\t\t Settings.Update(); break;\r\n\t\t\t\tcase (GameState.SaveLoad):\t\t SaveLoad.Update(); break;\r\n\t\t\t\tcase (GameState.GameRunning):\t GameRunning.Update();\t break;\r\n\t\t\t\tcase (GameState.GamePaused): GamePaused.Update(); break;\r\n\t\t\t\tcase (GameState.PlayerDeceased): PlayerDeceased.Update(); break;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tthrow new FatalException(\"No Game Window For Current Game State\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void ResetCurrentGameWindow() {\r\n\t\t\tswitch (GV.MonoGameImplement.gameState) {\r\n\t\t\t\tcase (GameState.Home):\t\t\t Home.Reset();\t\t\t break;\r\n\t\t\t\tcase (GameState.Settings):\t\t Settings.Reset();\t break;\r\n\t\t\t\tcase (GameState.SaveLoad):\t\t SaveLoad.Reset();\t\t break;\r\n\t\t\t\tcase (GameState.GameRunning):\t GameRunning.Reset(); break;\r\n\t\t\t\tcase (GameState.GamePaused): GamePaused.Reset(); break;\r\n\t\t\t\tcase (GameState.PlayerDeceased): PlayerDeceased.Reset(); break;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tthrow new FatalException(\"No Game Window For Current Game State\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7513774037361145, "avg_line_length": 37.24324417114258, "blob_id": "0d0679b7d4cce9104b944545214a36039399ce08", "content_id": "0d6edc6cffd69bcf28ca45204649eb21c6eb769e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 120, "num_lines": 37, "path": "/HollowAether/Lib/GAssets/Boundary/Container/Assistance/Shared.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.Exceptions;\r\nusing Microsoft.Xna.Framework;\r\n\r\nnamespace HollowAether.Lib.GAssets.Boundary {\r\n\tstatic class BoundaryShared {\r\n\t\t/// <summary>Gets Rectangle encompassing all boundaries within instance</summary>\r\n\t\t/// <param name=\"container\">Instance of collision boundary class</param>\r\n\t\t/// <returns>Rectangle containing area of all boundaries within a given container</returns>\r\n\t\tpublic static IBRectangle GetBoundaryArea(IBoundaryContainer container) {\r\n\t\t\tif (container.Boundaries.Length == 0) return container.SpriteRect; // throw new HollowAetherException(\"No Boundary\");\r\n\r\n\t\t\tIBRectangle compound = container.Boundaries[0].Container; // Begin from first\r\n\r\n\t\t\tforeach (IBoundary boundary in container.Boundaries) {\r\n\t\t\t\tcompound = IBRectangle.Union(compound, boundary.Container);\r\n\t\t\t}\r\n\r\n\t\t\treturn compound;\r\n\t\t}\r\n\r\n\t\tpublic static DeltaPositions GetDeltaPositions(Rectangle spriteRect, IBRectangle containerRect) {\r\n\t\t\treturn new DeltaPositions(\r\n\t\t\t\tdeltaX: spriteRect.Width - containerRect.Width,\r\n\t\t\t\tdeltaY: spriteRect.Height - containerRect.Height,\r\n\t\t\t\tdeltaTop: containerRect.Top - spriteRect.Top,\r\n\t\t\t\tdeltaBottom: spriteRect.Bottom - containerRect.Bottom,\r\n\t\t\t\tdeltaLeft: containerRect.Left - spriteRect.Left,\r\n\t\t\t\tdeltaRight: spriteRect.Right - containerRect.Right\r\n\t\t\t);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6910617351531982, "alphanum_fraction": 0.6931357979774475, "avg_line_length": 34.290321350097656, "blob_id": "a4120b710c834da98889291d2b89c9e825f7c726", "content_id": "6e9e09967832c125513abeaf5cd371a1abc3e7c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 10127, "license_type": "no_license", "max_line_length": 118, "num_lines": 279, "path": "/HollowAether/Lib/Global/GlobalVars/Content.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#define DebugOutputLoadImage\r\n\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\nusing System.Drawing;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Content;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing SUM = HollowAether.StartUpMethods;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nusing System;\r\nusing System.Windows.Forms;\r\nusing System.Threading;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class Content {\r\n\t\t\t#region APIWrapperClasses\r\n\t\t\t/// <summary>\r\n\t\t\t/// Container class implements the IServiceProvider interface. This is used\r\n\t\t\t/// to pass shared services between different components, for instance the\r\n\t\t\t/// ContentManager uses it to locate the IGraphicsDeviceService implementation.\r\n\t\t\t/// </summary>\r\n\t\t\tpublic class ServiceContainer : IServiceProvider {\r\n\t\t\t\t/// <summary> Adds a new service to the collection. </summary>\r\n\t\t\t\tpublic void AddService<T>(T service) {\r\n\t\t\t\t\tservices.Add(typeof(T), service);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t/// <summary> Looks up the specified service.</summary>\r\n\t\t\t\tpublic object GetService(Type serviceType) {\r\n\t\t\t\t\tobject service;\r\n\r\n\t\t\t\t\tservices.TryGetValue(serviceType, out service);\r\n\r\n\t\t\t\t\treturn service;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tDictionary<Type, object> services = new Dictionary<Type, object>();\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary> Helper class responsible for creating and managing the GraphicsDevice.\r\n\t\t\t/// All GraphicsDeviceControl instances share the same GraphicsDeviceService,\r\n\t\t\t/// so even though there can be many controls, there will only ever be a single\r\n\t\t\t/// underlying GraphicsDevice. This implements the standard IGraphicsDeviceService\r\n\t\t\t/// interface, which provides notification events for when the device is reset\r\n\t\t\t/// or disposed. </summary>\r\n\t\t\tclass GraphicsDeviceService : IGraphicsDeviceService {\r\n\t\t\t\t#region Fields\r\n\r\n\r\n\t\t\t\t// Singleton device service instance.\r\n\t\t\t\tstatic GraphicsDeviceService singletonInstance;\r\n\r\n\r\n\t\t\t\t// Keep track of how many controls are sharing the singletonInstance.\r\n\t\t\t\tstatic int referenceCount;\r\n\r\n\r\n\t\t\t\t#endregion\r\n\r\n\r\n\t\t\t\t/// <summary> Constructor is private, because this is a singleton class:\r\n\t\t\t\t/// client controls should use the public AddRef method instead. </summary>\r\n\t\t\t\tGraphicsDeviceService(IntPtr windowHandle, int width, int height) {\r\n\t\t\t\t\tparameters = new PresentationParameters();\r\n\r\n\t\t\t\t\tparameters.BackBufferWidth = Math.Max(width, 1);\r\n\t\t\t\t\tparameters.BackBufferHeight = Math.Max(height, 1);\r\n\t\t\t\t\tparameters.BackBufferFormat = SurfaceFormat.Color;\r\n\t\t\t\t\tparameters.DepthStencilFormat = DepthFormat.Depth24;\r\n\t\t\t\t\tparameters.DeviceWindowHandle = windowHandle;\r\n\t\t\t\t\tparameters.PresentationInterval = PresentInterval.Immediate;\r\n\t\t\t\t\tparameters.IsFullScreen = false;\r\n\r\n\t\t\t\t\tgraphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tGraphicsProfile.Reach,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tparameters);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t/// <summary> Gets a reference to the singleton instance. </summary>\r\n\t\t\t\tpublic static GraphicsDeviceService AddRef(IntPtr windowHandle,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t int width, int height) {\r\n\t\t\t\t\t// Increment the \"how many controls sharing the device\" reference count.\r\n\t\t\t\t\tif (Interlocked.Increment(ref referenceCount) == 1) {\r\n\t\t\t\t\t\t// If this is the first control to start using the\r\n\t\t\t\t\t\t// device, we must create the singleton instance.\r\n\t\t\t\t\t\tsingletonInstance = new GraphicsDeviceService(windowHandle,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t width, height);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn singletonInstance;\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t/// <summary> Releases a reference to the singleton instance. </summary>\r\n\t\t\t\tpublic void Release(bool disposing) {\r\n\t\t\t\t\t// Decrement the \"how many controls sharing the device\" reference count.\r\n\t\t\t\t\tif (Interlocked.Decrement(ref referenceCount) == 0) {\r\n\t\t\t\t\t\t// If this is the last control to finish using the\r\n\t\t\t\t\t\t// device, we should dispose the singleton instance.\r\n\t\t\t\t\t\tif (disposing) {\r\n\t\t\t\t\t\t\tif (DeviceDisposing != null)\r\n\t\t\t\t\t\t\t\tDeviceDisposing(this, EventArgs.Empty);\r\n\r\n\t\t\t\t\t\t\tgraphicsDevice.Dispose();\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tgraphicsDevice = null;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t/// <summary> Resets the graphics device to whichever is bigger out of the specified\r\n\t\t\t\t/// resolution or its current size. This behavior means the device will\r\n\t\t\t\t/// demand-grow to the largest of all its GraphicsDeviceControl clients. </summary>\r\n\t\t\t\tpublic void ResetDevice(int width, int height) {\r\n\t\t\t\t\tif (DeviceResetting != null)\r\n\t\t\t\t\t\tDeviceResetting(this, EventArgs.Empty);\r\n\r\n\t\t\t\t\tparameters.BackBufferWidth = Math.Max(parameters.BackBufferWidth, width);\r\n\t\t\t\t\tparameters.BackBufferHeight = Math.Max(parameters.BackBufferHeight, height);\r\n\r\n\t\t\t\t\tgraphicsDevice.Reset(parameters);\r\n\r\n\t\t\t\t\tif (DeviceReset != null)\r\n\t\t\t\t\t\tDeviceReset(this, EventArgs.Empty);\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\t/// <summary> Gets the current graphics device. </summary>\r\n\t\t\t\tpublic GraphicsDevice GraphicsDevice {\r\n\t\t\t\t\tget { return graphicsDevice; }\r\n\t\t\t\t}\r\n\r\n\t\t\t\tGraphicsDevice graphicsDevice;\r\n\r\n\r\n\t\t\t\t// Store the current device settings.\r\n\t\t\t\tPresentationParameters parameters;\r\n\r\n\t\t\t\t// IGraphicsDeviceService events.\r\n\t\t\t\tpublic event EventHandler<EventArgs> DeviceCreated;\r\n\t\t\t\tpublic event EventHandler<EventArgs> DeviceDisposing;\r\n\t\t\t\tpublic event EventHandler<EventArgs> DeviceReset;\r\n\t\t\t\tpublic event EventHandler<EventArgs> DeviceResetting;\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\tpublic static void LoadContent() {\r\n\t\t\t\tContentManager Content = GlobalVars.hollowAether.Content;\r\n\r\n\t\t\t\tFunc<String, String> GetAllButFirstDirectory = (path) => {\r\n\t\t\t\t\tString[] splitPath = path.Split('\\\\'); // Split path into all sub paths including directories and files\r\n\t\t\t\t\treturn GV.CollectionManipulator.GetSubArray(splitPath, 1, splitPath.Length - 1).Aggregate((a, b) => $\"{a}\\\\{b}\");\r\n\t\t\t\t};\r\n\r\n\t\t\t\tforeach (string contentPath in SUM.SystemParserTruncatedScriptInterpreter(Content.RootDirectory)) {\r\n\t\t\t\t\tString trueContentPath = contentPath.Replace(IOMan.GetExtension(contentPath), \"\"), // No Extension\r\n\t\t\t\t\t\t key = GetAllButFirstDirectory(contentPath).Replace(IOMan.GetExtension(contentPath), \"\").ToLower();\r\n\r\n\t\t\t\t\tswitch (IOMan.GetDirectoryName(contentPath).Split('\\\\')[0].ToLower()) {\r\n\t\t\t\t\t\tcase \"textures\":\r\n\t\t\t\t\t\t\tMonoGameImplement.textures.Add(key, Content.Load<Texture2D>(trueContentPath));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"fonts\":\r\n\t\t\t\t\t\t\tMonoGameImplement.fonts.Add(key, Content.Load<SpriteFont>(trueContentPath));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"video\":\r\n\t\t\t\t\t\t\tMonoGameImplement.videos.Add(key, Content.Load<Video>(trueContentPath));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"sound\":\r\n\t\t\t\t\t\t\tMonoGameImplement.sounds.Add(key, Content.Load<SoundEffect>(trueContentPath));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate static IEnumerable<String> GetAllTexturePaths() {\r\n\t\t\t\tFunc<String, String> GetAllButFirstDirectory = (path) => {\r\n\t\t\t\t\tString[] splitPath = path.Split('\\\\'); // Split path into all sub paths including directories and files\r\n\t\t\t\t\treturn GV.CollectionManipulator.GetSubArray(splitPath, 1, splitPath.Length - 1).Aggregate((a, b) => $\"{a}\\\\{b}\");\r\n\t\t\t\t};\r\n\r\n\t\t\t\tString rootDirectory = GV.hollowAether.Content.RootDirectory;\r\n\t\t\t\t\r\n\t\t\t\tforeach (string contentPath in SUM.SystemParserTruncatedScriptInterpreter(rootDirectory)) {\r\n\t\t\t\t\t//String trueContentPath = contentPath.Replace(IOMan.GetExtension(contentPath), \"\"); // No Extension\r\n\t\t\t\t\t//String key = GetAllButFirstDirectory(contentPath).Replace(IOMan.GetExtension(contentPath), \"\").ToLower();\r\n\r\n\t\t\t\t\tswitch (IOMan.GetDirectoryName(contentPath).Split('\\\\')[0].ToLower()) {\r\n\t\t\t\t\t\tcase \"textures\": yield return contentPath; break;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate static ContentManager GenerateContentManager() {\r\n\t\t\t\tForm form = new Form(); // Dummy form for creating a graphics device\r\n\t\t\t\tGraphicsDeviceService gds = GraphicsDeviceService.AddRef(form.Handle,\r\n\t\t\t\t\t\tform.ClientSize.Width, form.ClientSize.Height);\r\n\r\n\t\t\t\tServiceContainer services = new ServiceContainer();\r\n\t\t\t\tservices.AddService<IGraphicsDeviceService>(gds);\r\n\r\n\t\t\t\treturn new ContentManager(services, GV.hollowAether.Content.RootDirectory);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static IEnumerable<Tuple<Texture2D, String>> LoadTextures() {\r\n\t\t\t\tContentManager manager = GenerateContentManager(); // Generate new content manager\r\n\r\n\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\tConsole.WriteLine(\"\\tContent Manager Made\\n\");\r\n\t\t\t\t#endif\r\n\r\n\t\t\t\tforeach (String texturePath in GetAllTexturePaths()) {\r\n\t\t\t\t\tString withoutExtension = texturePath.Replace(IOMan.GetExtension(texturePath), \"\");\r\n\r\n\t\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\t\tConsole.WriteLine($\"\\t\\tLoaded Texture '{texturePath}'\");\r\n\t\t\t\t\t#endif\r\n\r\n\t\t\t\t\tyield return new Tuple<Texture2D, String>(manager.Load<Texture2D>(withoutExtension), texturePath);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmanager.Dispose();\r\n\r\n\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\tConsole.WriteLine(\"\\tContent Manager Disposed\");\r\n\t\t\t\t#endif\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Tuple<Image, String>[] LoadImages() {\r\n\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\tConsole.WriteLine(\"Image Load Begun\");\r\n\t\t\t\t#endif\r\n\r\n\t\t\t\tList<Tuple<Image, String>> images = new List<Tuple<Image, String>>();\r\n\r\n\t\t\t\tforeach (Tuple<Texture2D, String> keyText in LoadTextures()) {\r\n\t\t\t\t\tTexture2D texture = keyText.Item1; // Alias for texture\r\n\r\n\t\t\t\t\tusing (MemoryStream memoryStrem = new MemoryStream()) {\r\n\t\t\t\t\t\ttexture.SaveAsPng(memoryStrem, texture.Width, texture.Height);\r\n\t\t\t\t\t\tImage image = Image.FromStream(memoryStrem); // Texture2D\r\n\t\t\t\t\t\timages.Add(new Tuple<Image, String>(image, keyText.Item2));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\t\tConsole.WriteLine($\"\\t\\tCasted Texture To Image\\n\");\r\n\t\t\t\t\t#endif\r\n\t\t\t\t}\r\n\r\n\t\t\t\t#if DEBUG && DebugOutputLoadImage\r\n\t\t\t\tConsole.WriteLine(\"Image Load Complete\\n\");\r\n\t\t\t\t#endif\r\n\r\n\t\t\t\treturn images.ToArray();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7054460048675537, "alphanum_fraction": 0.7090646028518677, "avg_line_length": 34.8466682434082, "blob_id": "00dd2fb03458d8d68f0c735dd6cdca3597259456", "content_id": "56a49db2af97c919af2096165bd5a30830f93cfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5529, "license_type": "no_license", "max_line_length": 125, "num_lines": 150, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/TileMap.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class TileMap : Form {\r\n\t\tpublic TileMap() {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tsizeBeforeResizing = Size; // Store initial size of tile map at form construction\r\n\r\n\t\t\tgapBetweenZoomInAndZoomOutButtons = zoomOutButton.Top - zoomInButton.Bottom; // Store gap region\r\n\r\n\t\t\ttextureDisplay.MouseWheel += (s, e) => { ((HandledMouseEventArgs)e).Handled = true; };\r\n\r\n\t\t\tFormClosing += (s, e) => { if (e.CloseReason != CloseReason.ApplicationExitCall) e.Cancel = true; closedOnce = true; };\r\n\r\n\t\t\tcanvas.DrawToCanvas += (s, e) => {\r\n\t\t\t\t//Console.WriteLine(canvas.SelectRect);\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate void TileMap2_Load(object sender, EventArgs e) {\r\n\t\t\tcanvas.Width = canvasRegionPanel.Width;\r\n\t\t\tcanvas.Height = canvasRegionPanel.Height;\r\n\t\t\t\r\n\t\t\tcanvas.DrawToCanvas += Canvas_DrawToCanvas;\r\n\t\t\tcanvasRegionPanel.Controls.Add(canvas);\r\n\r\n\t\t\ttextureDisplay.Items.AddRange(GV.LevelEditor.textures.Keys.ToArray()); // Add all textures to combo box\r\n\t\t\ttextureDisplay.SelectedIndex = 0; // Select first texture referenced by the combobox \r\n\r\n\t\t\tblockWidthTextBox.Text = canvas.GridWidth.ToString();\r\n\t\t\tblockHeightTextBox.Text = canvas.GridHeight.ToString();\r\n\t\t}\r\n\r\n\t\tprivate void Canvas_DrawToCanvas(object sender, PaintEventArgs e) {\r\n\t\t\tif (CurrentImage != null) e.Graphics.DrawImage(CurrentImage, Point.Empty);\r\n\t\t}\r\n\r\n\t\tprivate void TileMap2_Resize(object sender, EventArgs e) {\r\n\t\t\tSize deltaSize = Size - sizeBeforeResizing;\r\n\r\n\t\t\tcanvasRegionPanel.Size += deltaSize;\r\n\t\t\ttextureDisplay.Width += deltaSize.Width;\r\n\r\n\t\t\tblockWidthLabel.Location = new Point(blockWidthLabel.Location.X + deltaSize.Width, blockWidthLabel.Location.Y);\r\n\t\t\tblockHeightLabel.Location = new Point(blockHeightLabel.Location.X + deltaSize.Width, blockHeightLabel.Location.Y);\r\n\t\t\tblockWidthTextBox.Location = new Point(blockWidthTextBox.Location.X + deltaSize.Width, blockWidthTextBox.Location.Y);\r\n\t\t\tblockHeightTextBox.Location = new Point(blockHeightTextBox.Location.X + deltaSize.Width, blockHeightTextBox.Location.Y);\r\n\r\n\t\t\tif (deltaSize.Height != 0) {\r\n\t\t\t\tint heightDifferential = canvasRegionPanel.Bottom - zoomInButton.Location.Y; // Displacement from top to bottom of column\r\n\t\t\t\t\r\n\t\t\t\tzoomInButton.Height = zoomOutButton.Height = (heightDifferential - gapBetweenZoomInAndZoomOutButtons) / 2; // actual\r\n\t\t\t\tzoomOutButton.Location = new Point(zoomOutButton.Location.X, zoomInButton.Bottom + gapBetweenZoomInAndZoomOutButtons);\r\n\t\t\t}\r\n\r\n\t\t\tsizeBeforeResizing = Size; // Store new size\r\n\t\t}\r\n\r\n\t\tprivate void zoomInButton_Click(object sender, EventArgs e) {\r\n\t\t\tfloat newZoom = GV.BasicMath.Clamp(canvas.ZoomX+1, 0.5f, 15f);\r\n\t\t\tcanvas.Zoom = new SizeF(newZoom, newZoom); // Set new zoom\r\n\t\t}\r\n\r\n\t\tprivate void zoomOutButton_Click(object sender, EventArgs e) {\r\n\t\t\tfloat newZoom = GV.BasicMath.Clamp(canvas.ZoomX - 1, 0.5f, 15f);\r\n\t\t\tcanvas.Zoom = new SizeF(newZoom, newZoom); // Set new zoom\r\n\t\t}\r\n\r\n\t\tprivate void textureDisplay_TextChanged(object sender, EventArgs e) {\r\n\t\t\tSetCurrentImage(GetTextValueFromComboBox());\r\n\t\t}\r\n\r\n\t\tprivate void blockWidthTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tint? value = GV.Misc.StringToInt(blockWidthTextBox.Text);\r\n\r\n\t\t\tif (value.HasValue) { canvas.GridWidth = value.Value; canvas.Deselect(); } else {\r\n\t\t\t\tMessageBox.Show(\"Given Value Could Not Be Turned To An Int\", \"Value Error\");\r\n\t\t\t\tblockWidthTextBox.Text = canvas.GridWidth.ToString(); // Set text to current\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void blockHeightTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tint? value = GV.Misc.StringToInt(blockHeightTextBox.Text);\r\n\r\n\t\t\tif (value.HasValue) { canvas.GridHeight = value.Value; canvas.Deselect(); } else {\r\n\t\t\t\tMessageBox.Show(\"Given Value Could Not Be Turned To An Int\", \"Value Error\");\r\n\t\t\t\tblockHeightTextBox.Text = canvas.GridHeight.ToString(); // Set text to current\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate string GetTextValueFromComboBox() {\r\n\t\t\treturn textureDisplay.SelectedItem.ToString();\r\n\t\t}\r\n\r\n\t\tpublic void ChangeImage(String textureKey) {\r\n\t\t\tSetCurrentImage(textureKey);\r\n\t\r\n\t\t\ttextureDisplay.SelectedText = textureKey;\r\n\t\t}\r\n\r\n\t\tpublic new void Show() {\r\n\t\t\tbase.Show();\r\n\r\n\t\t\tif (closedOnce) ReShown(this);\r\n\t\t}\r\n\r\n\t\tprivate void SetCurrentImage(string textureKey) {\r\n\t\t\ttry {\r\n\t\t\t\tCurrentImage\t\t = GV.LevelEditor.textures[textureKey].Item1;\r\n\t\t\t\tCurrentImageTextureKey = textureKey;\r\n\t\t\t\tcanvas.Width\t\t = CurrentImage.Width;\r\n\t\t\t\tcanvas.Height\t\t = CurrentImage.Height;\r\n\t\t\t\tcanvas.Zoom\t\t\t = canvas.Zoom; // Fixes Bug\r\n\t\t\t\tcanvas.Deselect();\r\n\t\t\t} catch (KeyNotFoundException e) {\r\n\t\t\t\tCurrentImage = null;\r\n\t\t\t} finally {\r\n\t\t\t\tcanvas.Draw();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate int gapBetweenZoomInAndZoomOutButtons;\r\n\t\tprivate Size sizeBeforeResizing; // When resizing\r\n\r\n\t\tpublic CanvasRegionBox canvas = new CanvasRegionBox() {\r\n\t\t\tGridSize = new SizeF(32, 32),\r\n\t\t\tDrawGrid = true, DrawBorder = true,\r\n\t\t\tSelectOption = CanvasRegionBox.SelectType.GridDrag,\r\n\t\t\tdragableSelectionRectsAreVolatile = false\r\n\t\t};\r\n\r\n\t\tprivate bool closedOnce = false;\r\n\r\n\t\tpublic event Action<object> ReShown = (s) => { };\r\n\r\n\t\tpublic Image CurrentImage { get; private set; }\r\n\r\n\t\tpublic String CurrentImageTextureKey { get; private set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7184337973594666, "alphanum_fraction": 0.7276726961135864, "avg_line_length": 32.96923065185547, "blob_id": "8e1a7e7b077b976174249bf5665f9274e2460cdf", "content_id": "d4ed9d82c3b08b8d9855103bb15331efe5b3cedb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2275, "license_type": "no_license", "max_line_length": 148, "num_lines": 65, "path": "/HollowAether/Lib/GAssets/HUD/GamePadButtonIconWithText.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GPBI = HollowAether.Lib.GAssets.HUD.GamePadButtonIcon;\r\nusing GPB = HollowAether.Lib.GAssets.HUD.GamePadButtonIcon.GamePadButton;\r\nusing GPT = HollowAether.Lib.GAssets.HUD.GamePadButtonIcon.Theme;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\tpublic class GamePadButtonIconWithText : GPBI {\r\n\t\tpublic enum TextPosition { BeforeButton, OverButton, AfterButton }\r\n\r\n\t\tpublic GamePadButtonIconWithText(\r\n\t\t\t\tVector2 position, GPB _button, string text,\r\n\t\t\t\tTextPosition tp = TextPosition.OverButton, \r\n\t\t\t\tGPT theme=GPT.Regular, int width = SPRITE_WIDTH, \r\n\t\t\t\tint height = SPRITE_HEIGHT, bool active=true\r\n\t\t\t) : base(position, _button, theme, width, height, active) {\r\n\t\t\tSetText(text);\r\n\t\t\tpositionArg = tp;\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(Font, Text, GetTextPosition(), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, Layer+0.0005f);\r\n\t\t}\r\n\r\n\t\tprivate Vector2 GetTextPosition() {\r\n\t\t\tVector2 horizontalOffset = new Vector2(5, 0);\r\n\r\n\t\t\tswitch (positionArg) {\r\n\t\t\t\tcase TextPosition.AfterButton:\r\n\t\t\t\t\treturn Position + horizontalOffset + new Vector2(Width, 0);\r\n\t\t\t\tcase TextPosition.BeforeButton:\r\n\t\t\t\t\treturn Position - new Vector2(stringSize.X, 0) - horizontalOffset;\r\n\t\t\t\tcase TextPosition.OverButton:\r\n\t\t\t\t\treturn SpriteRect.Center.ToVector2() - (stringSize / 2);\r\n\t\t\t\tdefault: throw new HollowAetherException($\"Invalid position arg\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void SetText(String text) { Text = text; stringSize = Font.MeasureString(text); }\r\n\r\n\r\n\t\tprivate Vector2 stringSize;\r\n\r\n\t\tpublic String Text { get; private set; }\r\n\r\n\t\tprivate String fontKey = \"homescreen\";\r\n\r\n\t\tprivate TextPosition positionArg;\r\n\r\n\t\tpublic SpriteFont Font {\r\n\t\t\tget { return GV.MonoGameImplement.fonts[fontKey]; } // Gets sprite font from font key index in global store\r\n\t\t\tset { fontKey = GV.CollectionManipulator.DictionaryGetKeyFromValue(GV.MonoGameImplement.fonts, value); }\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6559386849403381, "alphanum_fraction": 0.6819923520088196, "avg_line_length": 34.25, "blob_id": "647c3533e2ab7771f09cade07d8ed369a19cdf17", "content_id": "c652148a396b0c7b0418d57f42ac09fa460b3981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2612, "license_type": "no_license", "max_line_length": 124, "num_lines": 72, "path": "/HollowAether/Lib/GAssets/Items/Points/Coin.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic sealed class Coin : TreasureItem {\r\n\t\t/// <summary>The coin types which exist in the game</summary>\r\n\t\t/// <remarks>\r\n\t\t///\t\tSmall - Texture 16_16, Y_Value 01\r\n\t\t///\t\tMedium - Texture 32_32, Y_Value 01\r\n\t\t///\t\tLarge - Texture 32_32, Y_Value 02\r\n\t\t///\t\tExtraLarge - Texture 16_16, Y_Value 02\r\n\t\t/// </remarks>\r\n\t\tpublic enum CoinType { Small, Medium, Large, ExtraLarge }\r\n\r\n\t\tpublic Coin(Vector2 position, CoinType? _type = null, bool randMove = true) \r\n\t\t\t: base(position, SPRITE_WIDTH, SPRITE_HEIGHT, 5000, true) {\r\n\t\t\ttype = (_type.HasValue) ? _type.Value : DEFAULT_COIN_TYPE;\r\n\t\t\tInitialize(TypeToTextureString(type)); // Build sequence lib\r\n\t\t}\r\n\r\n\t\tpublic override void Interact() {\r\n\t\t\tif (!CanInteract || Interacted) return;\r\n\t\t\tGameWindow.GameRunning.InvokeCoinAcquired(this);\r\n\t\t\tbase.Interact(); // Allocate to delete & Mark interacted\r\n\t\t}\r\n\r\n\t\tprivate static String TypeToTextureString(CoinType type) {\r\n\t\t\treturn (type == CoinType.Small || type == CoinType.ExtraLarge) ? @\"items\\coins\\coins_16x16\" : @\"items\\coins\\coins_32x32\";\r\n\t\t}\r\n\r\n\t\tprivate static int TypeToCurrencyValue(CoinType type) {\r\n\t\t\tswitch ((int)type) {\r\n\t\t\t\tcase 0: return 01;\r\n\t\t\t\tcase 1: return 03;\r\n\t\t\t\tcase 2: return 08;\r\n\t\t\t\tcase 3: return 12;\r\n\t\t\t\tdefault: return 00;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate int TypeToCurrencyValue() { return TypeToCurrencyValue(type); }\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tint widthAndHeight = (type == CoinType.Small || type == CoinType.ExtraLarge) ? 16 : 32;\r\n\t\t\tint frameCount = (type == CoinType.Small || type == CoinType.ExtraLarge) ? 04 : 06;\r\n\t\t\tint frameYValue = (type == CoinType.Small || type == CoinType.Medium) ? 00 : 01;\r\n\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(\r\n\t\t\t\twidthAndHeight, widthAndHeight, 0, frameYValue, frameCount, widthAndHeight, widthAndHeight\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tpublic CoinType type { get; private set; }\r\n\r\n\t\tpublic int Value { get { return TypeToCurrencyValue(type); } }\r\n\r\n\t\tpublic const CoinType DEFAULT_COIN_TYPE = CoinType.Small;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 16, SPRITE_HEIGHT = 16;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7084569931030273, "alphanum_fraction": 0.7203264236450195, "avg_line_length": 30.878047943115234, "blob_id": "bf48bce1e446c7cb9d0b5822e74c6d9191053a44", "content_id": "29ce75464f18378df4b04db1ff85c1c79e23e34b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1350, "license_type": "no_license", "max_line_length": 92, "num_lines": 41, "path": "/HollowAether/Lib/GAssets/Items/Chests/TreasureChest.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic sealed partial class TreasureChest : Chest {\r\n\t\tpublic TreasureChest() : this(Vector2.Zero) { }\r\n\r\n\t\tpublic TreasureChest(Vector2 position) : base(position) { }\r\n\r\n\t\tprotected override void ReleaseContents() {\r\n\t\t\tint enumCount = Enum.GetNames(typeof(Coin.CoinType)).Length; // Number of coin types\r\n\r\n\t\t\tVector2 initCoinPos = SpriteRect.Center.ToVector2() - new Vector2(0, Coin.SPRITE_HEIGHT);\r\n\r\n\t\t\tint coinCount = GV.Variables.random.Next(MIN_COIN_COUNT, MAX_COIN_COUNT);\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, coinCount)) {\r\n\t\t\t\tint coinType = GV.Variables.random.Next(0, enumCount);\r\n\r\n\t\t\t\tCoin coin = new Coin(initCoinPos, (Coin.CoinType)coinType) {\r\n\t\t\t\t\tInteractionTimeout = 1000 // Don't interact for 1 secs\r\n\t\t\t\t};\r\n\r\n\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(coin);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tprivate const int MIN_COIN_COUNT = 4, MAX_COIN_COUNT = 10;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6881153583526611, "alphanum_fraction": 0.6930379867553711, "avg_line_length": 33.54999923706055, "blob_id": "541bbe4254c29dd8bc03a4120457d235917bf29c", "content_id": "64a0b0ad082b88135274e94fc8445368f59b7161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2846, "license_type": "no_license", "max_line_length": 150, "num_lines": 80, "path": "/HollowAether/Lib/Global/GlobalVars/Misc.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class Misc {\r\n\t\t\tpublic static string GenerateRandomString(int length) {\r\n\t\t\t\tconst string chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"; // store alpha\r\n\t\t\t\treturn new string(Enumerable.Repeat(chars, length).Select(s => s[Variables.random.Next(s.Length)]).ToArray());\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Method to remove comments from Map & Zone Files</summary>\r\n\t\t\t/// <param name=\"contents\">Contents of Map/Zone files</param>\r\n\t\t\t/// <param name=\"commentString\">String which acts at comment</param>\r\n\t\t\tpublic static void RemoveComments(ref String contents, String commentString = \"#\") {\r\n\t\t\t\tforeach (Match comment in Regex.Matches(contents, $\"{commentString}(.*)\")) {\r\n\t\t\t\t\tcontents = contents.Replace(comment.Value, \"\"); // remove instance of comment\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool TypesContainsGivenType(Type current, Type[] desired) {\r\n\t\t\t\tforeach (Type type in desired) {\r\n\t\t\t\t\tif (DoesExtend(current, type))\r\n\t\t\t\t\t\treturn true; // Valid type\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn false; // Not in valid type array\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool DoesExtend(Type current, Type desired) {\r\n\t\t\t\treturn current == desired || current.IsAssignableFrom(desired) || current.IsSubclassOf(desired) || current.GetInterface(desired.FullName) != null;\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Method to try to turn a string to an int and return it</summary>\r\n\t\t\t/// <param name=\"arg\">String value to return as an int</param>\r\n\t\t\t/// <returns>Nullable which may have integer value of arg</returns>\r\n\t\t\tpublic static int? StringToInt(String arg) {\r\n\t\t\t\ttry { return int.Parse(arg); } catch { return null; }\r\n\t\t\t}\r\n\r\n\t\t\tpublic static float? StringToFloat(String arg) {\r\n\t\t\t\ttry { return float.Parse(arg); } catch { return null; }\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool SignChangedFromAddition(float A, float B) {\r\n\t\t\t\treturn (A < 0 && A + B >= 0) || (A >= 0 && A + B < 0);\r\n\t\t\t\t// (A is -ive && A + B is +ive) || (A is +ive && A + B is -ve) \r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool SignChangedFromSubtraction(float A, float B) {\r\n\t\t\t\treturn !SignChangedFromAddition(A, -B);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6966149806976318, "alphanum_fraction": 0.6985131502151489, "avg_line_length": 34.33333206176758, "blob_id": "aaff469f352e2efa1044c059d0371bf21183d9d9", "content_id": "c0649ba7ba28bbb2f4b91819584170d9a74b15bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3163, "license_type": "no_license", "max_line_length": 130, "num_lines": 87, "path": "/HollowAether/Lib/Entity/Tile.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing HollowAether.Lib.GAssets;\r\nusing System.Windows.Forms;\r\nusing System.Drawing;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether {\r\n\tpublic class EntityTile {\r\n\t\tpublic EntityTile(GameEntity entity) {\r\n\t\t\tthis.Entity = entity;\r\n\t\t\tBuildDisplayedImage();\r\n\t\t}\r\n\t\t\r\n\t\tpublic void Paint(PaintEventArgs e) {\r\n\t\t\tImage drawImage = (displayedImage != null) ? displayedImage : Properties.Resources.error;\r\n\t\t\te.Graphics.DrawImage(drawImage, Region); // Draw cropped image texture to canvas\r\n\r\n\t\t\tif (DrawBorder) {\r\n\t\t\t\tusing (Pen borderPen = new Pen(BorderColor, 2)) {\r\n\t\t\t\t\te.Graphics.DrawRectangle(borderPen, Location.X, Location.Y, Width, Height);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void BuildDisplayedImage() {\r\n\t\t\tif (Entity.GetEntityAttributes().Contains(\"DefaultAnimation\") && this[\"DefaultAnimation\"].IsAssigned) {\r\n\t\t\t\tframeRect = ((AnimationSequence)this[\"DefaultAnimation\"].GetActualValue()).GetFrame(false).ToDrawingRect();\r\n\t\t\t} else { frameRect = GV.EntityGenerators.GetAnimationFromEntityName(Entity.EntityType); }\r\n\r\n\t\t\tbool dontBuildTexture = !this[\"Texture\"].IsAssigned || !GV.LevelEditor.textures.ContainsKey(TextureKey) || !frameRect.HasValue;\r\n\r\n\t\t\tif (dontBuildTexture) { displayedImage = null; } else {\r\n\t\t\t\tdisplayedImage = GV.ImageManipulation.CropImage(GV.LevelEditor.textures[TextureKey].Item1, frameRect.Value);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool AttributeExists(string key) { return Entity.AttributeExists(key); }\r\n\r\n\t\tpublic EntityAttribute this[string key] { get { return Entity[key]; } }\r\n\r\n\t\tpublic Vector2 Position { get { return (Vector2)this[\"Position\"].GetActualValue(); } set { this[\"Position\"].Value = value; } }\r\n\r\n\t\tpublic PointF Location { set { Position = new Vector2(value.X, value.Y); } get {\r\n\t\t\t\tVector2 position = Position; return new PointF(position.X, position.Y);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic int Width { get { return (int)this[\"Width\"].GetActualValue(); } set { this[\"Width\"].Value = value; } }\r\n\r\n\t\tpublic int Height { get { return (int)this[\"Height\"].GetActualValue(); } set { this[\"Height\"].Value = value; } }\r\n\r\n\t\tpublic String TextureKey { get { return this[\"Texture\"].GetActualValue().ToString(); } set {\r\n\t\t\t\tthis[\"Texture\"].Value = value; BuildDisplayedImage();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic float Layer { get { return (float)this[\"Layer\"].GetActualValue(); } set { this[\"Layer\"].Value = value; } }\r\n\r\n\t\tpublic RectangleF Region { get { return new RectangleF(Location, Size); } }\r\n\r\n\t\tpublic Size Size { get { return new Size(Width, Height); } }\r\n\r\n\t\tprivate Image displayedImage;\r\n\r\n\t\tprivate System.Drawing.Rectangle? frameRect;\r\n\r\n\t\tpublic GameEntity Entity { get; private set; }\r\n\r\n\t\tpublic String EntityType { get { return Entity.EntityType; } }\r\n\r\n\t\tpublic bool DrawBorder { get; set; } = true;\r\n\r\n\t\tpublic static System.Drawing.Color BorderColor = System.Drawing.Color.BlueViolet;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7240617871284485, "alphanum_fraction": 0.743929386138916, "avg_line_length": 30.35714340209961, "blob_id": "000d8734b447beb72328e77160c5b746fba02493", "content_id": "86cf882fe4e87f543fea4c2c15a8425a2a794371", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 908, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/HollowAether/Lib/GAssets/Items/Gates/OpenGate.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items.Gates {\r\n\tpublic partial class OpenGate : Gate {\r\n\t\tpublic OpenGate() : this(Vector2.Zero, Vector2.Zero) { }\r\n\r\n\t\tpublic OpenGate(Vector2 position, Vector2 takesToZone) : base(position, takesToZone) { }\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = new AnimationSequence(\r\n\t\t\t\t0, new Frame(384, 224, 32, 32, 1, 1, 1)\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic override bool CanInteract { get; protected set; } = true;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6815865635871887, "alphanum_fraction": 0.6826883554458618, "avg_line_length": 41.740962982177734, "blob_id": "e75825f705ecbf2461fa7bb5b45c14393e839d83", "content_id": "e2c4be5be59a8b8972672734c95191417c7b67d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7263, "license_type": "no_license", "max_line_length": 108, "num_lines": 166, "path": "/HollowAether/Lib/InputOutput/OneTimePad.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Encryption {\r\n\t/// <summary>Class to securely encrypt a given peice of data</summary>\r\n\tpublic sealed class OneTimePad : Object {\r\n\t\t/// <summary>Storage class for OneTimePad exceptions</summary>\r\n\t\tpublic static class Exceptions {\r\n\t\t\t/// <summary>Could not find a valid key</summary>\r\n\t\t\tpublic class KeyNotSetException : Exception {\r\n\t\t\t\t#region InheritanceClone\r\n\t\t\t\tpublic KeyNotSetException() : base(\"Key & Alt not set\") { }\r\n\r\n\t\t\t\tpublic KeyNotSetException(String msg) : base(msg) { }\r\n\r\n\t\t\t\tpublic KeyNotSetException(String msg, Exception inner) : base(msg, inner) { }\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Could convert char to int or int to char</summary>\r\n\t\t\tpublic class CharConversionException : Exception {\r\n\t\t\t\t#region InheritanceClone\r\n\t\t\t\tpublic CharConversionException(String msg) : base(msg) { }\r\n\r\n\t\t\t\tpublic CharConversionException(String msg, Exception inner) : base(msg, inner) { }\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Delegate to store methods which convert inbetween encrypted and plain text</summary>\r\n\t\t/// <param name=\"X\">Integer value of 1st value</param> <param name=\"Y\">Integer value of 2nd value</param>\r\n\t\t/// <param name=\"maxX\">The gratest value that can be returned</param>\r\n\t\t/// <returns>Integer position of encrypted or decrypted character</returns>\r\n\t\tprivate delegate int Cryptifier(int X, int Y, int maxX);\r\n\r\n\t\t/// <summary>Initializzer for Onte Time Pad</summary>\r\n\t\t/// <param name=\"_key\">Initial Key for pad to use</param>\r\n\t\tpublic OneTimePad(String _key = null) { padKey = _key; }\r\n\r\n\t\tprivate String GetKey(String alternate = null) {\r\n\t\t\tif (alternate != null) return alternate;\r\n\t\t\telse if (KeySet()) return padKey; // class has key\t\r\n\t\t\telse throw new Exceptions.KeyNotSetException();\r\n\r\n\t\t\t// return KeySet() ? key : alternate; // Unsecure\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks wether stored key is valid</summary>\r\n\t\t/// <returns>Boolean indicating wether class-key can be used</returns>\r\n\t\tpublic Boolean KeySet() { return !(String.IsNullOrWhiteSpace(padKey)); }\r\n\r\n\t\t/// <summary>Cryptifies text using given character array</summary>\r\n\t\t/// <param name=\"text\">Plain text to encrypt/decrypt</param>\r\n\t\t/// <param name=\"key\">Key to encrypt/decrypt with</param>\r\n\t\t/// <param name=\"alphabet\">Character array to use</param>\r\n\t\t/// <param name=\"encrypt\">Wether to encrypt or decrypt</param>\r\n\t\t/// <returns>Encrypted or Decrypted version of plaintext</returns>\r\n\t\tprivate String CryptifyWithAlphabet(String text, String key, Char[] alphabet, bool encrypt) {\r\n\t\t\tCryptifier modificationMethod = (encrypt) ? _encrypter : _decrypter;\r\n\t\t\tStringBuilder container = new StringBuilder(text.Length); // container\r\n\t\t\tkey = GetKey(key); // Ensure key is of correct type and format\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, text.Length)) {\r\n\t\t\t\tif (!alphabet.Contains(text[X])) {\r\n\t\t\t\t\tthrow new Exceptions.CharConversionException(\r\n\t\t\t\t\t\t$\"'{text[X]}' Not Found in Alphabet\"\r\n\t\t\t\t\t);\r\n\t\t\t\t} else if (!alphabet.Contains(key[X % key.Length])) {\r\n\t\t\t\t\tthrow new Exceptions.CharConversionException(\r\n\t\t\t\t\t\t$\"'{key[X % key.Length]}' Not Found in Alphabet\"\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint textIndex = Array.FindIndex(alphabet, (Y) => Y == text[X]);\r\n\t\t\t\tint keyIndex = Array.FindIndex(alphabet, (Y) => Y == key[X % key.Length]);\r\n\r\n\t\t\t\tint encryptedTextIndex = modificationMethod(textIndex, keyIndex, alphabet.Length - 1);\r\n\t\t\t\tcontainer.Append(alphabet[encryptedTextIndex]); // convert new index to character\r\n\t\t\t}\r\n\r\n\t\t\treturn container.ToString();\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts or Decrypts given plaintext with given key</summary>\r\n\t\t/// <param name=\"text\">Plain text to encrypt/decrypt</param>\r\n\t\t/// <param name=\"key\">Key to encrypt/decrypt with</param>\r\n\t\t/// <param name=\"encrypt\">Wether to encrypt or decrypt</param>\r\n\t\t/// <returns>Encrypted or Decrypted version of plaintext</returns>\r\n\t\tprivate String Cryptify(String text, String key, bool encrypt) {\r\n\t\t\tCryptifier modificationMethod = (encrypt) ? _encrypter : _decrypter;\r\n\t\t\tStringBuilder container = new StringBuilder(text.Length); // container\r\n\t\t\tkey = GetKey(key); // Ensure key is of correct type and format\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, text.Length)) {\r\n\t\t\t\tint plainTextIndex, keyTextIndex, encryptedTextIndex;\r\n\r\n\t\t\t\ttry {\r\n\t\t\t\t\tplainTextIndex = CharToInt(text[X]);\r\n\t\t\t\t\tkeyTextIndex = CharToInt(key[X % key.Length]);\r\n\t\t\t\t} catch (OverflowException) { // Char outside bounds of index, unlikely but possible\r\n\t\t\t\t\tthrow new Exceptions.CharConversionException(\r\n\t\t\t\t\t\t$\"'{text[X]}' Or '{key[X % key.Length]}' Could not be converted\"\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tencryptedTextIndex = modificationMethod(plainTextIndex, keyTextIndex, maxCharacterIndex);\r\n\t\t\t\tcontainer.Append(IntToChar(encryptedTextIndex)); // add encrypted char to text container\r\n\t\t\t}\r\n\r\n\t\t\treturn container.ToString();\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts given text</summary>\r\n\t\t/// <param name=\"text\">Plain text to encrypt</param>\r\n\t\t/// <param name=\"key\">Optional key to encrypt with</param>\r\n\t\t/// <returns>Encrypted version of plain text</returns>\r\n\t\tpublic String Encrypt(String text, String key = null) {\r\n\t\t\treturn Cryptify(text, key, true);\r\n\t\t}\r\n\r\n\t\t/// <summary>Decrypts given text</summary>\r\n\t\t/// <param name=\"text\">Plain text to decrypt</param>\r\n\t\t/// <param name=\"key\">Optional key to decrypt with</param>\r\n\t\t/// <returns>Decrypted version of plain text</returns>\r\n\t\tpublic String Decrypt(String text, String key = null) {\r\n\t\t\treturn Cryptify(text, key, false);\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts given text using character array</summary>\r\n\t\t/// <param name=\"text\">Plain text to Encrypt</param>\r\n\t\t/// <param name=\"key\">Optional key to Encrypt with</param>\r\n\t\t/// <param name=\"alphabet\">Character array to encrypt with</param>\r\n\t\t/// <returns>Encrypted version of plain text</returns>\r\n\t\tpublic String EncryptWithAlphabet(String text, String key = null, params Char[] alphabet) {\r\n\t\t\treturn CryptifyWithAlphabet(text, key, alphabet, true);\r\n\t\t}\r\n\r\n\r\n\t\t/// <summary>Decrypts given text</summary>\r\n\t\t/// <param name=\"text\">Plain text to decrypt</param>\r\n\t\t/// <param name=\"key\">Optional key to decrypt with</param>\r\n\t\t/// <param name=\"alphabet\">Character array to decrypt with</param>\r\n\t\t/// <returns>Decrypted version of plain text</returns>\r\n\t\tpublic String DecryptWithAlphabet(String text, String key = null, params Char[] alphabet) {\r\n\t\t\treturn CryptifyWithAlphabet(text, key, alphabet, false);\r\n\t\t}\r\n\r\n\t\t/// <summary>Base key used when no argument key is passed</summary>\r\n\t\tpublic String key { get { return padKey; } set { padKey = value; } }\r\n\r\n\t\tprivate Cryptifier _encrypter = new Cryptifier((int X, int Y, int Z) => (X + Y < Z) ? X + Y : X + Y - Z);\r\n\r\n\t\tprivate Cryptifier _decrypter = new Cryptifier((int X, int Y, int Z) => (X - Y >= 0) ? X - Y : X - Y + Z);\r\n\r\n\t\tpublic Func<int, char> IntToChar = new Func<int, char>(Convert.ToChar); // Converts integer to character\r\n\r\n\t\tpublic Func<char, int> CharToInt = new Func<char, int>(Convert.ToInt32); // Converts Character to integer\r\n\r\n\t\tprivate static int maxCharacterIndex = Char.MaxValue; private String padKey;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7131627202033997, "alphanum_fraction": 0.721859872341156, "avg_line_length": 37.86000061035156, "blob_id": "845619a324aabf20aae08fb4e587ff7e8fefa696", "content_id": "ce6a576d10b38ce1e44008ec5cd18c4e856fe734", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5981, "license_type": "no_license", "max_line_length": 149, "num_lines": 150, "path": "/HollowAether/Lib/GAssets/Boundary/Shapes/IBRotatedRectangle.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class IBRotatedRectangle : IBoundary {\r\n\t\tpublic IBRotatedRectangle(Rectangle rect, float initialRotation, Vector2 rotationOrigin) {\r\n\t\t\torigin = rotationOrigin; // Region from which to rotate around\r\n\t\t\tposition = rect.Location.ToVector2(); // Actual unrotated rectangle\r\n\t\t\tsize = rect.Size;\r\n\t\t\tRotation = initialRotation; // Value by which to rotate rectangle\r\n\r\n\t\t\ttexture = GlobalVars.TextureCreation.GenerateBlankTexture(Color.White, rect.Width, rect.Height);\r\n\t\t}\r\n\r\n\t\tpublic IBRotatedRectangle(Rectangle rect, float rotation) \r\n\t\t\t: this(rect, rotation, new Vector2(rect.Width/2, rect.Height/2)) { }\r\n\r\n\t\tpublic IBRotatedRectangle(int X, int Y, int width, int height, float rotation)\r\n\t\t\t: this(new Rectangle(X, Y, width, height), rotation) { }\r\n\r\n\r\n\t\tpublic IBRotatedRectangle(int X, int Y, int width, int height, float rotation, Vector2 origin)\r\n\t\t\t: this(new Rectangle(X, Y, width, height), rotation, origin) { }\r\n\r\n\t\tpublic void Offset(float X=0, float Y=0) { position += new Vector2(X, Y); Container.Offset(X, Y); }\r\n\r\n\t\tpublic void Offset(Vector2 offset) { position += offset; Container.Offset(X, Y); }\r\n\r\n\t\tprivate static Vector2 RotateVector(Vector2 point, Vector2 origin, float rotation) {\r\n\t\t\tfloat originDeltaX = point.X - origin.X, originDeltaY = point.Y - origin.Y;\r\n\r\n\t\t\treturn new Vector2() { // Create and return new Vector2 representing rotated point\r\n\t\t\t\tX = (float)(origin.X + originDeltaX * Math.Cos(rotation) - originDeltaY * Math.Sin(rotation)),\r\n\t\t\t\tY = (float)(origin.Y + originDeltaY * Math.Cos(rotation) + originDeltaX * Math.Sin(rotation))\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic void Draw(Color color) {\r\n\t\t\tGlobalVars.MonoGameImplement.SpriteBatch.Draw(texture, position, origin: origin, rotation: rotation, color: color, layerDepth: 0.01f);\r\n\t\t}\r\n\r\n\t\tprivate Texture2D texture;\r\n\r\n\t\tpublic bool IsAxisCollision(IBRotatedRectangle rect, Vector2 axis) {\r\n\t\t\tint[] selfScalars = (from X in this.GenerateRotatedPoints() select GetScalar(X, axis)).ToArray(); \r\n\t\t\tint[] rectScalars = (from X in rect.GenerateRotatedPoints() select GetScalar(X, axis)).ToArray();\r\n\r\n\t\t\tint selfMinimum = selfScalars.Min(), selfMaximum = selfScalars.Max();\r\n\t\t\tint rectMinimum = rectScalars.Min(), rectMaximum = rectScalars.Max();\r\n\r\n\t\t\treturn (selfMinimum <= rectMaximum && selfMaximum >= rectMaximum)\r\n\t\t\t\t|| (rectMinimum <= selfMaximum && rectMaximum >= selfMaximum);\r\n\t\t}\r\n\r\n\t\tprivate int GetScalar(Vector2 rectCorner, Vector2 axis) {\r\n\t\t\tfloat numerator = (rectCorner.X * axis.X) + (rectCorner.Y * axis.Y);\r\n\t\t\tfloat denominator = (float)Math.Pow(axis.X, 2) + (float)Math.Pow(axis.Y, 2);\r\n\r\n\t\t\tfloat quotient = numerator / denominator; // Division of numerator and denominator\r\n\t\t\tVector2 projectedCorner = new Vector2(quotient) * axis; // Scale axis by quotient\r\n\r\n\t\t\treturn (int)((axis.X * projectedCorner.X) + (axis.Y * projectedCorner.Y));\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetRotatedUpperLeftCorner() {\r\n\t\t\treturn RotateVector(AxisAllignedTopLeftPoint, AxisAllignedTopLeftPoint + origin, rotation);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetRotatedUpperRightCorner() {\r\n\t\t\treturn RotateVector(AxisAllignedTopRightPoint, AxisAllignedTopRightPoint + new Vector2(-origin.X, origin.Y), rotation);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetRotatedLowerLeftCorner() {\r\n\t\t\treturn RotateVector(AxisAllignedBottomLeftPoint, AxisAllignedBottomLeftPoint + new Vector2(origin.X, -origin.Y), rotation);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetRotatedLowerRightCorner() {\r\n\t\t\treturn RotateVector(AxisAllignedBottomRightPoint, AxisAllignedBottomRightPoint + new Vector2(-origin.X, -origin.Y), rotation);\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<Vector2> GenerateRotatedPoints() {\r\n\t\t\tyield return RotatedTopLeftPoint;\r\n\t\t\tyield return RotatedTopRightPoint;\r\n\t\t\tyield return RotatedBottomLeftPoint;\r\n\t\t\tyield return RotatedBottomRightPoint;\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<Vector2> GeneratePoints() {\r\n\t\t\tyield return AxisAllignedTopLeftPoint;\r\n\t\t\tyield return AxisAllignedTopRightPoint;\r\n\t\t\tyield return AxisAllignedBottomLeftPoint;\r\n\t\t\tyield return AxisAllignedBottomRightPoint;\r\n\t\t}\r\n\r\n\t\tprivate Rectangle GetContainer() {\r\n\t\t\treturn GlobalVars.Physics.GetContainerRectFromVectors(RotatedTopLeftPoint, RotatedTopRightPoint, RotatedBottomLeftPoint, RotatedBottomRightPoint);\r\n\t\t}\r\n\t\t\r\n\t\tpublic Vector2 position;\r\n\r\n\t\tpublic Point size;\r\n\r\n\t\tprivate float rotation;\r\n\r\n\t\tpublic readonly Vector2 origin;\r\n\r\n\t\tpublic float Rotation { get { return rotation; } set {\r\n\t\t\trotation = value; Container = GetContainer(); // Re set container rect as well\r\n\r\n\t\t\tif (rotation > 2 * Math.PI) Rotation -= (float)(2 * Math.PI);\r\n\t\t} }\r\n\r\n\t\tpublic IBRectangle Container { get; private set; }\r\n\r\n\t\t#region AxisAllignedProperties\r\n\t\tpublic float X { get { return position.X; } }\r\n\r\n\t\tpublic float Y { get { return position.Y; } }\r\n\r\n\t\tpublic float Width { get { return position.X + size.X; } }\r\n\r\n\t\tpublic float Height { get { return position.Y + size.Y; } }\r\n\r\n\t\tpublic Vector2 AxisAllignedTopLeftPoint { get { return position; } }\r\n\r\n\t\tpublic Vector2 AxisAllignedTopRightPoint { get { return position + new Vector2(size.X, 0); } }\r\n\r\n\t\tpublic Vector2 AxisAllignedBottomLeftPoint { get { return position + new Vector2(0, size.Y); } }\r\n\r\n\t\tpublic Vector2 AxisAllignedBottomRightPoint { get { return position + new Vector2(size.X, size.Y); } }\r\n\t\t#endregion\r\n\r\n\t\t#region RotatedProperties\r\n\t\tpublic Vector2 RotatedTopLeftPoint { get { return GetRotatedUpperLeftCorner(); } }\r\n\r\n\t\tpublic Vector2 RotatedTopRightPoint { get { return GetRotatedUpperRightCorner(); } }\r\n\r\n\t\tpublic Vector2 RotatedBottomLeftPoint { get { return GetRotatedLowerLeftCorner(); } }\r\n\r\n\t\tpublic Vector2 RotatedBottomRightPoint { get { return GetRotatedLowerRightCorner(); } }\r\n\t\t#endregion\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6813042163848877, "alphanum_fraction": 0.6834078431129456, "avg_line_length": 35.2843132019043, "blob_id": "0e8d8c39f40a5bd3b4688a07c787ae68b402d88f", "content_id": "bda9406c97b3577652cade4bd02ec987ecbdd460", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3805, "license_type": "no_license", "max_line_length": 122, "num_lines": 102, "path": "/HollowAether/Lib/GAssets/Boundary/Container/Assistance/CollisionCalculators.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.Boundary {\r\n\tpublic static class CollisionCalculators {\r\n\t\tpublic delegate IntersectingPositions CollisionCalculator(IBoundary self, IBoundary target);\r\n\r\n\t\tpublic static IntersectingPositions CalculateCollision(IBoundary A, IBoundary B) {\r\n\t\t\tFunc<IBoundary, String> BoundaryToString = (X) => {\r\n\t\t\t\tif (X is IBRectangle) return \"Rectangle\";\r\n\t\t\t\telse if (X is IBTriangle) return \"Triangle\";\r\n\t\t\t\telse if (X is IBCircle) return \"Circle\";\r\n\t\t\t\telse return String.Empty;\r\n\t\t\t};\r\n\r\n\t\t\tswitch (BoundaryToString(A)) {\r\n\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t#region RectangleCalcBody\r\n\t\t\t\t\tswitch (BoundaryToString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn CollisionCalculators.RectangleToRectangle(A, B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn RectangleToTriangle(A, B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\tdefault: return IntersectingPositions.Empty;\r\n\t\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t#region TriangleCalcBody\r\n\t\t\t\t\tswitch (BoundaryToString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn TriangleToRectangle(A, B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn TriangleToTriangle(A, B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\tdefault: return IntersectingPositions.Empty;\r\n\t\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\treturn IntersectingPositions.Empty;\r\n\t\t\t\tdefault: return null;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic CollisionCalculator RectangleToRectangle = (self, target) => {\r\n\t\t\tIBRectangle IBself = (IBRectangle)self, IBtarget = (IBRectangle)target;\r\n\r\n\t\t\treturn new IntersectingPositions() {\r\n\t\t\t\t{ Direction.Top, IBtarget.Top }, { Direction.Bottom, IBtarget.Bottom },\r\n\t\t\t\t{ Direction.Left, IBtarget.Left }, { Direction.Right, IBtarget.Right }\r\n\t\t\t};\r\n\t\t};\r\n\r\n\t\tstatic CollisionCalculator RectangleToTriangle = (self, target) => {\r\n\t\t\tIBRectangle IBself = (IBRectangle)self; IBTriangle IBtarget = (IBTriangle)target;\r\n\r\n\t\t\tList<Vector2> verticalIntersectionPoints = new List<Vector2>(4), horizontalIntersectionPoints = new List<Vector2>(4);\r\n\r\n\t\t\tforeach (Line X in GV.Convert.TriangleTo3Lines(IBtarget)) {\r\n\t\t\t\tforeach (Line Y in GV.Convert.RectangleTo4Lines(IBself)) {\r\n\t\t\t\t\tif (X.Intersects(Y)) {\r\n\t\t\t\t\t\tVector2? intersectionPoint = X.GetIntersectionPoint(Y);\r\n\r\n\t\t\t\t\t\tif (!intersectionPoint.HasValue || float.IsNaN(intersectionPoint.Value.X) || float.IsNaN(intersectionPoint.Value.Y))\r\n\t\t\t\t\t\t\tcontinue; // No valid intersection value has been found, therefore skip addition to container values \r\n\r\n\t\t\t\t\t\tif (Y.type == Line.LineType.Normal) {\r\n\t\t\t\t\t\t\thorizontalIntersectionPoints.Add(intersectionPoint.Value);\r\n\t\t\t\t\t\t} else { // Y.type == Line.LineType.XEquals\r\n\t\t\t\t\t\t\tverticalIntersectionPoints.Add(intersectionPoint.Value);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn new IntersectingPositions() {\r\n\t\t\t\t{ Direction.Top, (int)((from X in verticalIntersectionPoints select X.Y).Aggregate(Math.Min)) },\r\n\t\t\t\t{ Direction.Bottom, (int)((from X in verticalIntersectionPoints select X.Y).Aggregate(Math.Max)) },\r\n\t\t\t\t{ Direction.Left, (int)((from X in horizontalIntersectionPoints select X.X).Aggregate(Math.Min)) },\r\n\t\t\t\t{ Direction.Right, (int)((from X in horizontalIntersectionPoints select X.X).Aggregate(Math.Max)) }\r\n\t\t\t};\r\n\t\t};\r\n\r\n\t\tstatic CollisionCalculator TriangleToRectangle = (self, target) => {\r\n\t\t\tIBTriangle IBself = (IBTriangle)self; IBRectangle IBtarget = (IBRectangle)target;\r\n\r\n\t\t\treturn IntersectingPositions.Empty;\r\n\t\t};\r\n\r\n\t\tstatic CollisionCalculator TriangleToTriangle = (self, target) => {\r\n\t\t\tIBTriangle IBself = (IBTriangle)self; IBTriangle IBtarget = (IBTriangle)target;\r\n\r\n\t\t\treturn IntersectingPositions.Empty;\r\n\t\t};\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6882572770118713, "alphanum_fraction": 0.6955044865608215, "avg_line_length": 36.07327651977539, "blob_id": "69566f3ed81ed4790ed2154f16235e5123bc9cd8", "content_id": "9f512a99841b86110eee25b0effdf200eb6595a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8833, "license_type": "no_license", "max_line_length": 115, "num_lines": 232, "path": "/HollowAether/Lib/GAssets/Camera/CameraBUP2.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "/*#region SystemImports\r\nusing System.Linq;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary> Camera class allowing game to instantiate and use a camera instance\r\n\t/// to view game instances. Customised Derivative Camera Class Inspired by source on\r\n\t/// : http://www.dylanwilson.net/implementing-a-2d-camera-in-monogame : </summary>\r\n\t/// <Note> Note any sprite batches begun with a Camera2D Matrix must have a default\r\n\t/// scale value of 0.1 or greater, anything lower will not be visible at all </Note>\r\n\tpublic class Camera2D {\r\n\t\t/// <summary>Camera behaviour defintions</summary>\r\n\t\t/// Fixed keeps camera in current position until behaviour is changed\r\n\t\t/// Centred keeps camera centred on a given target monogame object\r\n\t\t/// Forward makes camera face directly in front of given target\r\n\t\t/// Smart has it's own life. Don't bother trying to understand it\r\n\t\t/// <remarks>http://yuanworks.com/little-ninja-dev-smart-camera-movement/</remarks>\r\n\t\tpublic enum CameraType { Fixed, Centred, Forward, Smart }\r\n\r\n\t\t/// <summary>Class to hold relevent data for camera transition</summary>\r\n\t\tclass TransitionArgs {\r\n\t\t\t/// <summary>Defualt constructor</summary>\r\n\t\t\t/// <param name=\"pos\">Position to transition to</param>\r\n\t\t\t/// <param name=\"time\">Time over wich to transition</param>\r\n\t\t\tpublic TransitionArgs(Vector2 pos, float time) {\r\n\t\t\t\ttarget = pos;\r\n\t\t\t\ttiming = time;\r\n\t\t\t\ttimeCounter = 0;\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Updates transition and gets new position</summary>\r\n\t\t\t/// <param name=\"position\">Current position of camera</param>\r\n\t\t\t/// <returns>New position for camera</returns>\r\n\t\t\tpublic Vector2 Update(Vector2 position) {\r\n\t\t\t\ttimeCounter += GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t\treturn Vector2.Lerp(position, target, timeCounter / timing);\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Checks whether rounded values for given vectors match</summary>\r\n\t\t\t/// <param name=\"position\">Vector value to check equality with</param>\r\n\t\t\t/// <returns>Whether rounded values for two vectors are the same</returns>\r\n\t\t\tpublic bool EqualsRoundedTarget(Vector2 position) {\r\n\t\t\t\treturn Math.Round(position.X) == Math.Round(target.X) && Math.Round(position.Y) == Math.Round(target.Y);\r\n\t\t\t}\r\n\r\n\t\t\tpublic Vector2 target;\r\n\t\t\tfloat timing;\r\n\t\t\tfloat timeCounter;\r\n\t\t}\r\n\r\n\t\t/// <summary> Base constructor to create a 2Dimensional camera </summary>\r\n\t\t/// <param name=\"zoom\">Signifies maximum sprite scale zoom, value must be float above 0.1</param>\r\n\t\t/// <param name=\"type\">Type of camera algorithm to follow by default :)</param>\r\n\t\t/// <param name=\"percentageRotation\">Value representing the degrees of rotation to set the camera to</param>\r\n\t\tpublic Camera2D(CameraType type=CameraType.Centred, float zoom=1.0f, float percentageRotation=0.0f) {\r\n\t\t\tRotation = percentageRotation;\r\n\t\t\tScale = zoom;\r\n\t\t\tcameraType = type;\r\n\t\t\tsmartCameraRect = new Rectangle(0, 0, target.SpriteRect.Width * 2, target.SpriteRect.Height * 3);\r\n\t\t}\r\n\r\n\t\t/// <summary> Function to create and return a ViewMatrix Instance </summary>\r\n\t\t/// <returns> Single Matrix value, showing dimensions of camera </returns>\r\n\t\tpublic Matrix GetViewMatrix() {\r\n\t\t\tMatrix[] container = new Matrix[5]; int counter = 0; Vector2 origin = GetScaledOrigin();\r\n\r\n\t\t\t// Constructs a Matrix Container and incrementor, to construct a ViewMatrix\r\n\t\t\tforeach (Vector2 X in new Vector2[] { -_position, -origin, origin })\r\n\t\t\t\t// Loops for three different potential vectors required to influence ViewMatrix\r\n\t\t\t\tcontainer[counter++] = Matrix.CreateTranslation(new Vector3(X, 0f));\r\n\t\t\t// Translates and stores new vectors to Matrix Container for aggregation\r\n\r\n\t\t\tcontainer[counter++] = Matrix.CreateRotationZ(Rotation); // adds rotation\r\n\t\t\tcontainer[counter++] = Matrix.CreateScale(Scale, Scale, 1.0f);\r\n\t\t\t// and scale Matrices to simplify implementation of ViewMatrix through aggregation\r\n\r\n\t\t\treturn container.Aggregate((Matrix a, Matrix b) => { return a * b; });\r\n\t\t\t// Agrregates and then returns ViewMatrix using local Lambda Function\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch();\r\n\t\t\t//GV.DrawMethods.DrawRectangleFrame(smartCameraRect, Color.Green);\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic void Update() {\r\n\t\t\tVector2 newCameraPosition; // Variable to hold new camera position before clamping\r\n\t\t\t//ZoneBoundaries boundary = GV.MonoGameImplement.map.currentZone.zoneBoundaries;\r\n\r\n\t\t\tif (transitionArgs != null) {\r\n\t\t\t\tnewCameraPosition = transitionArgs.Update(_position);\r\n\r\n\t\t\t\tif (transitionArgs.EqualsRoundedTarget(newCameraPosition)) {\r\n\t\t\t\t\tnewCameraPosition = transitionArgs.target;\r\n\t\t\t\t\tStopTransition(); // Stop running transition\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tswitch (cameraType) {\r\n\t\t\t\t\tcase CameraType.Centred:\r\n\t\t\t\t\t\tnewCameraPosition = GetCentreVect();\r\n\t\t\t\t\t\t_position = newCameraPosition;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase CameraType.Forward:\r\n\t\t\t\t\t\tnewCameraPosition = GetCentreVect() + forwardOffset;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase CameraType.Smart:\r\n\t\t\t\t\t\tnewCameraPosition = SmartUpdate();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase CameraType.Fixed:\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\treturn; // Fixed so nothing to do. \r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/*if (!clampToZoneBoundaries) { _position = newCameraPosition; } else {\r\n\t\t\t\t_position.X = GV.BasicMath.Clamp(newCameraPosition.X, boundary.minX, boundary.maxX);\r\n\t\t\t\t_position.Y = GV.BasicMath.Clamp(newCameraPosition.Y, boundary.minY, boundary.maxY);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool ContainedInCamera(Rectangle rect) {\r\n\t\t\tPoint cameraSize = new Point((int)(GV.Variables.windowWidth / Scale), (int)(GV.Variables.windowHeight / Scale));\r\n\t\t\tRectangle cameraRect = new Rectangle(Position.ToPoint(), cameraSize); // Convert camera to viewport rectangle \r\n\r\n\t\t\treturn cameraRect.Intersects(rect); // Use existing rectangle intersection detection method to determine\r\n\t\t}\r\n\r\n\t\tprivate Vector2 GetCentreVect() {\r\n\t\t\treturn new Vector2(target.Position.X - GetScaledOrigin().X, target.Position.Y - GetScaledOrigin().Y);\r\n\t\t}\r\n\r\n\t\tprivate Vector2 SmartUpdate() {\r\n\t\t\tVector2 newPosition = smartCameraRect.Location.ToVector2(); // default = current\r\n\r\n\t\t\tif (!smartCameraRect.Contains(target.SpriteRect)) {\r\n\t\t\t\tif (target.SpriteRect.Left <= smartCameraRect.Left) {\r\n\t\t\t\t\tsmartCameraRect.X = target.SpriteRect.X; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (target.SpriteRect.Right >= smartCameraRect.Right) {\r\n\t\t\t\t\tsmartCameraRect.X = target.SpriteRect.X - smartCameraRect.Width + target.SpriteRect.Width;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (target.SpriteRect.Top <= smartCameraRect.Top) {\r\n\t\t\t\t\tsmartCameraRect.Y = target.SpriteRect.Y;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (target.SpriteRect.Bottom >= smartCameraRect.Bottom) {\r\n\t\t\t\t\tsmartCameraRect.Y = target.SpriteRect.Y - smartCameraRect.Height + target.SpriteRect.Height;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn newPosition - SmartCameraOffset;\r\n\t\t}\r\n\r\n\t\tpublic void Offset(Vector2 argVect) {\r\n\t\t\t_position += new Vector2(argVect.X, argVect.Y);\r\n\t\t}\r\n\r\n\t\tpublic void Offset(int X = 0, int Y = 0) {\r\n\t\t\tOffset(new Vector2(X, Y));\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetCenterOfScreen() {\r\n\t\t\treturn new Vector2(\r\n\t\t\t\t(_position.X + GV.hollowAether.GraphicsDevice.Viewport.Width) / 2,\r\n\t\t\t\t(_position.Y + GV.hollowAether.GraphicsDevice.Viewport.Height) / 2\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetScaledOrigin() {\r\n\t\t\treturn GetCenterOfScreen() / Scale;\r\n\t\t}\r\n\r\n\t\tpublic void ChangeCameraTarget() {\r\n\r\n\t\t}\r\n\r\n\t\tpublic void StartTransition(Vector2 position, float time) {\r\n\t\t\ttransitionArgs = new TransitionArgs(position, time);\r\n\t\t}\r\n\r\n\t\tpublic void StartTransition(float X, float Y, float time) {\r\n\t\t\tStartTransition(new Vector2(X, Y), time);\r\n\t\t}\r\n\r\n\t\tpublic void StopTransition() {\r\n\t\t\ttransitionArgs = null;\r\n\t\t}\r\n\r\n\t\tpublic event Action ZoomChanged = () => { };\r\n\r\n\t\tCameraType cameraType;\r\n\t\tfloat _scale, _rotation;\r\n\t\tVector2 _position;\r\n\t\tTransitionArgs transitionArgs;\r\n\t\tRectangle smartCameraRect;\r\n\t\tpublic Vector2 forwardOffset = new Vector2(64, 0);\r\n\r\n\t\tpublic bool ClampToZoneBoundaries { get; set; } = true;\r\n\t\tpublic float Scale { get { return _scale; } set { _scale = value; ZoomChanged(); } }\r\n\t\tpublic float Rotation { get { return _rotation; } set { _rotation = value; } }\r\n\t\tpublic Vector2 Position { get { return _position; } private set { _position = value; } }\r\n\r\n\t\tprivate Vector2 SmartCameraOffset {\r\n\t\t\tget {\r\n\t\t\t\treturn new Vector2(\r\n\t\t\t\t\t((GV.Variables.windowWidth * 0.5f) - smartCameraRect.Width) / (2 * Scale), \r\n\t\t\t\t\t(GV.Variables.windowHeight - smartCameraRect.Height) / (2 * Scale)\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tIMonoGameObject target { get { return GV.MonoGameImplement.Player; } }\r\n\t}\r\n}\r\n\r\n*/" }, { "alpha_fraction": 0.7427027225494385, "alphanum_fraction": 0.7427027225494385, "avg_line_length": 44.25, "blob_id": "2b676c46b7dc61f33ca0330dc3a5d92149a58c2f", "content_id": "847645d3838404065c1cc3cbae15cf5da49a7941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 927, "license_type": "no_license", "max_line_length": 107, "num_lines": 20, "path": "/HollowAether/Lib/Global/GameStates.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary>Enumeration to hold the current state of the game</summary>\r\n\tpublic enum GameState {\r\n\t\tGameRunning, /// <summary>Game state which actually manages game-play assets etc.</summary>\r\n\t\tHome, /// <summary>Main game state which the player is shown upon starting the game</summary>\r\n\t\tSaveLoad, /// <summary>State from which to load an existing save or choose to create a new save</summary>\r\n\t\tPlayerDeceased,\r\n\t\tSettings, /// <summary>State from where the player can modify window settings etc.</summary>\r\n\t\tCredits, /// <summary>Game state from which all contributors to the game will be mentioned</summary> \r\n\t\tGamePaused /// <summary>Pause window shown; Where gamerunning is still drawn, but not updated</summary>\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6660131812095642, "alphanum_fraction": 0.67207270860672, "avg_line_length": 37.51408386230469, "blob_id": "33ced3562ea4b81d8e73a3faa9454445e2daa834", "content_id": "059199fc454d046d92ca6a7b25e9b19331e37994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5613, "license_type": "no_license", "max_line_length": 139, "num_lines": 142, "path": "/HollowAether/Lib/GAssets/Animation/Frame.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing System.Text.RegularExpressions;\r\n\r\nusing HollowAether.Lib.Exceptions;\r\nusing Converters = HollowAether.Lib.InputOutput.Parsers.Converters;\r\nusing Parsers = HollowAether.Lib.InputOutput.Parsers.Parser;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic struct Frame {\r\n\t\t/// <summary> Holds sprite frame location in a given spritesheet </summary>\r\n\t\t/// <param name=\"fWidth\">Sprite Frame Width</param>\r\n\t\t/// <param name=\"fHeight\">Sprite Frame Height</param>\r\n\t\t/// <param name=\"xPos\">relative X position of sprite</param>\r\n\t\t/// <param name=\"yPos\">relative Y position of sprite</param>\r\n\t\t/// <param name=\"bWidth\">block width</param>\r\n\t\t/// <param name=\"bHeight\">block height</param>\r\n\t\tpublic Frame(int xPos, int yPos, int fWidth, int fHeight, int bWidth=defaultBlockWidth, int bHeight=defaultBlockHeight, int runCount=1) {\r\n\t\t\t_frameWidth = fWidth; // Width of sprite in frame\r\n\t\t\t_frameHeight = fHeight; // Height of sprite in frame\r\n\t\t\t_blockWidth = bWidth; // Width of sprites leading upto frame sprite\r\n\t\t\t_blockHeight = bHeight; // Height of sprites leading upto frame sprite\r\n\t\t\t_xPos = xPos; // relative X position of sprite in spritesheet\r\n\t\t\t_yPos = yPos; // relative Y position of sprite in spritesheet\r\n\t\t\tRunCount = runCount;\r\n\t\t}\r\n\r\n\t\tpublic Frame(System.Drawing.Rectangle rect) : this(rect.X, rect.Y, rect.Width, rect.Height, 1, 1, 1) {\r\n\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets buildup sprite dimensions</summary>\r\n\t\t/// <param name=\"X\">Width of buildup sprites</param>\r\n\t\t/// <param name=\"Y\">Height of buildup sprites</param>\r\n\t\tpublic void SetBlockDimensions(int X, int Y) {\r\n\t\t\t_blockWidth = X;\r\n\t\t\t_blockHeight = Y;\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({xPosition}, {yPosition}, {frameWidth}, {frameHeight} : {blockWidth}, {blockHeight})\";\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets buildup sprite dimensions</summary>\r\n\t\t/// <param name=\"vect\">Vector representing buildup sprite dimensions</param>\r\n\t\tpublic void SetBlockDimensions(Vector2 vect) {\r\n\t\t\tSetBlockDimensions((int)vect.X, (int)vect.Y);\r\n\t\t}\r\n\r\n\t\tpublic String ToFileContents() {\r\n\t\t\treturn $\"{xPosition}, {yPosition}, {frameWidth}, {frameHeight} : {blockWidth}, {blockHeight} -> {RunCount}\";\r\n\t\t}\r\n\r\n\t\tpublic static Frame FromFileContents(String line, bool throwException=false) {\r\n\t\t\tRegex r = new Regex(@\"(\\d+[, ]*)+(:[, ]*(\\d+[, ]*)+)?->[, ]*\\d+\");\r\n\t\t\t\r\n\t\t\tif (isFrameDefinitionRegexCheck.IsMatch(line)) {\r\n\t\t\t\tint[] values = Parsers.IntegerParser(line); // Array of length 6, corresponding to all integer values\r\n\r\n\t\t\t\tif (!line.Contains(\":\")) return new Frame(values[0], values[1], values[2], values[3], runCount: values[4]); else {\r\n\t\t\t\t\treturn new Frame(values[0], values[1], values[2], values[3], values[4], values[5], values[6]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (!throwException) return Frame.Zero; else { // Raise new exception\r\n\t\t\t\t\tthrow new HollowAetherException($\"'{line}' Is Not A Valid Frame Definition\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static Regex isFrameDefinitionRegexCheck = new Regex(@\"(\\d+[, ]*)+(:[, ]*(\\d+[, ]*)+)?->[, ]*\\d+\");\r\n\r\n\t\t/// <summary>Sets buildup sprite dimensions</summary>\r\n\t\t/// <param name=\"tup\">Tuple representing buildup sprite dimension</param>\r\n\t\tpublic void SetBlockDimensions(Tuple<int, int> tup) {\r\n\t\t\tSetBlockDimensions(tup.Item1, tup.Item2);\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets frame dimensions</summary>\r\n\t\t/// <param name=\"X\">Width of frame</param>\r\n\t\t/// <param name=\"Y\">Height of frame</param>\r\n\t\tpublic void SetFrameDimensions(int X, int Y) {\r\n\t\t\t_frameWidth = X;\r\n\t\t\t_frameHeight = Y;\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets frame dimensions</summary>\r\n\t\t/// <param name=\"vect\">Vector representing frame dimensions</param>\r\n\t\tpublic void SetFrameDimensions(Vector2 vect) {\r\n\t\t\tSetFrameDimensions((int)vect.X, (int)vect.Y);\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets frame dimensions</summary>\r\n\t\t/// <param name=\"tup\">Tuple representing frame dimension</param>\r\n\t\tpublic void SetFrameDimensions(Tuple<int, int> tup) {\r\n\t\t\tSetFrameDimensions(tup.Item1, tup.Item2);\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts frame to source rectangle</summary>\r\n\t\t/// <returns>Rectangle representing source of frame on spritesheet</returns>\r\n\t\tpublic Rectangle ToRect() {\r\n\t\t\treturn new Rectangle(_blockWidth * _xPos, _blockHeight * _yPos, _frameWidth, _frameHeight);\r\n\t\t}\r\n\r\n\t\tpublic System.Drawing.Rectangle ToDrawingRect() {\r\n\t\t\treturn new System.Drawing.Rectangle(_blockWidth * _xPos, _blockHeight * _yPos, _frameWidth, _frameHeight);\r\n\t\t}\r\n\r\n\t\tprivate int _frameWidth, _frameHeight, _blockWidth, _blockHeight, _xPos, _yPos;\r\n\r\n\t\tpublic const int defaultBlockWidth = 32, defaultBlockHeight = 32;\r\n\r\n\t\tpublic static Frame Zero { get { return new Frame(0, 0, 0, 0, 0, 0, 0); } }\r\n\r\n\t\tpublic int RunCount { get; /*private*/ set; }\r\n\r\n\t\tpublic int frameWidth { get { return _frameWidth; } set { _frameWidth = value; } }\r\n\r\n\t\tpublic int frameHeight { get { return _frameHeight; } set { _frameHeight = value; } }\r\n\r\n\t\tpublic int blockWidth { get { return _blockWidth; } set { _blockWidth = value; } }\r\n\r\n\t\tpublic int blockHeight { get { return _blockHeight; } set { _blockHeight = value; } }\r\n\r\n\t\tpublic int xPosition { get { return _xPos; } set { _xPos = value; } }\r\n\r\n\t\tpublic int yPosition { get { return _yPos; } set { _yPos = value; } }\r\n\r\n\t\tpublic Rectangle frame { get { return ToRect(); } } // Frame to source Rectangle\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7038094997406006, "alphanum_fraction": 0.715238094329834, "avg_line_length": 35.5, "blob_id": "dea0e0134bc192079af5e578e217a86cf20f9a2f", "content_id": "9440f63cb62cf57c9d442077d33a892ee7dfbeef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2102, "license_type": "no_license", "max_line_length": 123, "num_lines": 56, "path": "/HollowAether/Lib/GAssets/Items/Chests/Chest.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic abstract class Chest : BodySprite, IInteractable {\r\n\t\tpublic Chest(Vector2 position) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT) {\r\n\t\t\tInitialize(\"items\\\\chest\");\r\n\t\t\tLayer = 0.4f;\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\r\n\t\t\tImplementGravity(); // Gravity not automatically implemented\r\n\t\t\tCanInteract = !(Falling(0, 1)); // Don't allow interaction when falling\r\n\t\t}\r\n\r\n\t\tpublic void Interact() {\r\n\t\t\tif (CanInteract && !Interacted) {\r\n\t\t\t\tAnimation.ChainFinished += ChainFinishedHandler; // Handler attatched\r\n\t\t\t\tAnimation.AttatchAnimationChain(new AnimationChain(Animation[\"opened\"]));\r\n\t\t\t\tInteracted = true; // Don't interact again\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected abstract void ReleaseContents();\r\n\r\n\t\tprivate void ChainFinishedHandler(AnimationChain chain) {\r\n\t\t\tReleaseContents(); /* Begin contents release */\r\n\t\t\tAnimation.SetAnimationSequence(\"finished\");\r\n\t\t\tAnimation.ChainFinished -= ChainFinishedHandler;\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"begun\"] = new AnimationSequence(0, new Frame(0, 0, FRAME_WIDTH, FRAME_HEIGHT)); // Ignore Block Dimensions\r\n\t\t\tAnimation[\"finished\"] = new AnimationSequence(0, new Frame(7, 0, FRAME_WIDTH, FRAME_HEIGHT, FRAME_WIDTH, FRAME_HEIGHT));\r\n\t\t\tAnimation[\"opened\"] = AnimationSequence.FromRange(FRAME_WIDTH, FRAME_HEIGHT, 0, 0, 8, FRAME_WIDTH, FRAME_HEIGHT, 5);\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"begun\"); // Set animation sequence to inital animation frame. Ignore others for now.\r\n\t\t}\r\n\r\n\t\tpublic bool Interacted { get; private set; } = false;\r\n\r\n\t\tpublic bool CanInteract { get; private set; } = true;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 42, SPRITE_HEIGHT = 24;\r\n\t\tpublic const int FRAME_WIDTH = 126, FRAME_HEIGHT = 72;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7231976389884949, "alphanum_fraction": 0.7273066639900208, "avg_line_length": 36.24285888671875, "blob_id": "ed132982e5a9a97dd634caf30688b9c7a76d6441", "content_id": "df0e93009d1445a876db72b95540dbb0a571c969", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2679, "license_type": "no_license", "max_line_length": 111, "num_lines": 70, "path": "/HollowAether/Lib/Global/GlobalVars/ImageManipulation.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class ImageManipulation {\r\n\t\t\t/// <summary>Crops a bitmap image instance using a rectangle</summary>\r\n\t\t\t/// <param name=\"img\">Bitmap instance to crop using a rectangle</param>\r\n\t\t\t/// <param name=\"cropArea\">Rectangle representing area in image</param>\r\n\t\t\t/// <returns>Cropped Image</returns>\r\n\t\t\tpublic static System.Drawing.Image CropImage(System.Drawing.Bitmap img, System.Drawing.Rectangle cropArea) {\r\n\t\t\t\treturn img.Clone(cropArea, img.PixelFormat);\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Crops an Image instance using a rectangle</summary>\r\n\t\t\t/// <param name=\"img\">Image instance to crop using a rectangle</param>\r\n\t\t\t/// <param name=\"cropArea\">Rectangle representing area in image</param>\r\n\t\t\t/// <returns>Cropped Image</returns>\r\n\t\t\tpublic static System.Drawing.Image CropImage(System.Drawing.Image img, System.Drawing.Rectangle cropArea) {\r\n\t\t\t\treturn CropImage(new System.Drawing.Bitmap(img), cropArea);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Texture2D CreateCircleTexture(int frameRadius, Color circleColor) {\r\n\t\t\t\tTexture2D circleFrame = new Texture2D(GlobalVars.hollowAether.GraphicsDevice, frameRadius, frameRadius);\r\n\r\n\t\t\t\tColor[] circleColorData = new Color[(int)Math.Pow(frameRadius, 2)]; // 1 Dimensional texture data\r\n\r\n\t\t\t\tfloat diam = frameRadius / 2f, diamSquared = (float)Math.Pow(diam, 2); // Used for checking\r\n\t\t\t\tFunc<float, bool> Check = (posLengthSquared) => (posLengthSquared <= diamSquared);\r\n\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, frameRadius)) {\r\n\t\t\t\t\tforeach (int Y in Enumerable.Range(0, frameRadius)) {\r\n\t\t\t\t\t\tVector2 pos = new Vector2(X - diam, Y - diam); // Position in texture\r\n\t\t\t\t\t\tColor color = Check(pos.LengthSquared()) ? circleColor : Color.Transparent;\r\n\r\n\t\t\t\t\t\tcircleColorData[X * frameRadius + Y] = color; // Set Desired Color\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcircleFrame.SetData<Color>(circleColorData);\r\n\t\t\t\treturn circleFrame; // return circle texture\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7104583978652954, "alphanum_fraction": 0.712442934513092, "avg_line_length": 30.522581100463867, "blob_id": "bd56b8c869c25d6b960086f592360941ff52c057", "content_id": "f0c572ec87896e514ba65543009a2dfc6dc8f9a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5041, "license_type": "no_license", "max_line_length": 109, "num_lines": 155, "path": "/HollowAether/Lib/InputOutput/MapZone/Zone.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\n\r\nnamespace HollowAether.Lib.MapZone {\r\n\tpublic class Zone {\r\n\t\t/// <summary>Used to check whether a given condition is valid</summary>\r\n\t\t/// <returns>Boolean indicating whether conditional expression has succeeded</returns>\r\n\t\tpublic delegate bool Condition();\r\n\t\t\r\n\t\tpublic Zone(String filePath, bool _visible=false, bool initialiseNow=false) {\r\n\t\t\tFilePath = GetRelativeFilePath(filePath);\r\n\t\t\tvisible = _visible; // Whether zone is visible\r\n\t\t\tif (initialiseNow) Initialize(); // From construction\r\n\t\t}\r\n\r\n\t\tpublic Zone(Map.ZoneArgs args, bool initialiseNow=false) : this(args.path, args.visible, initialiseNow) { }\r\n\r\n\t\tpublic static String GetRelativeFilePath(String filePath) {\r\n\t\t\tif (IOMan.FileExists(filePath)) return filePath; else {\r\n\t\t\t\tString mapContainer = IOMan.GetDirectoryName(GV.MonoGameImplement.map.FilePath);\r\n\t\t\t\tString adjusted = System.IO.Path.GetFullPath(IOMan.Join(mapContainer, filePath));\r\n\r\n\t\t\t\tif (IOMan.FileExists(adjusted)) return adjusted; else {\r\n\t\t\t\t\tthrow new ZoneNotFoundException(filePath);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Initialize() {\r\n\t\t\tif (!initialized) {\r\n\t\t\t\tZoneParser.Parse(this);\r\n\r\n\t\t\t\tinitialized = true; // Now initialised\r\n\t\t\t}\r\n\r\n\t\t\t/*foreach (IMonoGameObject _object in monogameObjects) {\r\n\t\t\t\t_object.Initialize(_object.Animation.TextureID);\r\n\t\t\t}*/\r\n\t\t}\r\n\r\n\t\tpublic bool Contains(Vector2 pos) {\r\n\t\t\treturn new Rectangle(Point.Zero, new Point(ZoneWidth, ZoneHeight)).Contains(pos);\r\n\t\t}\r\n\r\n\t\tpublic static bool CreateEmptyZone(String fpath) {\r\n\t\t\ttry {\r\n\t\t\t\tstring fileContents = $\"{ZONE_FILE_HEADER} # Header\\n\";\r\n\t\t\t\tIOMan.WriteEncryptedFile(fpath, fileContents, GV.Encryption.oneTimePad);\r\n\t\t\t} catch { return false; }\r\n\t\t\t\r\n\t\t\treturn true; // Succesfully made \r\n\t\t}\r\n\r\n\t\tpublic void Update() {\r\n\t\t\t/*if (runtimeEvents.Count < 1) return; // prevent wasted CPU usage\r\n\r\n\t\t\tList<Condition> removalBatch = new List<Condition>(runtimeEvents.Count);\r\n\r\n\t\t\tforeach (Condition conditionalEvent in runtimeEvents.Keys) {\r\n\t\t\t\tif (!conditionalEvent()) continue; // Condition Not Yet Valid\r\n\r\n\t\t\t\tforeach (Action func in runtimeEvents[conditionalEvent])\r\n\t\t\t\t\tfunc(); // Execute Command Here\r\n\r\n\t\t\t\tremovalBatch.Add(conditionalEvent); // Mark Method for removal\r\n\t\t\t}\r\n\r\n\t\t\tforeach (Condition condition in removalBatch) {\r\n\t\t\t\truntimeEvents.Remove(condition);\r\n\t\t\t}*/\r\n\t\t}\r\n\r\n\t\tpublic void AddZoneToSpriteBatch() {\r\n\t\t\tforeach (String entityKey in zoneEntities.Keys) {\r\n\t\t\t\tGameEntity entity = zoneEntities[entityKey];\r\n\r\n\t\t\t\tIMonoGameObject _object = entity.ToIMGO();\r\n\t\t\t\t_object.SpriteID = entityKey; // Set ID\r\n\t\t\t\t_object.Initialize(_object.Animation.TextureID);\r\n\r\n\t\t\t\tGV.MonoGameImplement.monogameObjects.Add(_object);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void RemoveZoneFromSpriteBatch() {\r\n\t\t\tforeach (string entityKey in zoneEntities.Keys) {\r\n\t\t\t\tif (GV.MonoGameImplement.monogameObjects.Exists(entityKey))\r\n\t\t\t\t\tGV.MonoGameImplement.monogameObjects.Remove(entityKey);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static String ZONE_FILE_HEADER = \"ZNE\";\r\n\r\n\t\t/// <summary>File path of zone file</summary>\r\n\t\tpublic String FilePath { get; private set; }\r\n\r\n\t\t/// <summary>Zone is visible in map HUD</summary>\r\n\t\tpublic bool visible;\r\n\r\n\t\t/// <summary>Map has been initialised</summary>\r\n\t\tpublic bool initialized;\r\n\r\n\t\t/// <summary>Local Asset Store</summary>\r\n\t\tpublic AssetContainer assets = new AssetContainer();\r\n\r\n\t\t/// <summary>Keep conditional blocks for Level Editor</summary>\r\n\t\t//public static bool keepBlocks = false; \r\n\r\n\t\t/// <summary>Also for conditional block statements</summary>\r\n\t\t//public static bool dontExecuteBlockStatements = false;\r\n\r\n\t\tpublic static bool StoreAssetTrace { get; set; } //= false;\r\n\r\n\t\tpublic Dictionary<String, GameEntity> zoneEntities = new Dictionary<String, GameEntity>();\r\n\r\n\t\t// public MonoGameObjectStore monogameObjects = new MonoGameObjectStore();\r\n\r\n\t\t// private Dictionary<Condition, Action[]> runtimeEvents;\r\n\r\n\t\tpublic const int DEFAULT_ZONE_WIDTH = 736, DEFAULT_ZONE_HEIGHT = 736;\r\n\r\n\t\tpublic AssetTrace ZoneAssetTrace { get; private set; } = new AssetTrace();\r\n\r\n\t\tpublic int ZoneWidth { get; set; } = DEFAULT_ZONE_WIDTH;\r\n\r\n\t\tpublic int ZoneHeight { get; set; } = DEFAULT_ZONE_HEIGHT;\r\n\r\n\t\tpublic System.Drawing.Size Size { get { return new System.Drawing.Size(ZoneWidth, ZoneHeight); } }\r\n\r\n\t\tpublic Vector2 XSize { get { return new Vector2(ZoneWidth, ZoneHeight); } }\r\n\t}\r\n}" }, { "alpha_fraction": 0.684222400188446, "alphanum_fraction": 0.6961512565612793, "avg_line_length": 34.418033599853516, "blob_id": "63b74ab2b6d4c99ac329467c88737b8dc517a639", "content_id": "91732d691167a56e87c4d49b231b515d9832c5b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4445, "license_type": "no_license", "max_line_length": 109, "num_lines": 122, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/SaveButton.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing SM = HollowAether.Lib.InputOutput.SaveManager;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic sealed class SaveButton : Button {\r\n\t\tprivate struct SaveFileDetails {\r\n\t\t\tpublic SaveFileDetails(int slotIndex) {\r\n\t\t\t\tsaveIndex = slotIndex; // Store slot index locally\r\n\t\t\t\tfilePath = SM.GetSaveFilePathFromSlotIndex(slotIndex);\r\n\t\t\t\texists = IOMan.FileExists(filePath); // File Exists :)\r\n\r\n\t\t\t\tif (exists) {\r\n\t\t\t\t\tmade = System.IO.File.GetCreationTime(filePath);\r\n\t\t\t\t\twritten = System.IO.File.GetLastWriteTime(filePath);\r\n\t\t\t\t\tVector2 index = SM.GetSave(slotIndex).currentZone;\r\n\t\t\t\t\tzoneName = IOMan.GetFileTitleFromPath(GV.MonoGameImplement.map.GetZoneArgsFromVector(index).path);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmade = DateTime.MinValue;\r\n\t\t\t\t\twritten = DateTime.MinValue;\r\n\t\t\t\t\tzoneName = null; // Nothing\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Draw(Rectangle containerRect, float layer) {\r\n\t\t\t\tSpriteFont font = GV.MonoGameImplement.fonts[\"homescreen\"]; // Get and store sprite font\r\n\t\t\t\tVector2 offset = new Vector2(containerRect.Height * 7 / 40);\r\n\t\t\t\tVector2 textPosition = containerRect.Location.ToVector2() + offset;\r\n\t\t\t\tVector2 containerBottomRight = new Vector2(containerRect.Right, containerRect.Bottom);\r\n\r\n\t\t\t\tString slotString = $\"Slot: {(saveIndex + 1).ToString().PadLeft(3, '0')}\";\r\n\t\t\t\tVector2 slotStringSize = font.MeasureString(slotString); // Size of main\r\n\t\t\t\tDrawString(slotString, font, textPosition, layer); // Draw slot string to screen\r\n\r\n\t\t\t\tString bottomCornerString = (Valid) ? zoneName : \"New Game!\"; // String in bottom right corner\r\n\t\t\t\tVector2 bottomCornerSize = font.MeasureString(bottomCornerString); // Size of said string \r\n\t\t\t\tVector2 bottomCornerPos = containerBottomRight - offset - bottomCornerSize; // Position\r\n\r\n\t\t\t\tDrawString(bottomCornerString, font, bottomCornerPos, layer); // Draw corner string to position\r\n\r\n\t\t\t\tif (Valid) { // Draw some date details\r\n\t\t\t\t\tString madeString = $\"Made: {made}\"; // When save file was made in string format\r\n\t\t\t\t\tVector2 madePosition = containerRect.Center.ToVector2() - (font.MeasureString(madeString) / 2);\r\n\t\t\t\t\tDrawString(madeString, font, madePosition, layer); // Draw the date for when the save was made\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate static void DrawString(String value, SpriteFont font, Vector2 position, float layer) {\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(\r\n\t\t\t\t\tfont, value, position, Color.White,\r\n\t\t\t\t\t0f, Vector2.Zero, 1f,\r\n\t\t\t\t\tSpriteEffects.None, layer\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Delete() {\r\n\t\t\t\texists = false;\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Name of zone</summary>\r\n\t\t\tprivate string zoneName;\r\n\r\n\t\t\t/// <summary>Path to save file</summary>\r\n\t\t\tpublic String filePath;\r\n\r\n\t\t\t/// <summary>Index of save file</summary>\r\n\t\t\tpublic int saveIndex;\r\n\r\n\t\t\t/// <summary>Dates when made and last written</summary>\r\n\t\t\tpublic DateTime made, written;\r\n\r\n\t\t\t/// <summary>File exists</summary>\r\n\t\t\tpublic bool exists;\r\n\r\n\t\t\t/// <summary>Valid save file</summary>\r\n\t\t\tpublic bool Valid { get { return exists; } }\r\n\t\t}\r\n\r\n\t\tpublic SaveButton(Vector2 position, int saveIndex, int width, int height) : base(position, width, height) {\r\n\t\t\tfileDetails = new SaveFileDetails(saveIndex);\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw(); // Draws hold deets\r\n\r\n\t\t\tfileDetails.Draw(SpriteRect, Layer + 0.0005f);\r\n\t\t}\r\n\r\n\t\tpublic void DeleteDetails() {\r\n\t\t\tfileDetails.Delete();\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Default\"] = new AnimationSequence(0, new Frame(0, 0, SPRITE_WIDTH, 16, SPRITE_WIDTH, 16));\r\n\t\t\tAnimation[\"Dark\"] = new AnimationSequence(0, new Frame(0, 1, SPRITE_WIDTH, 16, SPRITE_WIDTH, 16));\r\n\t\t\tAnimation[\"Active\"] = new AnimationSequence(0, new Frame(0, 2, SPRITE_WIDTH, 16, SPRITE_WIDTH, 16));\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"Default\");\r\n\t\t}\r\n\r\n\t\tSaveFileDetails fileDetails;\r\n\r\n\t\tpublic new const int SPRITE_WIDTH = 112;\r\n\r\n\t\tpublic int SaveIndex { get { return fileDetails.saveIndex; } }\r\n\r\n\t\tpublic override String TextureID { get; protected set; } = @\"cs\\button_stretched\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7310553789138794, "alphanum_fraction": 0.7360154390335083, "avg_line_length": 36.20000076293945, "blob_id": "8657cb66a708e406ee5ffff0c0f02b1029fe757b", "content_id": "52718696ddbdf96713d630b44d6dee5f2d991203", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3631, "license_type": "no_license", "max_line_length": 120, "num_lines": 95, "path": "/HollowAether/Lib/Global/GlobalVars/MonoGameImplement.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class MonoGameImplement {\r\n\t\t\tpublic static void InitializeSpriteBatch(bool useCamera = true, SpriteSortMode mode = SpriteSortMode.FrontToBack) {\r\n\t\t\t\tSpriteBatch.Begin(\r\n\t\t\t\t\tsamplerState:\t SamplerState.PointClamp,\r\n\t\t\t\t\tsortMode:\t\t mode,\r\n\t\t\t\t\tblendState:\t\t BlendState.AlphaBlend,\r\n\t\t\t\t\ttransformMatrix: (useCamera) ? camera.GetViewMatrix() : Matrix.Identity\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Player Player { get; set; }\r\n\r\n\t\t\tpublic static bool FullScreen {\r\n\t\t\t\tget { return hollowAether.IsFullScreen; } // Return value stored in game instance\r\n\t\t\t\tset { if (hollowAether.IsFullScreen != value) hollowAether.ToggleFullScreen(); }\r\n\t\t\t}\r\n\r\n\t\t\tpublic static SpriteBatch SpriteBatch { get { return GlobalVars.hollowAether.spriteBatch; } }\r\n\r\n\t\t\tpublic static float MilisecondsPerFrame { get { return 1000 / framesPerSecond; } }\r\n\r\n\t\t\tpublic static Dictionary<String, AnimationSequence> importedAnimations = new Dictionary<String, AnimationSequence>();\r\n\r\n\t\t\tpublic static Dictionary<String, Texture2D> textures = new Dictionary<String, Texture2D>(); // ImportedImages\r\n\t\t\tpublic static Dictionary<String, SpriteFont> fonts = new Dictionary<String, SpriteFont>(); // ImportedFonts\r\n\t\t\tpublic static Dictionary<String, Video> videos = new Dictionary<String, Video>(); // ImportedVideos\r\n\t\t\tpublic static Dictionary<String, SoundEffect> sounds = new Dictionary<String, SoundEffect>(); // ImportedSounds\r\n\r\n\t\t\tpublic static MonoGameObjectStore monogameObjects = new MonoGameObjectStore(); // Main object store\r\n\t\t\tpublic static RemovalBatch removalBatch = new RemovalBatch(); // Batch to remove existing monogame objects\r\n\t\t\tpublic static AdditionBatch additionBatch = new AdditionBatch(); // Batch to add new monogame objects\r\n\r\n\t\t\tpublic static GameState gameState = GameState.Home; // Stores current game state\r\n\r\n\t\t\tpublic static Camera2D camera;\r\n\r\n\t\t\tpublic static float gameZoom = 2.0f;\r\n\r\n\t\t\tpublic const float gravity = 1.5f * 32f; // gravitational field strength affecting all objects by default\r\n\r\n\t\t\tpublic static String defaultAnimationSequenceKey = \"Idle\"; // Sequence run by default on all sprites\r\n\r\n\t\t\tpublic static Type[] BlockTypes = { typeof(Block), /*typeof(AngledBlock),*/ typeof(Crusher), typeof(GravityBlock) };\r\n\r\n\t\t\tpublic static GameTime gameTime;\r\n\r\n\t\t\tpublic static float framesPerSecond = 30; // GT and FPS\r\n\r\n\t\t\tpublic static Background background;\r\n\r\n\t\t\tpublic static Dictionary<String, Background> backgrounds = new Dictionary<String, Background>();\r\n\r\n\t\t\tpublic static Map map { get; set; }\r\n\r\n\t\t\tpublic static HUD GameHUD;\r\n\r\n\t\t\tpublic static int money = 0;\r\n\r\n\t\t\tpublic static int saveIndex = -1; // Default value will throw exception if used as is\r\n\r\n\t\t\tpublic static int ContactDamage { get { return 3; } }\r\n\r\n\t\t\tpublic static String PlayerName { get; private set; } = \"Quote\";\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6940247416496277, "alphanum_fraction": 0.6940247416496277, "avg_line_length": 36.31578826904297, "blob_id": "7c00f39557ae35480b556442b3dc44117adde8cf", "content_id": "fb27953d9cbe88cd76d7a50ce31cf93e73afbdab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2914, "license_type": "no_license", "max_line_length": 146, "num_lines": 76, "path": "/HollowAether/Lib/GAssets/TypeDef/IntersectingPositions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic enum Direction { Top, Bottom, Left, Right }\r\n\r\n\tpublic class IntersectingPositions : Dictionary<Direction, float?> {\r\n\t\tpublic IntersectingPositions() : base() { }\r\n\t\tpublic IntersectingPositions(int capacity) : base(capacity) { }\r\n\t\tpublic IntersectingPositions(IDictionary<Direction, float?> dict) : base(dict) { }\r\n\t\tpublic IntersectingPositions(IEqualityComparer<Direction> comparer) : base(comparer) { }\r\n\t\tpublic IntersectingPositions(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t\tpublic IntersectingPositions(int capacity, IEqualityComparer<Direction> comparer) : base(capacity, comparer) { }\r\n\t\tpublic IntersectingPositions(IDictionary<Direction, float?> dict, IEqualityComparer<Direction> comparer) : base(dict, comparer) { }\r\n\r\n\t\tprivate delegate float SetMethod(float X, float Y);\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\tFunc<KeyValuePair<Direction, float?>, String> KVPToString = (KVP) => {\r\n\t\t\t\tString val = (KVP.Value.HasValue) ? KVP.Value.ToString() : \"Null\";\r\n\t\t\t\treturn $\"({KVP.Key} : {val})\";\r\n\t\t\t};\r\n\r\n\t\t\treturn $\"IP{{{(from X in this select KVPToString(X)).Aggregate((a, b) => $\"{a}, {b}\")}}}\";\r\n\t\t}\r\n\r\n\t\tpublic void Set(Direction key, float? newVal) {\r\n\t\t\tif (!newVal.HasValue) return; // No value to add\r\n\t\t\t\r\n\t\t\tSetMethod Call = (Equals(key, Direction.Top) || Equals(key, Direction.Left)) \r\n\t\t\t\t? new SetMethod(Math.Min) : new SetMethod(Math.Max);\r\n\r\n\t\t\tif (!this[key].HasValue) { this[key] = newVal.Value; } else {\r\n\t\t\t\tthis[key] = Call(this[key].Value, newVal.Value);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Set(IntersectingPositions other) {\r\n\t\t\tforeach (Direction direction in Enum.GetValues(typeof(Direction))) {\r\n\t\t\t\tSet(direction, other[direction]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static IntersectingPositions operator -(IntersectingPositions A, IntersectingPositions B) {\r\n\t\t\tIntersectingPositions N = A.MemberwiseClone() as IntersectingPositions;\r\n\r\n\t\t\tforeach (Direction direction in Enum.GetValues(typeof(Direction))) {\r\n\t\t\t\tif (A[direction].HasValue && B[direction].HasValue)\r\n\t\t\t\t\tN[direction] -= B[direction].Value;\r\n\t\t\t}\r\n\r\n\t\t\treturn N;\r\n\t\t}\r\n\r\n\t\tpublic static IntersectingPositions operator +(IntersectingPositions A, IntersectingPositions B) {\r\n\t\t\tIntersectingPositions N = A.MemberwiseClone() as IntersectingPositions;\r\n\r\n\t\t\tforeach (Direction direction in Enum.GetValues(typeof(Direction))) {\r\n\t\t\t\tif (A[direction].HasValue && B[direction].HasValue)\r\n\t\t\t\t\tN[direction] += B[direction].Value;\r\n\t\t\t}\r\n\r\n\t\t\treturn N;\r\n\t\t}\r\n\r\n\t\tpublic static IntersectingPositions Empty {\r\n\t\t\tget {\r\n\t\t\t\treturn new IntersectingPositions { { Direction.Top, null }, { Direction.Bottom, null }, { Direction.Left, null }, { Direction.Right, null } };\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7110704183578491, "alphanum_fraction": 0.7235016822814941, "avg_line_length": 42.95294189453125, "blob_id": "7c086cb5a4dff2919d23ce56e0e5444ceea8cc10", "content_id": "79a7a127f63423c8196196b0b017cbe5221155a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7644, "license_type": "no_license", "max_line_length": 162, "num_lines": 170, "path": "/HollowAether/Lib/Global/GameWindow/Settings.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tstatic class Settings {\r\n\t\tstatic Settings() {\r\n\t\t\tGV.MonoGameImplement.backgrounds[\"GW_SETTINGS\"] = new Background() {\r\n\t\t\t\tnew StretchedBackgroundLayer(@\"backgrounds\\windows\\settingsbg\", new Frame(0, 0, 1080, 720, 1, 1, 1), 0.5f),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Begin(samplerState: SamplerState.PointClamp);\r\n\r\n\t\t\tbuttons.Draw();\r\n\r\n\t\t\tforeach (Button button in multiChoiceAssistiveButtons) button.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() {\r\n\t\t\tBuildButtons(); // Rebuild displayed full screen menu buttons\r\n\t\t\tGV.MonoGameImplement.background = GV.MonoGameImplement.backgrounds[\"GW_SETTINGS\"];\r\n\t\t}\r\n\r\n\t\tprivate static void BuildButtons() {\r\n\t\t\tint width = GV.Variables.windowWidth, height = GV.Variables.windowHeight; // Store window dimensions for positioning\r\n\t\t\tfloat buttonWidth = (Button.SPRITE_WIDTH * BUTTON_SCALE) + 225, buttonHeight = Button.SPRITE_HEIGHT * BUTTON_SCALE;\r\n\r\n\t\t\t#region Build Buttons\r\n\t\t\tint yOffset = (int)(buttonHeight * 1.25f);\r\n\t\t\t\r\n\t\t\tTextButton toggleFullscreenButton = new TextButton(Vector2.Zero, \"Toggle Fullscreen\", (int)buttonWidth, (int)buttonHeight) {\r\n\t\t\t\tPosition = new Vector2((width - buttonWidth) / 2, 0.25f * buttonHeight) // Center screen with primary offset vertically\r\n\t\t\t};\r\n\r\n\t\t\t#region BuildMultiChoiceButtons\r\n\t\t\tVector2 fpsButtonPosition = toggleFullscreenButton.Position + new Vector2(buttonWidth / 2, yOffset);\r\n\t\t\tvar fpsOptions = (from X in Enumerable.Range(10, 120) where X % 5 == 0 select X.ToString()).ToArray(); // Frames Per Second Options For Button To Select\r\n\t\t\tMultichoiceButton fpsButton = new MultichoiceButton(fpsButtonPosition, width: (int)buttonWidth, height: (int)buttonHeight, options: fpsOptions);\r\n\t\t\tint fpsIndex = Array.IndexOf(fpsOptions, GV.BasicMath.RoundToNearestMultiple(Convert.ToInt32(GV.MonoGameImplement.framesPerSecond), 5, true).ToString());\r\n\t\t\tfpsButton.SetSelectedOption(fpsIndex != -1 ? fpsIndex : 0); // If current frame value not found in options array then just set to 10 for now\r\n\r\n\t\t\tVector2 screenSizeButtonPosition = toggleFullscreenButton.Position + new Vector2(buttonWidth / 2, 2 * yOffset);\r\n\t\t\tstring[] sizeOptions = (from X in Enumerable.Range(10, 21) select $\"{X * 100}x{X * 100 * 960 / 1600}\").ToArray(); // Multiples, while maintaining aspect ratio\r\n\t\t\tMultichoiceButton screenSizeButton = new MultichoiceButton(screenSizeButtonPosition, width: (int)buttonWidth, height: (int)buttonHeight, options: sizeOptions);\r\n\t\t\t//int index = Array.IndexOf(sizeOptions, GV.BasicMath.RoundToNearestMultiple(Convert.ToInt32(GV.MonoGameImplement.framesPerSecond), 5, true).ToString());\r\n\t\t\tint sizeIndex = Array.IndexOf(sizeOptions, $\"{GV.Variables.windowWidth}x{GV.Variables.windowHeight}\");\r\n\t\t\tscreenSizeButton.SetSelectedOption(sizeIndex != -1 ? sizeIndex : 0); // Select option corresponding to current window size\r\n\r\n\t\t\t#region AssistiveSideButtons\r\n\t\t\tmultiChoiceAssistiveButtons = new Button[2];\r\n\r\n\t\t\tmultiChoiceAssistiveButtons[0] = new TextButton(Vector2.Zero, \"FPS\", (int)buttonWidth, (int)buttonHeight) {\r\n\t\t\t\tPosition = fpsButtonPosition - new Vector2(buttonWidth, 0)\r\n\t\t\t};\r\n\r\n\t\t\tmultiChoiceAssistiveButtons[1] = new TextButton(Vector2.Zero, \"Dimensions\", (int)buttonWidth, (int)buttonHeight) {\r\n\t\t\t\tPosition = screenSizeButtonPosition - new Vector2(buttonWidth, 0)\r\n\t\t\t};\r\n\t\t\t#endregion\r\n\r\n\t\t\t#endregion\r\n\r\n\t\t\tTextButton goBackButton = new TextButton(Vector2.Zero, \"Back\", (int)buttonWidth, (int)buttonHeight) {\r\n\t\t\t\tPosition = new Vector2(toggleFullscreenButton.Position.X, screenSizeButtonPosition.Y + yOffset)\r\n\t\t\t};\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region Build Event Handlers\r\n\t\t\ttoggleFullscreenButton.Click += (self) => GV.hollowAether.ToggleFullScreen();\r\n\t\t\tgoBackButton.Click += (self) => ReturnToHomeState();\r\n\r\n\t\t\tfpsButton.Changed += (self) => {\r\n\t\t\t\tGV.MonoGameImplement.framesPerSecond = int.Parse(self.ActiveSelection);\r\n\t\t\t};\r\n\r\n\t\t\tscreenSizeButton.Click += (self) => {\r\n\t\t\t\tstring[] split = screenSizeButton.ActiveSelection.Split('x');\r\n\t\t\t\tint horizontal = int.Parse(split[0]), vertical = int.Parse(split[1]);\r\n\t\t\t\tGV.hollowAether.SetWindowDimensions(new Vector2(horizontal, vertical));\r\n\t\t\t\tBuildButtons();\r\n\t\t\t};\r\n\t\t\t#endregion\r\n\r\n\t\t\tbuttons = new ButtonList(0, 3, new Button[] {toggleFullscreenButton, fpsButton, screenSizeButton, goBackButton});\r\n\t\t}\r\n\r\n\t\tpublic static void Update() {\r\n\t\t\tbuttons.Update(false);\r\n\r\n\t\t\tGV.PeripheralIO.ControlState controlState = GV.PeripheralIO.currentControlState;\r\n\r\n\t\t\tbool altPressed = GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.LeftAlt, Keys.RightAlt); // Whether alt key is pressed\r\n\t\t\tbool enter = GetEnterInput(), goBack = GetReturnInput(); // Determines What To Do/The specific command the input corresponds to\r\n\t\t\tbool moveForward = controlState.Down || controlState.Right, moveBackward = controlState.Up || controlState.Left; // Buttons\r\n\t\t\tbool nothingPressed = !(altPressed || enter || goBack || moveForward || moveBackward); // If no input detected\r\n\r\n\t\t\tif (WaitForInputToBeRemoved) {\r\n\t\t\t\tif (nothingPressed) WaitForInputToBeRemoved = false;\r\n\t\t\t\treturn; // Input has been removed || Is still in affect\r\n\t\t\t}\r\n\r\n\t\t\tif (inputTimeout > 0) {\r\n\t\t\t\tif (nothingPressed) inputTimeout = 0; // Remove input time out, user can input again\r\n\t\t\t\telse inputTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t} else if (!nothingPressed) {\r\n\t\t\t\tif (goBack) ReturnToHomeState(); else if (enter) buttons.ActiveButton.InvokeClick();\r\n\t\t\t\telse if (moveForward || moveBackward) {\r\n\t\t\t\t\tif ((controlState.Left || controlState.Right) && buttons.ActiveButton is MultichoiceButton) {\r\n\t\t\t\t\t\tif (moveForward) (buttons.ActiveButton as MultichoiceButton).SelectNextOption();\r\n\t\t\t\t\t\telse\t\t\t (buttons.ActiveButton as MultichoiceButton).SelectPreviousOption();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tif (moveForward) buttons.MoveToNextButton();\r\n\t\t\t\t\t\telse\t\t buttons.MoveToPreviousButton();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinputTimeout = 150; // Dont accept input for given value in milleseconds\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region GetInputStates\r\n\t\tprivate static bool GetEnterInput() {\r\n\t\t\treturn (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.Buttons.A == ButtonState.Pressed)\r\n\t\t\t\t|| GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Enter);\r\n\t\t}\r\n\r\n\t\tprivate static bool GetReturnInput() {\r\n\t\t\treturn (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.Buttons.B == ButtonState.Pressed)\r\n\t\t\t\t|| GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Back, Keys.B);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate static void ReturnToHomeState() {\r\n\t\t\tGV.MonoGameImplement.gameState = GameState.Home;\r\n\t\t\tHome.Reset(); // Reset home screen window\r\n\t\t}\r\n\r\n\t\tprivate static Vector2 GetCenterAllignedButtonPosition(int width, int height, int windowWidth, int Y) {\r\n\t\t\treturn new Vector2();\r\n\t\t}\r\n\r\n\t\tpublic static void FullScreenReset(bool isFullScreen) { if (GV.MonoGameImplement.gameState == GameState.Settings) Reset(); }\r\n\r\n\t\tprivate static ButtonList buttons;\r\n\r\n\t\tprivate static Button[] multiChoiceAssistiveButtons;\r\n\r\n\t\tpublic static bool WaitForInputToBeRemoved { get; set; }\r\n\r\n\t\tprivate static int inputTimeout = 0;\r\n\r\n\t\tprivate const float BUTTON_SCALE = 3.5f;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6479560732841492, "alphanum_fraction": 0.6705307960510254, "avg_line_length": 30.13725471496582, "blob_id": "6cf0997ba4b695e4488e5435060cd960705abd20", "content_id": "664005b1eed9cca42b1009b8dd39866a06bb6db5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1641, "license_type": "no_license", "max_line_length": 89, "num_lines": 51, "path": "/HollowAether/Lib/Global/GlobalVars/Convert.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class Convert {\r\n\t\t\tpublic static Vector2[] RectangleTo4Vects(Rectangle rect) {\r\n\t\t\t\treturn new Vector2[] {\r\n\t\t\t\t\tnew Vector2(rect.Left, rect.Top), // Top Left\r\n\t\t\t\t\tnew Vector2(rect.Right, rect.Top), // Top Right\r\n\t\t\t\t\tnew Vector2(rect.Left, rect.Bottom), // Bottom Left\r\n\t\t\t\t\tnew Vector2(rect.Right, rect.Bottom), // Bottom Right\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Line[] RectangleTo4Lines(Rectangle rect) {\r\n\t\t\t\tVector2[] rectVects = RectangleTo4Vects(rect);\r\n\r\n\t\t\t\treturn _4VectorsTo4Lines(rectVects[0], rectVects[1], rectVects[2], rectVects[3]);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Line[] RotatedRectangleTo4Lines(IBRotatedRectangle rect) {\r\n\t\t\t\tVector2[] rectVects = (from X in rect.GenerateRotatedPoints() select X).ToArray();\r\n\r\n\t\t\t\treturn _4VectorsTo4Lines(rectVects[0], rectVects[1], rectVects[2], rectVects[3]);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Line[] TriangleTo3Lines(IBTriangle tri) {\r\n\t\t\t\treturn new Line[] {\r\n\t\t\t\t\tnew Line(tri.Ventrices[0], tri.Ventrices[1]),\r\n\t\t\t\t\tnew Line(tri.Ventrices[0], tri.Ventrices[2]),\r\n\t\t\t\t\tnew Line(tri.Ventrices[1], tri.Ventrices[2]),\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Line[] _4VectorsTo4Lines(Vector2 A, Vector2 B, Vector2 C, Vector2 D) {\r\n\t\t\t\treturn new Line[] { new Line(A, B), new Line(A, C), new Line(B, D), new Line(C, D) };\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6840937733650208, "alphanum_fraction": 0.6880016922950745, "avg_line_length": 31.935483932495117, "blob_id": "a601e7df0085b8a6011b5ca694feed0a31c9fdf6", "content_id": "ab7b3638f8d01e9040869575505fb43a4d1bf411", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9470, "license_type": "no_license", "max_line_length": 129, "num_lines": 279, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Forms/Asset View/AssetView.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.MapZone;\r\n\r\nusing Converters = HollowAether.Lib.InputOutput.Parsers.Converters;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class AssetView : Form {\r\n\t\tpublic AssetView(Zone zone) {\r\n\t\t\tInitializeComponent();\r\n\t\t\tsizeBeforeResize = MinimumSize;\r\n\t\t\tOpen = true; this.zone = zone;\r\n\t\t}\r\n\r\n\t\tprivate void AssetView_Load(object sender, EventArgs e) {\r\n\t\t\tviewComboBox.Items.AddRange(new string[] {\r\n\t\t\t\t\"All\", \"Global\", \"Local\"\r\n\t\t\t});\r\n\r\n\t\t\tsaveButton.Click += (s, e2) => {\r\n\t\t\t\tChangesMade = false;\r\n\t\t\t};\r\n\r\n\t\t\t#region Assets View Definition\r\n\t\t\tDataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn() {\r\n\t\t\t\tReadOnly = true, HeaderText = \"Name\", Width = 250\r\n\t\t\t};\r\n\r\n\t\t\tDataGridViewTextBoxColumn set = new DataGridViewTextBoxColumn() {\r\n\t\t\t\tReadOnly = false, HeaderText = \"Set\", Width = 250\r\n\t\t\t};\r\n\r\n\t\t\tDataGridViewTextBoxColumn _default = new DataGridViewTextBoxColumn() {\r\n\t\t\t\tReadOnly = true, HeaderText = \"Default\", Width = 250\r\n\t\t\t};\r\n\r\n\t\t\tDataGridViewTextBoxColumn type = new DataGridViewTextBoxColumn() {\r\n\t\t\t\tReadOnly = true, HeaderText = \"Type\", // Takes up remaining space\r\n\t\t\t\tWidth = assetsView.Width - name.Width - _default.Width - set.Width - 3\r\n\t\t\t};\r\n\r\n\t\t\tassetsView.CellValueChanged += AssetsView_CellValueChanged;\r\n\r\n\t\t\tassetsView.CellBeginEdit += AssetsView_CellBeginEdit;\r\n\r\n\t\t\tassetsView.Columns.AddRange(new DataGridViewColumn[] {\r\n\t\t\t\tname, type, _default, set // All columns\r\n\t\t\t});\r\n\r\n\t\t\tassetsView.ContextMenu = GetContextMenu();\r\n\r\n\t\t\tassetsView.MouseDown += AssetsView_MouseDown;\r\n\r\n\t\t\tassetsView.MouseUp += AssetsView_MouseUp;\r\n\t\t\t#endregion\r\n\r\n\t\t\tControls.Add(assetsView); // Store assets view\r\n\r\n\t\t\tviewComboBox.SelectedIndex = 0;\r\n\t\t}\r\n\r\n\t\tprivate void AssetsView_MouseUp(object sender, MouseEventArgs e) {\r\n\t\t\tif (clickedMouseButton == MouseButtons.Right) {\r\n\t\t\t\tassetsView.ContextMenu.Show(this, e.Location, LeftRightAlignment.Right);\r\n\t\t\t}\r\n\r\n\t\t\tclickedMouseButton = null; // Reset to null\r\n\t\t}\r\n\r\n\t\tprivate void AssetsView_MouseDown(object sender, MouseEventArgs e) {\r\n\t\t\tclickedMouseButton = e.Button;\r\n\t\t}\r\n\r\n\t\tprivate MouseButtons? clickedMouseButton = null;\r\n\r\n\t\tprivate ContextMenu GetContextMenu() {\r\n\t\t\tMenuItem item = new MenuItem(\"Delete\");\r\n\r\n\t\t\titem.Click += DeleteContextMenuItem_Click;\r\n\r\n\t\t\tContextMenu menu = new ContextMenu(new MenuItem[] { item });\r\n\r\n\t\t\treturn menu;\r\n\t\t}\r\n\r\n\t\tprivate void DeleteContextMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tif (assetsView.SelectedCells.Count > 0) {\r\n\t\t\t\tDataGridViewCell selectedCell = assetsView.SelectedCells[0];\r\n\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t$\"Are you sure you want to delete asset \\\"{selectedCell.Value}\\\"\", \r\n\t\t\t\t\t\"Are You Sure?\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result == DialogResult.Yes) {\r\n\t\t\t\t\tif (GV.MapZone.globalAssets.ContainsKey(selectedCell.Value.ToString())) {\r\n\t\t\t\t\t\tMessageBox.Show(\"Cannot Delete a Global Asset\", \"Forbidden\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tTrace.DeleteAsset(selectedCell.Value.ToString());\r\n\t\t\t\t\t\tassetsView.Rows.RemoveAt(selectedCell.RowIndex);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AssetView_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\tif (!ChangesMade) { Open = false; } else {\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\"Would You Like To Save, Before Closing Asset View?\",\r\n\t\t\t\t\t\"Warning\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result == DialogResult.Yes && ChangesMade) saveButton.PerformClick();\r\n\r\n\t\t\t\tif (result == DialogResult.Cancel) e.Cancel = true; else Open = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AssetView_Resize(object sender, EventArgs e) {\r\n\t\t\tSize deltaSize = Size - sizeBeforeResize;\r\n\r\n\t\t\tassetsView.Size += deltaSize; // Change in size\r\n\r\n\t\t\tsizeBeforeResize = Size; // Current size\r\n\t\t}\r\n\r\n\t\tpublic static IEnumerable<Tuple<AssetTrace.AssetTraceArgs, DataGridViewRow>> TraceToDatagridRows(AssetTrace trace) {\r\n\t\t\tforeach (AssetTrace.AssetTraceArgs args in trace.store) {\r\n\t\t\t\tyield return new Tuple<AssetTrace.AssetTraceArgs, DataGridViewRow>(\r\n\t\t\t\t\targs, AssetTraceArgsToDataGridViewRow(args) // Make Tuple\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static DataGridViewRow AssetTraceArgsToDataGridViewRow(AssetTrace.AssetTraceArgs args) {\r\n\t\t\tDataGridViewRow row = new DataGridViewRow();\r\n\r\n\t\t\trow.Cells.AddRange(new DataGridViewCell[] {\r\n\t\t\t\tnew DataGridViewTextBoxCell() { Value = args.ID },\r\n\t\t\t\tnew DataGridViewTextBoxCell() { Value = args.Type },\r\n\t\t\t});\r\n\r\n\t\t\trow.Cells.Add(new DataGridViewTextBoxCell() { Value = (args.HasDefaultValue) ? args.DefaultValue : \"\"});\r\n\t\t\trow.Cells.Add(new DataGridViewTextBoxCell() { Value = (args.ValueAssigned) ? args.Value : \"\"});\r\n\r\n\t\t\tif (!args.HasDefaultValue) {\r\n\t\t\t\trow.Cells[2].Style.BackColor = Color.LightGray;\r\n\t\t\t\trow.Cells[2].Style.ForeColor = Color.DarkGray;\r\n\t\t\t}\r\n\r\n\t\t\treturn row;\r\n\t\t}\r\n\r\n\t\tprivate DataGridViewRow[] GetAllDataGridRows() {\r\n\t\t\treturn (from X in TraceToDatagridRows(Trace) select X.Item2).ToArray();\r\n\t\t}\r\n\r\n\t\tprivate DataGridViewRow[] GetAllGlobalDataGridRows() {\r\n\t\t\treturn (from X in TraceToDatagridRows(Trace) where GV.MapZone.globalAssets.ContainsKey(X.Item1.ID) select X.Item2).ToArray();\r\n\t\t}\r\n\r\n\t\tprivate DataGridViewRow[] GetAllLocalDataGridRows() {\r\n\t\t\treturn (from X in TraceToDatagridRows(Trace) where !GV.MapZone.globalAssets.ContainsKey(X.Item1.ID) select X.Item2).ToArray();\r\n\t\t}\r\n\r\n\t\tprivate void AssetsView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {\r\n\t\t\tstring id = assetsView[0, e.RowIndex].Value.ToString();\r\n\t\t\tstring type = assetsView[1, e.RowIndex].Value.ToString();\r\n\t\t\tstring newValue = assetsView[3, e.RowIndex].Value.ToString();\r\n\r\n\t\t\tif (newValue == valueBefore_AssetsView_CellValueChanged) return; // Cancel assignment\r\n\r\n\t\t\tif (String.IsNullOrWhiteSpace(newValue)) { /* Deleted */\r\n\t\t\t\tTrace.DeleteAssetValue(id); ChangesMade = true;\r\n\t\t\t} else {\r\n\t\t\t\tif (Converters.IsValidConversion(type, newValue)) {\r\n\t\t\t\t\tTrace.SetValue(id, newValue); ChangesMade = true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t$\"Couldn't Convert '{newValue}' To Instance Of Type '{type}'\", // Failed\r\n\t\t\t\t\t\t\"Operation Cancelled\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tassetsView[e.ColumnIndex, e.RowIndex].Value = valueBefore_AssetsView_CellValueChanged;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AssetsView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {\r\n\t\t\tvalueBefore_AssetsView_CellValueChanged = assetsView[e.ColumnIndex, e.RowIndex].Value.ToString();\r\n\t\t}\r\n\r\n\t\tprivate void viewComboBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tassetsView.Rows.Clear(); // Remove all displayed controls\r\n\r\n\t\t\tswitch (viewComboBox.Text) {\r\n\t\t\t\tcase \"All\": assetsView.Rows.AddRange(GetAllDataGridRows()); break;\r\n\t\t\t\tcase \"Global\": assetsView.Rows.AddRange(GetAllGlobalDataGridRows()); break;\r\n\t\t\t\tcase \"Local\": assetsView.Rows.AddRange(GetAllLocalDataGridRows()); break;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void defineNewAssetButton_Click(object sender, EventArgs e) {\r\n\t\t\tNewAssetDialog dialog = new NewAssetDialog();\r\n\t\t\tDialogResult result = dialog.ShowDialog(); \r\n\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tstring id = dialog.AssetID, type=dialog.AssetType, value=dialog.AssetValue;\r\n\r\n\t\t\t\tbool idInvalid = String.IsNullOrWhiteSpace(id);\r\n\t\t\t\tbool valueExists = !String.IsNullOrWhiteSpace(value);\r\n\r\n\t\t\t\tif (!idInvalid) {\r\n\t\t\t\t\tif (!Trace.Exists(id)) {\r\n\t\t\t\t\t\tif (!valueExists) {\r\n\t\t\t\t\t\t\tTrace.AddEmptyAsset(id, type, definition: true); // No value assigned so create as empty\r\n\r\n\t\t\t\t\t\t\tChangesMade = true;\r\n\r\n\t\t\t\t\t\t\tassetsView.Rows.Add(AssetTraceArgsToDataGridViewRow(Trace.store.Last()));\r\n\t\t\t\t\t\t} else if (Converters.IsValidConversion(type, value)) {\r\n\t\t\t\t\t\t\tTrace.AddDefineAsset(id, type, value); // Value assigned at creation\r\n\r\n\t\t\t\t\t\t\tChangesMade = true;\r\n\r\n\t\t\t\t\t\t\tassetsView.Rows.Add(AssetTraceArgsToDataGridViewRow(Trace.store.Last()));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\t\t$\"Couldn't Convert '{value}' To Instance Of Type '{type}'\",\r\n\t\t\t\t\t\t\t\t\"Operation Cancelled\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else { // Trace Exists\r\n\t\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\t\"Asset With Given ID Already Exists, Operation Cancelled\",\r\n\t\t\t\t\t\t\t\"Operation Cancelled\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else { // Is Invalid\r\n\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\"Invalid Id Passed To Asset View, Operation Cancelled\",\r\n\t\t\t\t\t\t\"Operation Cancelled\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tDataGridView assetsView = new DataGridView() {\r\n\t\t\tLocation = new Point(13, 35),\r\n\t\t\tSize = new Size(1073, 304),\r\n\t\t\tColumnHeadersHeight = 30,\r\n\t\t\tRowHeadersVisible = false,\r\n\t\t\tAllowUserToAddRows = false\r\n\t\t};\r\n\r\n\t\tprivate Size sizeBeforeResize;\r\n\r\n\t\tpublic static bool Open = false;\r\n\r\n\t\tprivate Zone zone;\r\n\r\n\t\tpublic bool ChangesMade { get; private set; } = false;\r\n\r\n\t\tprivate string valueBefore_AssetsView_CellValueChanged;\r\n\r\n\t\tpublic AssetTrace Trace { get { return zone.ZoneAssetTrace; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6942196488380432, "alphanum_fraction": 0.7052023410797119, "avg_line_length": 43.11304473876953, "blob_id": "2cb1e839f9437835cb73594b84c03669523575c6", "content_id": "b8de205f137a0af4b2c9d9391aefe52bd526ba9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5192, "license_type": "no_license", "max_line_length": 115, "num_lines": 115, "path": "/HollowAether/Lib/GAssets/Camera/Camera.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System.Linq;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary> Camera class allowing game to instantiate and use a camera instance\r\n\t/// to view game instances. Customised Derivative Camera Class Inspired by source on\r\n\t/// : http://www.dylanwilson.net/implementing-a-2d-camera-in-monogame : </summary>\r\n\t/// <Note> Note any sprite batches begun with a Camera2D Matrix must have a default\r\n\t/// scale value of 0.1 or greater, anything lower will not be visible at all </Note>\r\n\tpublic class Camera2D {\r\n\t\t/// <summary> Base constructor to create a 2Dimensional camera </summary>\r\n\t\t/// <param name=\"zoom\">Signifies maximum sprite scale zoom, value must be float above 0.1</param>\r\n\t\t/// <param name=\"type\">Type of camera algorithm to follow by default :)</param>\r\n\t\t/// <param name=\"percentageRotation\">Value representing the degrees of rotation to set the camera to</param>\r\n\t\tpublic Camera2D(float zoom=1.0f, float percentageRotation=0.0f) {\r\n\t\t\tRotation = percentageRotation;\r\n\t\t\tScale = zoom;\r\n\t\t\tsmartCameraRect = new Rectangle(0, 0, target.SpriteRect.Width * 2, target.SpriteRect.Height * 3);\r\n\t\t}\r\n\r\n\t\t/// <summary> Function to create and return a ViewMatrix Instance </summary>\r\n\t\t/// <returns> Single Matrix value, showing dimensions of camera </returns>\r\n\t\tpublic Matrix GetViewMatrix() {\r\n\t\t\tMatrix[] container = new Matrix[5]; int counter = 0; Vector2 origin = GetScaledOrigin();\r\n\r\n\t\t\t// Constructs a Matrix Container and incrementor, to construct a ViewMatrix\r\n\t\t\tforeach (Vector2 X in new Vector2[] { -_position, -origin, origin })\r\n\t\t\t\t// Loops for three different potential vectors required to influence ViewMatrix\r\n\t\t\t\tcontainer[counter++] = Matrix.CreateTranslation(new Vector3(X, 0f));\r\n\t\t\t// Translates and stores new vectors to Matrix Container for aggregation\r\n\r\n\t\t\tcontainer[counter++] = Matrix.CreateRotationZ(Rotation); // adds rotation\r\n\t\t\tcontainer[counter++] = Matrix.CreateScale(Scale, Scale, 1.0f);\r\n\t\t\t// and scale Matrices to simplify implementation of ViewMatrix through aggregation\r\n\r\n\t\t\treturn container.Aggregate((Matrix a, Matrix b) => { return a * b; });\r\n\t\t\t// Agrregates and then returns ViewMatrix using local Lambda Function\r\n\t\t}\r\n\t\r\n\t\tpublic void Update() {\r\n\t\t\tVector2 screenSize = new Vector2(GV.Variables.windowWidth, GV.Variables.windowHeight) / Scale;\r\n\t\t\tVector2 center = target.SpriteRect.Center.ToVector2() - screenSize / 2; // Screen Centered\r\n\r\n\t\t\t_position = ClampPositionToZoneBoundaries(new Vector2(center.X, center.Y - GV.Variables.windowHeight * 0.10f));\r\n\t\t}\r\n\r\n\t\tprivate Vector2 ClampPositionToZoneBoundaries(Vector2 pos) {\r\n\t\t\tFunc<float, float, float, float> calculator = (position, scaledScreenMagnitude, zoneMagnitude) => {\r\n\t\t\t\tbool exceededRegion = position + scaledScreenMagnitude > zoneMagnitude;\r\n\r\n\t\t\t\tif (exceededRegion) return zoneMagnitude - scaledScreenMagnitude;\r\n\t\t\t\telse if (position > 0) return position; // When valid positive value\r\n\t\t\t\telse return 0; // When a -ve value -> isn't allowed\r\n\t\t\t};\r\n\r\n\t\t\tVector2 scaledScreenSize = GV.Variables.windowSize / new Vector2(Scale); // Scaled down\r\n\t\t\tVector2 zoneSize = GV.MonoGameImplement.map.CurrentZone.XSize; // XNA Size as V2\r\n\r\n\t\t\tbool xValid = zoneSize.X > scaledScreenSize.X, yValid = zoneSize.Y > scaledScreenSize.Y;\r\n\r\n\t\t\treturn (!xValid && !yValid) ? -(scaledScreenSize - zoneSize) / 2 : new Vector2() {\r\n\t\t\t\tX = (xValid) ? calculator(pos.X, scaledScreenSize.X, zoneSize.X) : pos.X,\r\n\t\t\t\tY = (yValid) ? calculator(pos.Y, scaledScreenSize.Y, zoneSize.Y) : pos.Y\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic bool ContainedInCamera(Rectangle rect) {\r\n\t\t\tPoint cameraSize = new Point((int)(GV.Variables.windowWidth / Scale), (int)(GV.Variables.windowHeight / Scale));\r\n\t\t\tRectangle cameraRect = new Rectangle(Position.ToPoint(), cameraSize); // Convert camera to viewport rectangle \r\n\r\n\t\t\treturn cameraRect.Intersects(rect); // Use existing rectangle intersection detection method to determine\r\n\t\t}\r\n\r\n\t\tpublic void Offset(Vector2 argVect) { _position += new Vector2(argVect.X, argVect.Y); }\r\n\r\n\t\tpublic void Offset(int X = 0, int Y = 0) { Offset(new Vector2(X, Y)); }\r\n\r\n\t\tpublic Vector2 GetCenterOfScreen() {\r\n\t\t\treturn new Vector2(\r\n\t\t\t\t(_position.X + GV.hollowAether.GraphicsDevice.Viewport.Width) / 2,\r\n\t\t\t\t(_position.Y + GV.hollowAether.GraphicsDevice.Viewport.Height) / 2\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetScaledOrigin() { return GetCenterOfScreen() / Scale; }\r\n\r\n\t\tfloat _scale, _rotation;\r\n\r\n\t\tVector2 _position;\r\n\r\n\t\tRectangle smartCameraRect;\r\n\t\t\r\n\t\tpublic float Scale { get { return _scale; } set { _scale = value; } }\r\n\r\n\t\tpublic float Rotation { get { return _rotation; } set { _rotation = value; } }\r\n\r\n\t\tpublic Vector2 Position { get { return _position; } private set { _position = value; } }\r\n\r\n\t\tIMonoGameObject target { get { return GV.MonoGameImplement.Player; } }\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.6907049417495728, "alphanum_fraction": 0.6922221183776855, "avg_line_length": 36.02692413330078, "blob_id": "c7f02b47932e063747befebe099f0dd6134224d8", "content_id": "ff546fa0ff70d9a48f941b1464669677f7061830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9889, "license_type": "no_license", "max_line_length": 171, "num_lines": 260, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Forms/EditEntityView.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Windows.Forms;\r\nusing HollowAether.Lib.MapZone;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing EntityGenerator = HollowAether.Lib.GlobalVars.EntityGenerators;\r\nusing Converters = HollowAether.Lib.InputOutput.Parsers.Converters;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\t/// <summary>Form to allow modification of existing tiles</summary>\r\n\tpartial class EditEntityView : Form {\r\n\t\tpublic struct EditEntityViewResultsContainer {\r\n\t\t\tpublic ReturnState state;\r\n\t\t\tpublic string id;\r\n\t\t\tpublic GameEntity updatedEntity;\r\n\t\t}\r\n\r\n\t\tpublic enum ReturnState { Changed, Delete, Cancel }\r\n\r\n\t\tEditEntityView(GameEntity entity, Zone zone) {\r\n\t\t\tInitializeComponent(); // Initialize Form Components\r\n\r\n\t\t\tentityTypeTextBox.Text = entity.EntityType;\r\n\r\n\t\t\tthis.entity\t\t = entity.Clone() as GameEntity;\r\n\t\t\tthis.backupEntity = entity.Clone() as GameEntity;\r\n\t\t\tthis.zone\t\t = zone;\r\n\r\n\t\t\tBuildEntityAttributeView(); // Builds table to hold entity attributes for entity\r\n\t\t\tSetEntityAttributeViewItems(entity); // Assign Attributes For Current Entity Item, etc.\r\n\r\n\t\t\tSize = sizeBeforeResize = MinimumSize; // Store the default size of the form\r\n\r\n\t\t\tdataViewTable.Focus(); // Set focus to entity attributes view / 1st attribute value\r\n\r\n\t\t\tdataViewTable.CellBeginEdit += DataViewTableValueColumnChanged_CellBeginEdit;\r\n\t\t\tdataViewTable.CellEndEdit += DataViewTableValueColumnChanged_CellEndEdit;\r\n\r\n\t\t\tActiveControl = dataViewTable; // Set initial focus to data view table\r\n\t\t}\r\n\r\n\t\tprivate void DataViewTableValueColumnChanged_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {\r\n\t\t\tvalueBefore_DataViewTableValueColumnChanged = dataViewTable[e.ColumnIndex, e.RowIndex].Value.ToString();\r\n\t\t}\r\n\r\n\t\tprivate void DataViewTableValueColumnChanged_CellEndEdit(object sender, DataGridViewCellEventArgs e) {\r\n\t\t\tDataGridViewCell cell = dataViewTable[e.ColumnIndex, e.RowIndex]; // Store New Cell\r\n\r\n\t\t\tstring attributeKey = dataViewTable[0, e.RowIndex].Value.ToString();\r\n\r\n\t\t\tEntityAttribute attrib = entity[attributeKey]; // Store Entity Attribute reference\r\n\t\t\t\r\n\t\t\tif (cell.Value == null) { attrib.Delete(); /* User has erased entity attribute value */ } else {\r\n\t\t\t\tstring value = cell.Value.ToString().Trim(); // Remove forward and backward whitespace\r\n\r\n\t\t\t\tif (String.IsNullOrWhiteSpace(value)) attrib.Delete(); else {\r\n\t\t\t\t\tif (value.First() == '[' && value.Last() == ']') {\r\n\t\t\t\t\t\t#region IsAsset_Implement\r\n\t\t\t\t\t\tstring Id = value.Substring(1, value.Length - 2);\r\n\r\n\t\t\t\t\t\tbool existsGlobally = GV.MapZone.globalAssets.ContainsKey(Id);\r\n\t\t\t\t\t\tbool existsLocally = zone.assets.ContainsKey(Id); // Within zone\r\n\r\n\t\t\t\t\t\tif (existsGlobally || existsLocally) {\r\n\t\t\t\t\t\t\tAsset asset = (existsGlobally) ? GV.MapZone.globalAssets[Id] : zone.assets[Id];\r\n\r\n\t\t\t\t\t\t\tif (asset.TypesMatch(attrib.Type)) attrib.Value = asset;\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\t\t\t$\"Cannot Assign Asset Of Type '{asset.assetType}' to Attribute Of Type '{attrib.Type}'\",\r\n\t\t\t\t\t\t\t\t\t\"error\", MessageBoxButtons.OK, MessageBoxIcon.Error // Alert that change cannot be done\r\n\t\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t\t\tcell.Value = valueBefore_DataViewTableValueColumnChanged; // Reset to before val\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tMessageBox.Show($\"Couldn't Find Asset With Name '{Id}'\", \"error\", MessageBoxButtons.OK);\r\n\r\n\t\t\t\t\t\t\tcell.Value = valueBefore_DataViewTableValueColumnChanged; // Reset to before val\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t#endregion\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\ttry { attrib.Value = Converters.StringToAssetValue(attrib.Type, value); } catch {\r\n\t\t\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\t\t$\"Couldn't Convert '{value}' To Object Of Type '{attrib.Type}'\",\r\n\t\t\t\t\t\t\t\t\"error\", MessageBoxButtons.OK // Display that new value could not be done\r\n\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t\tcell.Value = valueBefore_DataViewTableValueColumnChanged; // Reset to before val\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (value.First() == '[' && value.Last() == ']') {\r\n\t\t\t\t\t\t\t#region IsAsset_Implement\r\n\t\t\t\t\t\t\tstring Id = value.Substring(1, value.Length - 1);\r\n\r\n\t\t\t\t\t\t\tbool existsGlobally = GV.MapZone.globalAssets.ContainsKey(Id);\r\n\t\t\t\t\t\t\tbool existsLocally = zone.assets.ContainsKey(Id); // Within zone\r\n\r\n\t\t\t\t\t\t\tif (existsGlobally || existsLocally) {\r\n\t\t\t\t\t\t\t\tattrib.Value = (existsGlobally) ? GV.MapZone.globalAssets[Id] : zone.assets[Id];\r\n\t\t\t\t\t\t\t} else {\r\n\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t#endregion\r\n\t\t\t\t\t\t} else attrib.Value = Converters.StringToAssetValue(attrib.Type, value);\r\n\t\t\t\t\t} catch {\r\n\t\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t\t$\"Couldn't Convert '{value}' To Object Of Type '{attrib.Type}'\",\r\n\t\t\t\t\t\t\t\"error\", MessageBoxButtons.OK // Display that new value could not be done\r\n\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\tcell.Value = valueBefore_DataViewTableValueColumnChanged; // Reset to before val\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region PublicDialogMethods\r\n\t\tpublic static EditEntityViewResultsContainer RunForTemplateEntity(GameEntity tile, Zone zone) {\r\n\t\t\tEditEntityView view = new EditEntityView(tile, zone);\r\n\t\t\tview.tileIDTextBox.ReadOnly = true; // Leave Blank\r\n\r\n\t\t\tview.ShowDialog(); // Display form instance as dialog\r\n\r\n\t\t\treturn new EditEntityViewResultsContainer() {\r\n\t\t\t\tstate\t\t = view.dialogReturnState,\r\n\t\t\t\tupdatedEntity = view.entity,\r\n\t\t\t\tid\t\t\t = String.Empty\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static EditEntityViewResultsContainer RunForExistingEntity(string id, GameEntity tile, Zone zone) {\r\n\t\t\tEditEntityView view = new EditEntityView(tile, zone);\r\n\t\t\tview.tileIDTextBox.Text = id; // Set id text\r\n\r\n\t\t\tview.ShowDialog(); // Display form instance as dialog\r\n\r\n\t\t\treturn new EditEntityViewResultsContainer() {\r\n\t\t\t\tstate\t\t = view.dialogReturnState,\r\n\t\t\t\tupdatedEntity = view.entity,\r\n\t\t\t\tid\t\t\t = view.tileIDTextBox.Text.Trim()\r\n\t\t\t};\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate void EditExistingEntityView_Load(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\tprivate void EditExistingEntityView_Shown(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\t#region ButtonClickEventHandlers\r\n\t\tprivate void resetButton_Click(object sender, EventArgs e) {\r\n\t\t\tentity = backupEntity.Clone() as GameEntity;\r\n\t\t\tSetEntityAttributeViewItems(backupEntity);\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\tdialogReturnState = ReturnState.Changed; // State\r\n\t\t\tthis.Close(); // Close form after values changed\r\n\t\t}\r\n\r\n\t\t/// <summary>Handler for close button press</summary>\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) {\r\n\t\t\tdialogReturnState = ReturnState.Cancel; // State\r\n\t\t\tthis.Close(); // Close form after values changed\r\n\t\t}\r\n\r\n\t\t/// <summary>Clears contents of data grid views value</summary>\r\n\t\tprivate void clearAllButton_Click(object sender, EventArgs e) {\r\n\t\t\tforeach (String key in entity.GetEntityAttributes()) {\r\n\t\t\t\tentity[key].Delete(); // Delete value assigned to attr\r\n\t\t\t}\r\n\r\n\t\t\tSetEntityAttributeViewItems(entity); // From current\r\n\t\t}\r\n\r\n\t\tprivate void deleteTileButton_Click(object sender, EventArgs e) {\r\n\t\t\tdialogReturnState = ReturnState.Delete; // State\r\n\t\t\tthis.Close(); // Close form after values changed\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Builds data grid view and adds columns</summary>\r\n\t\tprivate void BuildEntityAttributeView() {\r\n\t\t\tdataViewTable = new DataGridView() {\r\n\t\t\t\tMultiSelect\t\t\t\t = false, \r\n\t\t\t\tColumnHeadersHeight\t\t = 45,\r\n\t\t\t\tRowHeadersVisible\t\t = false,\r\n\t\t\t\tAllowUserToAddRows\t\t = false,\r\n\t\t\t\tBackgroundColor\t\t\t = Color.White,\r\n\t\t\t\tBorderStyle\t\t\t\t = BorderStyle.None,\r\n\t\t\t\tAllowUserToResizeColumns = false,\r\n\t\t\t\tMinimumSize\t\t\t\t = attributesPanel.Size,\r\n\t\t\t\tRowHeadersBorderStyle\t = DataGridViewHeaderBorderStyle.Sunken\r\n\t\t\t};\r\n\r\n\t\t\t#region ColumnDefintions\r\n\t\t\tvar nameColumn = new DataGridViewColumn() { HeaderText = \"Name\", Name = \"Attribute Name\", Width = (int)(attributesPanel.Width / 2.5) };\r\n\t\t\tvar typeColumn = new DataGridViewColumn() { HeaderText = \"Type\", Name = \"Attribute Type\", Width = (int)(attributesPanel.Width / 4.5) };\r\n\t\t\tvar valueColumn = new DataGridViewColumn() { HeaderText = \"Value\", Name = \"Value\", Width = attributesPanel.Width - (nameColumn.Width + typeColumn.Width + 3) };\r\n\r\n\t\t\tforeach (DataGridViewColumn column in new DataGridViewColumn[] { nameColumn, typeColumn, valueColumn }) {\r\n\t\t\t\tcolumn.CellTemplate = new DataGridViewTextBoxCell();\r\n\t\t\t\tcolumn.Resizable = DataGridViewTriState.True;\r\n\t\t\t\tcolumn.Visible = true;\r\n\t\t\t\tdataViewTable.Columns.Add(column);\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\tattributesPanel.Controls.Add(dataViewTable);\r\n\t\t} // Complete\r\n\r\n\t\t/// <summary>Reads data from tile entity and translates it to data grid</summary>\r\n\t\tprivate void SetEntityAttributeViewItems(GameEntity entity) {\r\n\t\t\tdataViewTable.Rows.Clear(); // int rowCounter = 0\r\n\r\n\t\t\tforeach (string key in entity.GetEntityAttributes()) {\r\n\t\t\t\tEntityAttribute attribute = entity[key]; // Get Entity Attribute\r\n\r\n\t\t\t\tType type = attribute.Type; // Get Type Of Current Entity Attribute\r\n\r\n\t\t\t\tString attrType = type.ToString().Split('.').Last(); // Convert Attribute Type To Displayable String Value\r\n\t\t\t\tString value = (attribute.IsAssigned) ? attribute.ToFileContents() : \"\";\r\n\t\t\t\t\r\n\t\t\t\tdataViewTable.Rows.Add(key, attrType, value); // Add new row to table indicating entity value\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void EditEntityView_Resize(object sender, EventArgs e) {\r\n\t\t\tSize deltaSize = Size - sizeBeforeResize; // Change in size\r\n\t\t\tsizeBeforeResize = Size; // Store new size, before resizing\r\n\r\n\t\t\tattributesPanel.Width\t\t += deltaSize.Width;\r\n\t\t\tdataViewTable.Size\t\t\t += deltaSize;\r\n\t\t\tdataViewTable.Columns[2].Width += deltaSize.Width;\r\n\t\t} \r\n\r\n\t\tprivate void EditEntityView_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\tstring valueBefore_DataViewTableValueColumnChanged = String.Empty;\r\n\r\n\t\tprivate ReturnState dialogReturnState = ReturnState.Cancel;\r\n\r\n\t\tprivate GameEntity entity, backupEntity;\r\n\r\n\t\tpublic DataGridView dataViewTable;\r\n\r\n\t\tprivate Size sizeBeforeResize;\r\n\r\n\t\tprivate Zone zone;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.49441057443618774, "alphanum_fraction": 0.5, "avg_line_length": 39.87234115600586, "blob_id": "4767ee27114b6370e4dd0e6415e8a4faa63f0570", "content_id": "e3b076ebd9303974e67e623e98a94e0aa28dfc4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1970, "license_type": "no_license", "max_line_length": 119, "num_lines": 47, "path": "/HollowAether/Lib/Misc/CommandLineHelp.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing CS = HollowAether.Text.ColoredString;\r\n\r\nnamespace HollowAether.Lib.Misc {\r\n\t/// <summary>Class to hold ugly undesireable code. Basically HollowAethers dirty laundry</summary>\r\n\tpublic static class CommandLineHelp {\r\n\t\t/// <remarks>Efficiency is down the drain here</remarks>\r\n\t\tpublic static IEnumerable<Object> GenerateHelpString() {\r\n\t\t\tList<Object> help = new List<Object>() {\r\n\t\t\t\t#region Usage\r\n\t\t\t\t\"Usage:\", CS.Red(\" HollowAether \"),\r\n\r\n\t\t\t\t\"(\", CS.Red(\"-r\"), \" ^| \", CS.Red(\"-lE\"), \" ^| \", CS.Red(\"-dR\"), \" ^| \", CS.Red(\"-rZ\"), \" ^| \", CS.Red(\"-h\"), \") \",\r\n\r\n\t\t\t\t\"[-\", CS.Green(\"eF\"), \" \", CS.Yellow(\"file\"), \" [\", CS.Yellow(\"tar_file\"), \"]] \",\r\n\t\t\t\t\"[-\", CS.Green(\"dF\"), \" \", CS.Yellow(\"file\"), \" [\", CS.Yellow(\"tar_file\"), \"]] \",\r\n\t\t\t\t\"[-\", CS.Green(\"eD\"), \" \", CS.Yellow(\"dir\"), \" [\", CS.Yellow(\"tar_dir\"), \"]] \",\r\n\t\t\t\t\"[-\", CS.Green(\"dD\"), \" \", CS.Yellow(\"dir\"), \" [\", CS.Yellow(\"tar_dir\"), \"]] \",\r\n\t\t\t\t\"[-\", CS.Green(\"eP\"), \" \", CS.Yellow(\"file\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"dP\"), \" \", CS.Yellow(\"file\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"sZ\"), \" (\", CS.Red(\"X\"), \":\", CS.Yellow(\"x_val\"), \" \", CS.Red(\"Y\"), \":\", CS.Yellow(\"y_val\"), \")] \",\r\n\t\t\t\t\"[-\", CS.Green(\"m\"), CS.Yellow(\" map_file\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"sA\"), CS.Yellow(\" anim_dir\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"z\"), CS.Yellow(\" float\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"60fps\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"30fps\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"20fps\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"15fps\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"f\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"w\"), \"] \",\r\n\t\t\t\t\"[-\", CS.Green(\"tE\"), \"] \\n\\n\",\r\n\t\t\t\t#endregion\r\n\t\t\t};// File encoding should be Unicode\r\n\t\t\t\r\n\t\t\t#region Blurb\r\n\t\t\thelp.AddRange(new List<Object> { CS.Red(\"HollowAether: \"), \"Program Version 0.13 (\", CS.Blue(\"C\"), \") Mohsin L. C. Kale\" });\r\n\t\t\t#endregion\r\n\r\n\t\t\tforeach (Object obj in help)\r\n\t\t\t\tyield return obj;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6835685968399048, "alphanum_fraction": 0.6871317028999329, "avg_line_length": 39.6971435546875, "blob_id": "1dd8c771f05e91639534ee186b1c600b5975feb0", "content_id": "503b616098c29f61c0de5e609aee8f2906d6212b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7299, "license_type": "no_license", "max_line_length": 123, "num_lines": 175, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Classes/TileBox.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic class TileBox : PictureBox {\r\n\t\tpublic TileBox() : base() {\r\n\t\t\tPaint += PaintTile;\r\n\t\r\n\t\t\tTextureOrRegionChanged = (t, r) => { texture = t; textureRegion = r; };\r\n\t\t\tTextureOrRegionChanged += (t, r) => { CropTexture(); \t\t };\r\n\t\t\tTextureOrRegionChanged += (t, r) => { BuildCroppedPictureBoxRegion(); };\r\n\t\t\tTextureOrRegionChanged += (t, r) => { Draw();\t\t\t\t\t\t };\r\n\r\n\t\t\tSizeChanged += (s, e) => { TextureOrRegionChanged(texture, textureRegion); };\r\n\t\t}\r\n\r\n\t\t~TileBox() { fillBrush.Dispose(); }\r\n\r\n\t\tpublic TileBox(Frame initFrame) : this() { AssignFrame(initFrame); }\r\n\r\n\t\tpublic TileBox(Rectangle initFrame) : this() { AssignRect(initFrame); }\r\n\r\n\t\tpublic void PaintTile(object sender, PaintEventArgs args) {\r\n\t\t\tif (DrawTile) {\r\n\t\t\t\targs.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;\r\n\r\n\t\t\t\tif (croppedTexture != null) {\r\n\t\t\t\t\tif (DisplayBorderRectsForScaledImage && BorderRects != null) {\r\n\t\t\t\t\t\targs.Graphics.FillRectangle(fillBrush, BorderRects.Item1);\r\n\t\t\t\t\t\targs.Graphics.FillRectangle(fillBrush, BorderRects.Item2);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\targs.Graphics.DrawImage(croppedTexture, CPBR_X, CPBR_Y, CPBR_Width, CPBR_Height);\r\n\t\t\t\t} else if (haveErrorIndicator) args.Graphics.DrawImage(ErrorImage, new Rectangle(0, 0, 25, 25));\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic void Draw() { Refresh(); /*Invalidates & Updates*/ }\r\n\r\n\t\tpublic void AssignFrame(Frame frame) { AssignRect(frame.ToRect()); }\r\n\r\n\t\tpublic void AssignRect(Microsoft.Xna.Framework.Rectangle rect) {\r\n\t\t\tAssignRect(new Rectangle(rect.X, rect.Y, rect.Width, rect.Height));\r\n\t\t}\r\n\r\n\t\tpublic void AssignRect(Rectangle rect) { if (textureRegion != rect) TextureOrRegionChanged(texture, rect); }\r\n\r\n\t\tpublic void AssignTexture(Image image) { if (image != this.texture) TextureOrRegionChanged(image, textureRegion); }\r\n\r\n\t\tpublic void AssignTextureAndRect(Image img, Rectangle rect) {\r\n\t\t\tif (img != this.texture || rect != TextureRegion) {\r\n\t\t\t\tTextureOrRegionChanged(img, rect);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void CropTexture() {\r\n\t\t\tif (texture == null) CropFailureEventHandler(null); else {\r\n\t\t\t\ttry { croppedTexture = GV.ImageManipulation.CropImage(texture, TextureRegion); } catch (Exception e) {\r\n\t\t\t\t\tRectangle cropRect = TextureRegion; // Store clone of actual tile crop rectangle for reference\r\n\t\t\t\t\tint width = Texture.Width, height = Texture.Height; // Store Texture Width/Height dimensions\r\n\t\t\t\t\tbool notRangeError = cropRect.Location.X <= width && cropRect.Location.Y <= height; // In Img\r\n\r\n\t\t\t\t\tif (notRangeError) CropFailureEventHandler(e); else {\r\n\t\t\t\t\t\tbool horizontallyOutOfRange = cropRect.Right > width;\r\n\t\t\t\t\t\tbool verticallyOutOfRange = cropRect.Bottom > height;\r\n\r\n\t\t\t\t\t\tif (!horizontallyOutOfRange && !verticallyOutOfRange) CropFailureEventHandler(e); else {\r\n\t\t\t\t\t\t\tSize boundedSize = new Size(width, height); // New size for bounding region\r\n\r\n\t\t\t\t\t\t\tif (horizontallyOutOfRange) boundedSize.Width -= cropRect.Location.X;\r\n\t\t\t\t\t\t\tif (verticallyOutOfRange) boundedSize.Height -= cropRect.Location.Y;\r\n\r\n\t\t\t\t\t\t\tcropRect = new Rectangle(cropRect.Location, boundedSize); // New Texture Region\r\n\r\n\t\t\t\t\t\t\ttry { croppedTexture = GV.ImageManipulation.CropImage(Texture, cropRect); } \r\n\t\t\t\t\t\t\tcatch { CropFailureEventHandler(e); /* Unknown error, Image Not Cropped, */ }\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void CropFailureEventHandler(Exception e) { croppedTexture = null; }\r\n\t\t\r\n\r\n\t\tprivate void BuildCroppedPictureBoxRegion() {\r\n\t\t\tif (croppedTexture == null || croppedTexture.Width == 0 || croppedTexture.Height == 0) {\r\n\t\t\t\tBorderRects = null; CPBR_X = 0; CPBR_Y = 0; CPBR_Width = 0; CPBR_Height = 0;\r\n\t\t\t} else {\r\n\t\t\t\tfloat horizontalScale = Width / (float)CroppedTexture.Width, width;\r\n\t\t\t\tfloat verticalScale = Height / (float)CroppedTexture.Height, height;\r\n\r\n\t\t\t\tif (horizontalScale == verticalScale) { width = Width; height = Height; /* Perfect Square */ } else {\r\n\t\t\t\t\tif\t\t (horizontalScale > verticalScale) { height = Height; width = CroppedTexture.Width * verticalScale; } \r\n\t\t\t\t\telse /*if (horizontalScale < verticalScale)*/ { width = Width; height = CroppedTexture.Height * horizontalScale; }\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCPBR_X = (Width - width) / 2; CPBR_Y = (Height - height) / 2; CPBR_Width = width; CPBR_Height = height;\r\n\r\n\t\t\t\t#region BorderRectCreation\r\n\t\t\t\tRectangleF leftBorder, rightBorder; // Left and right border rectangles\r\n\r\n\t\t\t\tif (horizontalScale == verticalScale) leftBorder = rightBorder = Rectangle.Empty; else {\r\n\t\t\t\t\tSizeF size = (horizontalScale > verticalScale) ? new SizeF(CPBR_X, Height) : new SizeF(Width, CPBR_Y);\r\n\t\t\t\t\tPointF pointB = (horizontalScale > verticalScale) ? new PointF(CPBR_X + width, 0) : new PointF(0, CPBR_Y + height);\r\n\r\n\t\t\t\t\tleftBorder = new RectangleF(PointF.Empty, size); rightBorder = new RectangleF(pointB, size); // Set border rectangles\r\n\t\t\t\t}\r\n\r\n\t\t\t\tBorderRects = new Tuple<RectangleF, RectangleF>(leftBorder, rightBorder);\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate event Action<Image, Rectangle> TextureOrRegionChanged;\r\n\r\n\t\tpublic Image Texture { get { return texture; } set { AssignTexture(value); } }\r\n\r\n\t\tpublic Image CroppedTexture { get { return croppedTexture; } }\r\n\r\n\t\tpublic Rectangle TextureRegion { get { return textureRegion; } set { AssignRect(value); } }\r\n\r\n\t\tprivate RectangleF CroppedTextureRegion { get {\r\n\t\t\t\treturn new RectangleF(CPBR_X, CPBR_Y, CPBR_Width, CPBR_Height);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool DisplayBorderRectsForScaledImage { get; set; } = true;\r\n\r\n\t\tpublic int FrameX { get { return textureRegion.X; } set {\r\n\t\t\tAssignRect(new Rectangle(value, textureRegion.Y, textureRegion.Width, textureRegion.Height));\r\n\t\t} }\r\n\r\n\t\tpublic int FrameY { get { return textureRegion.Y; } set {\r\n\t\t\tAssignRect(new Rectangle(textureRegion.X, value, textureRegion.Width, textureRegion.Height));\r\n\t\t} }\r\n\r\n\t\tpublic int FrameWidth { get { return textureRegion.Width; } set {\r\n\t\t\tAssignRect(new Rectangle(textureRegion.X, textureRegion.Y, value, textureRegion.Height));\r\n\t\t} }\r\n\r\n\t\tpublic int FrameHeight { get { return textureRegion.Height; } set {\r\n\t\t\tAssignRect(new Rectangle(textureRegion.X, textureRegion.Y, textureRegion.Width, value));\r\n\t\t} }\r\n\r\n\t\tpublic Color BorderRectColor { get { return fillBrush.Color; } set { fillBrush.Color = value; } }\r\n\r\n\t\tpublic bool DrawTile { get { return drawTile; } set { drawTile = value; Draw(); } }\r\n\r\n\t\tprivate Image ErrorImage { get { return Properties.Resources.error; } }\r\n\r\n\t\tpublic bool HaveErrorIndicator { get { return haveErrorIndicator; } set { haveErrorIndicator = value; } }\r\n\r\n\t\tprivate Image texture, croppedTexture; // Textures\r\n\r\n\t\tprivate Rectangle textureRegion; // Frame Rect\r\n\r\n\t\tprivate bool drawTile = true, haveErrorIndicator=true;\r\n\r\n\t\tprivate float CPBR_X, CPBR_Y, CPBR_Width, CPBR_Height; // croppedPictureBoxRegion\r\n\r\n\t\tprivate Tuple<RectangleF, RectangleF> BorderRects;\r\n\r\n\t\tprivate SolidBrush fillBrush = new SolidBrush(Color.FromArgb(255, 0, 255));\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6828358173370361, "alphanum_fraction": 0.7027363181114197, "avg_line_length": 32.956520080566406, "blob_id": "8b3da73c81729cfe3b4f6f8de32b3289f8a6a973", "content_id": "3f8586ac2c574f94990bce40c2e1fd8c66be299b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1610, "license_type": "no_license", "max_line_length": 107, "num_lines": 46, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/Button.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic abstract class Button : Sprite, IPredefinedTexture {\r\n\t\tpublic Button(Vector2 position, int width=SPRITE_WIDTH, int height=SPRITE_HEIGHT) \r\n\t\t\t: base(position, width, height, true) { Initialize(TextureID); }\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Default\"] = new AnimationSequence(0, new Frame(160, 176, SPRITE_WIDTH, SPRITE_HEIGHT, 1, 1));\r\n\t\t\tAnimation[\"Dark\"] = new AnimationSequence(0, new Frame(160, 208, SPRITE_WIDTH, SPRITE_HEIGHT, 1, 1));\r\n\t\t\tAnimation[\"Active\"] = new AnimationSequence(0, new Frame(160, 240, SPRITE_WIDTH, SPRITE_HEIGHT, 1, 1));\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"Default\"); // Set to default animation sequence\r\n\t\t}\r\n\r\n\t\tpublic void Toggle() {\r\n\t\t\tactive = !active; // Switch active to not active\r\n\r\n\t\t\tif (active) Animation.SetAnimationSequence(\"Active\");\r\n\t\t\telse\t\tAnimation.SetAnimationSequence(\"Default\"); \r\n\t\t}\r\n\r\n\t\tpublic void InvokeClick() { Click(this); }\r\n\r\n\t\tpublic event Action<Button> Click = (self) => { };\r\n\r\n\t\tprotected bool active = false;\r\n\r\n\t\tpublic bool Active { get { return active; } set { if (active != value) Toggle(); } }\r\n\r\n\t\tpublic virtual String TextureID { get; protected set; } = @\"cs\\textbox\";\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 64, SPRITE_HEIGHT = 32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6967641115188599, "alphanum_fraction": 0.7019832730293274, "avg_line_length": 26.176469802856445, "blob_id": "22c0c75fd800879730984e42a02a32bf074a2142", "content_id": "d901ac0ac5bf0daa4f6500992521204775b84a55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 87, "num_lines": 68, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/PushableText.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic class PushableText : IPushable {\r\n\t\tpublic PushableText(Vector2 position, String text, Color color, String fontKey) {\r\n\t\t\tPosition = position;\r\n\t\t\tfont = fontKey;\r\n\t\t\tthis.color = color;\r\n\t\t\tstringToOutput = text;\r\n\t\t}\r\n\r\n\t\tpublic void Update(bool updateAnimation=true) {\r\n\t\t\tint elapsedMilitime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\tfloat elapsedTime = elapsedMilitime * (float)Math.Pow(10, -3); // To Miliseconds\r\n\r\n\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) {\r\n\t\t\t\tPushPack = null; // Delete push args\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(Font, stringToOutput, Position, color);\r\n\t\t}\r\n\r\n\t\tpublic void PushTo(Vector2 position, float over=0.8f) {\r\n\t\t\tif (PushArgs.PushValid(position, Position))\r\n\t\t\t\tPush(new PushArgs(position, Position, over, true));\r\n\t\t}\r\n\r\n\t\tpublic void Push(PushArgs push) { PushPack = push; }\r\n\r\n\t\tpublic Vector2 MeasureString(String str) {\r\n\t\t\treturn Font.MeasureString(str);\r\n\t\t}\r\n\r\n\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\r\n\t\tpublic Vector2 Size { get { return MeasureString(stringToOutput); } }\r\n\r\n\t\tpublic SpriteFont Font { get { return GV.MonoGameImplement.fonts[font]; } }\r\n\r\n\t\tprivate String font;\r\n\r\n\t\tprivate Color color;\r\n\r\n\t\tprivate String stringToOutput;\r\n\r\n\t\tpublic Vector2 Position { get; set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.698019802570343, "alphanum_fraction": 0.698019802570343, "avg_line_length": 27.381818771362305, "blob_id": "9787ac6861d6ee68ae3419d1591698665069d31c", "content_id": "212e6c32f0736fd8ab83a63a951066a320cc2dcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1618, "license_type": "no_license", "max_line_length": 83, "num_lines": 55, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Forms/SetZoomDialog.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing M = HollowAether.Lib.GlobalVars.BasicMath;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class SetZoomDialog : Form {\r\n\t\tSetZoomDialog(float current, float min, float max) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tminZoomTextBox.Text = min.ToString();\r\n\t\t\tmaxZoomTextBox.Text = max.ToString();\r\n\t\t\tzoomTextBox.Text = current.ToString();\r\n\t\t}\r\n\r\n\t\tprivate void SetZoomDialog_Load(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\tpublic static float GetZoom(float current, float min, float max) {\r\n\t\t\tSetZoomDialog dialog = new SetZoomDialog(current, min, max);\r\n\r\n\t\t\tDialogResult result = dialog.ShowDialog(); // Get result\r\n\r\n\t\t\tif (result != DialogResult.OK) return current; else {\r\n\t\t\t\tfloat? currentValue = GV.Misc.StringToFloat(dialog.zoomTextBox.Text);\r\n\r\n\t\t\t\tif (currentValue.HasValue) return M.Clamp(currentValue.Value, min, max); else {\r\n\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t$\"Couldn't cast value to float, zoom set to {current}\", \"Error\",\r\n\t\t\t\t\t\tMessageBoxButtons.OKCancel, MessageBoxIcon.Error // Show Msg\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn current; // return value passed to method at start\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\tDialogResult = DialogResult.OK;\r\n\t\t\tClose(); // Close form after click\r\n\t\t}\r\n\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) {\r\n\t\t\tClose();\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7045497298240662, "alphanum_fraction": 0.7090432643890381, "avg_line_length": 40.38888931274414, "blob_id": "5b7654f1a253def23fc97673b244cf571454e1b1", "content_id": "caf6e0616accffcc04f1f474f362c52249b82af3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5343, "license_type": "no_license", "max_line_length": 108, "num_lines": 126, "path": "/HollowAether/Lib/InputOutput/SettingsManager.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\nusing System.Xml;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.InputOutput {\r\n\t/// <summary>Class to manage settings operations for the game</summary>\r\n\tpublic class SettingsManager {\r\n\t\t/// <summary> Constructor auto builds settings file</summary>\r\n\t\tpublic SettingsManager() { BuildSettings(); }\r\n\r\n\t\t/// <summary>Method to read, interpret or create anew, the players window settings</summary>\r\n\t\tpublic void BuildSettings() {\r\n\t\t\tDictionary<String, String> settings; // holder for settings and value pairs\r\n\t\t\t\r\n\t\t\ttry { settings = (settingsWriterStream.Length == 0) ? BuildDefaultSettings() : ReadSettings(); } \r\n\t\t\tcatch { throw new XmlException(\"Settings File Parse Error\"); } // Get settings or throw error\r\n\t\t\t\r\n\t\t\tshouldBeFullScreen = settings[\"fullscreen\"].ToLower() == \"true\";\r\n\r\n\t\t\tGlobalVars.MonoGameImplement.framesPerSecond = (float)Convert.ToDouble(settings[\"fps\"]);\r\n\t\t\t// GlobalVars.username = settings[\"username\"]; // UName not implemented\r\n\r\n\t\t\tint width = Convert.ToInt32(settings[\"width\"]), height = Convert.ToInt32(settings[\"height\"]);\r\n\t\t\tGlobalVars.hollowAether.SetWindowDimensions(width, height); // set window dimensions using game\r\n\t\t}\r\n\r\n\t\t/// <summary>Saves current window settings to save file</summary>\r\n\t\tpublic void Save() {\r\n\t\t\tWriteXML(GlobalVars.Variables.windowWidth, GlobalVars.Variables.windowHeight, \r\n\t\t\t\tGlobalVars.hollowAether.IsFullScreen, GlobalVars.MonoGameImplement.framesPerSecond, \"UNAME\");\r\n\t\t}\r\n\r\n\t\t/// <summary>Reads settings from settings file in assets folder</summary>\r\n\t\t/// <returns>Dictionary containing settings parameters as keys and values as values</returns>\r\n\t\tprivate Dictionary<String, String> ReadSettings() {\r\n\t\t\tXmlReader reader = XmlReader.Create(settingsWriterStream);\r\n\t\t\tDictionary<String, String> settings = new Dictionary<String, String>();\r\n\t\t\tString lastName = String.Empty;\r\n\r\n\t\t\twhile (reader.Read()) {\r\n\t\t\t\tbool nodeSet = reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.Text;\r\n\r\n\t\t\t\tif (nodeSet && reader.Name != \"Settings\") {\r\n\t\t\t\t\tif (reader.Name == \"dimensions\" && reader.HasAttributes)\r\n\t\t\t\t\t\tsettings.Add(\"fullscreen\", reader.GetAttribute(\"fullscreen\"));\r\n\t\t\t\t\telse if (reader.NodeType == XmlNodeType.Element) lastName = reader.Name;\r\n\t\t\t\t\telse settings.Add(lastName, reader.Value); // Add name to settings\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn settings;\r\n\t\t}\r\n\r\n\t\t/// <summary> Use when no settings file has been made </summary>\r\n\t\tprivate Dictionary<String, String> BuildDefaultSettings() {\r\n\t\t\tWriteXML(1000, 640, false, 60, Environment.UserName); // Default settings\r\n\t\t\t\r\n\t\t\treturn new Dictionary<String, String>() {\r\n\t\t\t\t{ \"username\", Environment.UserName }, { \"fps\", \"60\" },\r\n\t\t\t\t{ \"width\", \"1000\" }, { \"height\", \"640\" },\r\n\t\t\t\t{ \"fullscreen\", false.ToString() }\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t/// <summary>Creates an XML writer with easy to use settings</summary>\r\n\t\tprivate void CreateXMLWriter() {\r\n\t\t\tXmlWriterSettings settings = new XmlWriterSettings() {\r\n\t\t\t\tIndent = true, IndentChars = \" \", NewLineChars = \"\\r\\n\",\r\n\t\t\t\tNewLineHandling = NewLineHandling.Replace\r\n\t\t\t};\r\n\r\n\t\t\tsettingsWriterStream.SetLength(0L);\r\n\t\t\tsettingsWriter = XmlWriter.Create(settingsWriterStream, settings);\r\n\t\t}\r\n\r\n\t\t/// <summary>Actual method to store settings</summary>\r\n\t\t/// <param name=\"windowWidth\">Width of current window (Out of full screen)</param>\r\n\t\t/// <param name=\"windowHeight\">Height of current window (Out of full screen)</param>\r\n\t\t/// <param name=\"fullscreen\">Wether the current window is full screen or not</param>\r\n\t\t/// <param name=\"fps\">The amount of frames drawn to the screen per second</param>\r\n\t\t/// <param name=\"uname\">The name of current computers user (could come in useful)</param>\r\n\t\tprivate void WriteXML(float windowWidth, float windowHeight, bool fullscreen, float fps, String uname) {\r\n\t\t\tCreateXMLWriter();\r\n\r\n\t\t\tsettingsWriter.WriteStartDocument();\r\n\t\t\tsettingsWriter.WriteStartElement(\"Settings\");\r\n\r\n\t\t\tsettingsWriter.WriteStartElement(\"dimensions\");\r\n\t\t\tsettingsWriter.WriteAttributeString(\"fullscreen\", fullscreen.ToString());\r\n\t\t\tWriteElement(\"width\", windowWidth.ToString());\r\n\t\t\tWriteElement(\"height\", windowHeight.ToString());\r\n\t\t\tsettingsWriter.WriteEndElement();\r\n\r\n\t\t\tWriteElement(\"fps\", fps.ToString());\r\n\t\t\tWriteElement(\"username\", uname);\r\n\r\n\t\t\tsettingsWriter.WriteEndElement();\r\n\r\n\t\t\tsettingsWriter.WriteEndDocument();\r\n\t\t\tsettingsWriter.Close();\r\n\t\t}\r\n\r\n\t\t/// <summary> Writes a single tag to the settings file</summary>\r\n\t\t/// <param name=\"elementName\">Name of element/tag to append</param>\r\n\t\t/// <param name=\"value\">Value given to said element/tag</param>\r\n\t\tprivate void WriteElement(String elementName, String value=null) {\r\n\t\t\tsettingsWriter.WriteStartElement(elementName);\r\n\t\t\t\r\n\t\t\tif (!String.IsNullOrWhiteSpace(value))\r\n\t\t\t\tsettingsWriter.WriteString(value);\r\n\t\t\t\r\n\t\t\tsettingsWriter.WriteEndElement();\r\n\t\t}\r\n\t\t\r\n\t\tprivate XmlWriter settingsWriter; // XMLwriter can write to the xml file.\r\n\t\tpublic FileStream settingsWriterStream = new FileStream(settingsPath, FileMode.OpenOrCreate);\r\n\t\tpublic static String settingsPath = Path.Combine(Directory.GetCurrentDirectory(), @\"Assets\\settings.xml\");\r\n\t\tpublic bool shouldBeFullScreen = false;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7092248201370239, "alphanum_fraction": 0.7144861221313477, "avg_line_length": 33.197532653808594, "blob_id": "b317b55446c46c2f3e870439e56ed84cb7ea5371", "content_id": "57d94b9d5a3090cc99b963b40e6b43410d35fdbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2853, "license_type": "no_license", "max_line_length": 114, "num_lines": 81, "path": "/HollowAether/Lib/Global/GlobalVars/DrawMethods.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class DrawMethods {\r\n\t\t\tpublic static void DrawBoundary(IBoundaryContainer boundary, Color? color = null) {\r\n\t\t\t\tcolor = color.HasValue ? color.Value : Color.White;\r\n\r\n\t\t\t\tforeach (IBoundary cBoundary in boundary) {\r\n\t\t\t\t\tif (cBoundary is IBRectangle) {\r\n\t\t\t\t\t\tDrawRectangleFrame((IBRectangle)cBoundary, color);\r\n\t\t\t\t\t} else if (cBoundary is IBTriangle) {\r\n\t\t\t\t\t\tDrawTriangleFrame((IBTriangle)cBoundary, color);\r\n\t\t\t\t\t} else if (cBoundary is IBCircle) {\r\n\t\t\t\t\t\t((IBCircle)cBoundary).Draw(color.Value);\r\n\t\t\t\t\t} else if (cBoundary is IBRotatedRectangle) {\r\n\t\t\t\t\t\t((IBRotatedRectangle)cBoundary).Draw(color.Value);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void DrawTriangleFrame(IBTriangle triangle, Color? color = null, int lineThickenes = 1) {\r\n\t\t\t\ttriangle.Draw(color, lineThickenes); // Taken care of in class\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void DrawRectangleFrame(IBRectangle rectangle, Color? color = null, int lineThickness = 1) {\r\n\t\t\t\tforeach (Line line in Convert.RectangleTo4Lines(rectangle)) {\r\n\t\t\t\t\tDrawLine(line.pointA, line.pointB, color, lineThickness);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void DrawRectangleFrame(IBRotatedRectangle rectangle, Color? color=null, int lineThickness = 1) {\r\n\t\t\t\tforeach (Line line in Convert.RotatedRectangleTo4Lines(rectangle)) {\r\n\t\t\t\t\tDrawLine(line.pointA, line.pointB, color, lineThickness);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void DrawLine(Vector2 start, Vector2 end, Color? _color = null, int thickness = 1) {\r\n\t\t\t\t//GlobalVars.InitializeSpriteBatch(); // Taken care of by GameWindow\r\n\r\n\t\t\t\tVector2 edge = end - start; Color defaultC = Color.White;\r\n\t\t\t\tfloat angle = (float)Math.Atan2(edge.Y, edge.X);\r\n\t\t\t\tRectangle rect = new Rectangle((int)start.X, (int)start.Y, (int)edge.Length(), thickness);\r\n\r\n\t\t\t\tMonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\t\ttexture: GlobalVars.MonoGameImplement.textures[\"debugFrame\"], destinationRectangle: rect,\r\n\t\t\t\t\tcolor: (_color.HasValue) ? _color.Value : defaultC,\r\n\t\t\t\t\trotation: angle, scale: new Vector2(0, 0), layerDepth: 0.6f\r\n\t\t\t\t);\r\n\r\n\t\t\t\t//GlobalVars.spriteBatch.End();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5443691611289978, "alphanum_fraction": 0.5487253665924072, "avg_line_length": 37.730770111083984, "blob_id": "f6dc031771a652ccc4ab98b97a4b6fea8d099804", "content_id": "6a4793c5233b761942b3127eeb0ec013ee25a509", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6198, "license_type": "no_license", "max_line_length": 86, "num_lines": 156, "path": "/HollowAether/PyScripts/input_parser.py", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "# >> InputParser Class Definition Version\\\\Rendition 1.00 || (C) M.K. 2017 << #\r\n\r\nfrom re import findall, escape, split # Regex Imports for line\\string parsing\r\n\r\nclass IPErrors(object):\r\n \"\"\"Exception Class Holder\"\"\"\r\n class InputFormatError(Exception):\r\n \"\"\"Thrown when input string isn't a string\"\"\"\r\n def __init__(self, type):\r\n string = \"Input Of Type '{}' Not Accepted\".format(type)\r\n super().__init__(string)\r\n \r\n class ContainerTypeError(Exception):\r\n \"\"\"Thrown when container isn't a tuple\"\"\"\r\n def __init__(self, string, type):\r\n string = \"'{}' Must Be A Tuple Not A '{}'\".format(string, type)\r\n super().__init__(string)\r\n\r\n class UnacceptedTypeInContainerError(Exception):\r\n \"\"\"Thrown when value in container is of undesired type\"\"\"\r\n def __init__(self, index, string, type):\r\n string = \"'{}' Has An Unaccepted Value of Type '{}' At Index '{}'\".format(\r\n string, type, index\r\n )\r\n \r\n super().__init__(string)\r\n\r\n\r\nclass Flag(object):\r\n \"\"\"Container class for flag and any corresponding\r\n arguments flag was passed with during initialisation\"\"\"\r\n def __init__(self, flag, *args):\r\n self.flag, self.args = flag, args\r\n\r\n def __repr__(self):\r\n if isinstance(self.flag, str):\r\n return self.flag\r\n\r\n try:\r\n return str(self.flag)\r\n except:\r\n return \"Flag Print Error\"\r\n\r\n def __eq__(self, other):\r\n f_check = str(self.flag) == str(other.flag)\r\n a_check = self.args == other.args\r\n \r\n if isinstance(other, Flag):\r\n # comparing everything you can\r\n return f_check and a_check\r\n elif isinstance(other, str):\r\n return f_check\r\n elif isinstance(other, list):\r\n return a_check\r\n else:\r\n raise TypeError(\"Other Type Not Accepted : {} :\".format(type(other)))\r\n\r\n def __len__(self):\r\n return len(self.args)\r\n\r\n\r\nclass InputParser(object):\r\n \"\"\"Class to parse user input. Quite self explanatory :)\\n\r\n c_chars are the container characters used like \\\" or \\'.\r\n f_chars are the characters used to interpret flags like '-' or '+'.\\n\\n\r\n Warning: Avoid using multiple c_chars in the same string like \"'hello' there\" \"\"\"\r\n def __init__(self, c_chars=('\"', \"'\"), f_chars=('-',)):\r\n self.container_chars, self.flag_chars = c_chars, f_chars\r\n\r\n def _exception_check(self, s_input):\r\n \"\"\"Wether any value types are wrong and then throws an exception\"\"\"\r\n if not(isinstance(s_input, str)):\r\n raise IPErrors.InputFormatError(type(s_input))\r\n elif not(isinstance(self.container_chars, tuple)):\r\n raise IPErrors.ContainerTypeError(\r\n \"Container Chars\", type(self.container_chars))\r\n elif not(isinstance(self.flag_chars, tuple)):\r\n raise IPErrors.ContainerTypeError(\r\n \"Flag Chars\", type(self.container_chars))\r\n elif False in [isinstance(X, str) for X in self.container_chars]:\r\n index = [isinstance(X, str) for X in self.container_chars].index(False)\r\n \r\n raise IPErrors.UnacceptedTypeInContainerError(\r\n index, \"Container Chars\", type(self.container_chars[index])\r\n )\r\n elif False in [isinstance(X, str) for X in self.flag_chars]:\r\n index = [isinstance(X, str) for X in self.flag_chars].index(False)\r\n \r\n raise IPErrors.UnacceptedTypeInContainerError(\r\n index, \"Flag Chars\", type(self.container_chars[index])\r\n )\r\n\r\n def _get_str_contained_terms(self, sub_string):\r\n # extracts items within container chars\r\n container_array = list() # empty list to contain results\r\n get_search_term = gst = lambda X: '{0}([^{0}]*){0}'.format(X)\r\n \r\n for C in self.container_chars:\r\n container_array.extend(\r\n [\"{}{}{}\".format(C, X, C) for X in findall(gst(C), sub_string)]\r\n\t\t\t)\r\n\r\n return container_array\r\n\r\n def parse_input(self, s_input):\r\n \"\"\"parses input from string.\r\n Returns Tuple containing Flags\"\"\"\r\n self._exception_check(s_input)\r\n\r\n if len(self.flag_chars) == 0:\r\n # no potential flags in parser\r\n for C in self.container_chars:\r\n # remove container characters\r\n s_input = s_input.replace(C, '')\r\n \r\n return s_input.split(' ')\r\n\r\n s_input, found = self.flag_chars[0] + '\\0 ' + s_input, list()\r\n contained = self._get_str_contained_terms(s_input)\r\n c_index = contained_index = 0\r\n\r\n for c_arg in contained:\r\n #if not(c_arg in s_input): continue\r\n s_input = s_input.replace(c_arg, '\\0')\r\n\r\n for flagsplit in split('|'.join(map(escape, self.flag_chars)), s_input):\r\n if len(flagsplit) < 1: continue # ignore 0 length\r\n flag, container = flagsplit.split(' ')[0], list()\r\n flag = flag if flag != '\\0' else None \r\n \r\n for arg in ' '.join(flagsplit.split(' ')[1:]).split(' '):\r\n if len(arg) == 0:\r\n continue\r\n elif arg == '\\0': # contained_item\r\n container.append(contained[c_index][1:-1])\r\n # 1 to -1 removes container chars from str\r\n c_index = c_index + 1 # increment by one\r\n else:\r\n container.append(arg)\r\n\r\n found.append((flag, container)) # Newer version returns tuple for c#.\r\n #found.append(Flag(flag, *container)) # Original Rendition Used Flags.\r\n \r\n return tuple(found)\r\n\r\n @staticmethod\r\n def _input_parse(string, c_chars=None, f_chars=None):\r\n \"\"\"Unrecommended approach to parse input statically\"\"\"\r\n ip = InputParser()\r\n\r\n if not(c_chars is None):\r\n ip.container_chars = c_chars\r\n if not(f_chars is None):\r\n ip.flag_chars = f_chars\r\n\r\n return ip.parse_input(string)\r\n" }, { "alpha_fraction": 0.7089290618896484, "alphanum_fraction": 0.7175613641738892, "avg_line_length": 36.216495513916016, "blob_id": "8b16b50ca8beac239408a67761aea2f140e864a3", "content_id": "ba0cea2ffc657a7d23971eec76aa954c2dc8903b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3709, "license_type": "no_license", "max_line_length": 111, "num_lines": 97, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Jumper.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Jumper : Enemy, IPredefinedTexture {\r\n\t\tpublic Jumper() : this(Vector2.Zero, 1) { }\r\n\r\n\t\tpublic Jumper(Vector2 position, int level) : base(position, 2 * FRAME_WIDTH, 2 * FRAME_HEIGHT, level, true) {\r\n\t\t\tInitialize(@\"enemies\\jumper\");\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey);\r\n\r\n\t\t\tmaxJumpHeight = GetMaxJumpHeight(Level); // Set max jump height depending on enemy level.\r\n\t\t\tjumpVelocity = new Vector2(0, -GV.Physics.GetJumpVelocity(GV.MonoGameImplement.gravity, maxJumpHeight));\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Idle\"] = GV.MonoGameImplement.importedAnimations[@\"jumper\\idle\"];\r\n\t\t\tAnimation[\"Laughing\"] = GV.MonoGameImplement.importedAnimations[@\"jumper\\laughing\"];\r\n\t\t\tAnimation[\"Crouched\"] = GV.MonoGameImplement.importedAnimations[@\"jumper\\crouched\"];\r\n\t\t\tAnimation[\"Jumping\"] = GV.MonoGameImplement.importedAnimations[@\"jumper\\jumping\"];\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"Laughing\");\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(SpriteRect));\r\n\t\t}\r\n\r\n\t\tprotected override void DoEnemyStuff() {\r\n\t\t\tif (!Falling()) { // When not already jumping, check whether in range to jump upwards\r\n\t\t\t\tVector2 playerCenter = GV.MonoGameImplement.Player.SpriteRect.Center.ToVector2();\r\n\r\n\t\t\t\tVector2 distanceDifferential = (SpriteRect.Center.ToVector2() - playerCenter);\r\n\r\n\t\t\t\tif (distanceDifferential.Y < 5 * maxJumpHeight) { // If jumping can reach player\r\n\t\t\t\t\tfloat theta = (float)Math.Atan2(distanceDifferential.X, distanceDifferential.Y);\r\n\t\t\t\t\tint thetaDeg = (int)Math.Round(GV.BasicMath.RadiansToDegrees(theta)); // to degrees\r\n\r\n\t\t\t\t\tif (Math.Abs(thetaDeg) < 25) Jump(); // If angle between enemy and player is small enough\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tImplementGravity(); // Push back down if not atop block. If so, then stop jumping altogether\r\n\r\n\t\t\tif (velocity != Vector2.Zero) OffsetSpritePosition(velocity * elapsedTime); // Add displacement\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t\tif (!Alive) ImplementGravity();\r\n\t\t}\r\n\r\n\t\tpublic void Jump() {\r\n\t\t\tvelocity = jumpVelocity; // Set velocity to enemy jump velocity\r\n\r\n\t\t\tAnimationChain chain = new AnimationChain(Animation[\"Crouched\"]); // new chain\r\n\t\t\tchain.ChainFinished += () => { Animation.SetAnimationSequence(\"Jumping\"); };\r\n\t\t\tAnimation.AttatchAnimationChain(chain); // Attach chain to existing animation\r\n\t\t\tAnimation.Update(); // Move to next frame in newly attatched animation chain\r\n\t\t}\r\n\r\n\t\tprotected override void StopFalling() {\r\n\t\t\tvelocity = Vector2.Zero; // This enemy doesn't have any horizontal velocity anyways\r\n\t\t\tAnimation.SetAnimationSequence(\"Laughing\"); // Reset to default animation when grounded\r\n\t\t}\r\n\r\n\t\tprivate int GetMaxJumpHeight(int level) {\r\n\t\t\treturn GV.BasicMath.Clamp<int>(6 * GV.Variables.random.Next(Level - 2, Level + 3), 30, 250);\r\n\t\t}\r\n\r\n\t\tprivate int maxJumpHeight;\r\n\r\n\t\tprivate Vector2 jumpVelocity;\r\n\r\n\t\tprotected override bool CanGenerateHealth { get; set; } = false;\r\n\r\n\t\tprotected override bool CausesContactDamage { get; set; } = true;\r\n\r\n\t\tpublic const int FRAME_WIDTH = 16, FRAME_HEIGHT = 16;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = FRAME_WIDTH * 2, SPRITE_HEIGHT = FRAME_HEIGHT * 2;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7224164009094238, "alphanum_fraction": 0.7224164009094238, "avg_line_length": 30.30645179748535, "blob_id": "02ad5de674c7587a31e50cab4a47d57b8deb7c70", "content_id": "302aa5aa850c66d685ab43607a608f0026302688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 107, "num_lines": 62, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/AnimationView/RenameAnimationSequenceDialog.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class RenameAnimationSequenceDialog : Form {\r\n\t\tpublic RenameAnimationSequenceDialog(string key) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tdefaultSequenceKey = key;\r\n\r\n\t\t\tresetButton_Click(this, null);\r\n\t\t}\r\n\r\n\t\tprivate void RenameAnimationSequenceDialog_Load(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\tpublic static Tuple<DialogResult, string, string> Run(string current) {\r\n\t\t\tRenameAnimationSequenceDialog dialog = new RenameAnimationSequenceDialog(current);\r\n\r\n\t\t\tDialogResult result = dialog.ShowDialog(); // Show dialog and get result\r\n\r\n\t\t\tstring animContainer = dialog.animationContainerTextBox.Text;\r\n\t\t\tstring sequenceName = dialog.sequenceNameTextBox.Text;\r\n\r\n\t\t\tstring returnVal = $\"{animContainer}\\\\{sequenceName}\".ToLower();\r\n\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tbool typeInvalid = String.IsNullOrWhiteSpace(animContainer) || String.IsNullOrWhiteSpace(sequenceName);\r\n\r\n\t\t\t\tif (returnVal.ToLower() == current.ToLower()) result = DialogResult.Cancel; else if (typeInvalid) {\r\n\t\t\t\t\tMessageBox.Show(\"One or More Inputs Are Empty\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t\t\t\tresult = DialogResult.Cancel; // Invalid entry, means cancel dialog\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn new Tuple<DialogResult, string, string>(result, current, returnVal);\r\n\t\t}\r\n\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) {\r\n\t\t\t//Close();\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\t//Close();\r\n\t\t}\r\n\r\n\t\tprivate void resetButton_Click(object sender, EventArgs e) {\r\n\t\t\tanimationContainerTextBox.Text = defaultSequenceKey.Split('\\\\').First();\r\n\t\t\tsequenceNameTextBox.Text = defaultSequenceKey.Split('\\\\').Last();\r\n\t\t}\r\n\r\n\t\tprivate string defaultSequenceKey;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6768231987953186, "alphanum_fraction": 0.6773226857185364, "avg_line_length": 27.674074172973633, "blob_id": "37d5e72f68ce69b5f819626bcdb3c35e437cdc19", "content_id": "d853fd3612a13556da066750c5eba265b7468a48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4006, "license_type": "no_license", "max_line_length": 117, "num_lines": 135, "path": "/HollowAether/Lib/InputOutput/MapZone/AssetTrace.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\n\r\nnamespace HollowAether.Lib.MapZone {\r\n\tpublic class AssetTrace {\r\n\t\tpublic class AssetTraceArgs {\r\n\t\t\tpublic String ToFileContents() {\r\n\t\t\t\tif\t\t(IsImported) return $\"ImportAsset: \\\"{Type}\\\" {Value} as [{ID}]\";\r\n\t\t\t\telse if (IsDefinition) return $\"DefineAsset: \\\"{Type}\\\" [{ID}] {Value}\";\r\n\t\t\t\telse if (IsAssignment) return $\"Set: [{ID}] {Value}\";\r\n\r\n\t\t\t\tthrow new HollowAetherException($\"Asset '{ID}' Not Set, Imported Or Defined\");\r\n\t\t\t}\r\n\r\n\t\t\t#region ArgumentType\r\n\t\t\tpublic bool IsImported { get; set; } = false;\r\n\r\n\t\t\tpublic bool IsDefinition { get; set; } = false;\r\n\r\n\t\t\tpublic bool IsAssignment { get; set; } = false;\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region ValueDefintions\r\n\t\t\tpublic string DefaultValue { get; set; } = null;\r\n\r\n\t\t\tpublic string Type { get; set; }\r\n\r\n\t\t\tpublic string Value { get; set; }\r\n\r\n\t\t\tpublic string ID { get; set; }\r\n\t\t\t#endregion\r\n\r\n\t\t\tpublic bool HasDefaultValue { get { return DefaultValue != null; } }\r\n\r\n\t\t\tpublic bool ValueAssigned { get { return Value != null; } }\r\n\t\t}\r\n\r\n\t\tstatic AssetTrace() {\r\n\t\t\tglobalAssetsClone = (from X in GV.MapZone.globalAssets.Values.ToArray() select X.Clone() as Asset).ToArray();\r\n\t\t\t// Clone all default global assets/values in existance. In most cases, these will be unassigned by default\r\n\t\t}\r\n\r\n\t\tpublic AssetTrace() {\r\n\t\t\tforeach (Asset asset in globalAssetsClone) {\r\n\t\t\t\tstore.Add(new AssetTraceArgs() { // Note: can only be assigned\r\n\t\t\t\t\tID = asset.assetID, Type = asset.assetType.Name, IsAssignment = true,\r\n\t\t\t\t\tDefaultValue = Converters.ValueToString(asset.assetType, asset.GetValue())\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void AddImportAsset(string ID, string type, string value) {\r\n\t\t\tstore.Add(new AssetTraceArgs() { ID = ID, Type = type, Value = value, IsImported = true });\r\n\t\t}\r\n\r\n\t\tpublic void AddDefineAsset(string ID, string type, string value) {\r\n\t\t\tstore.Add(new AssetTraceArgs() { ID = ID, Type = type, Value = value, IsDefinition = true });\r\n\t\t}\r\n\r\n\t\tpublic void AddSetAsset(string ID, string value) {\r\n\t\t\tstore[GetIndexFromKey(ID)].Value = value;\r\n\t\t}\r\n\r\n\t\tpublic void AddEmptyAsset(string id, string type, bool definition = false, bool import = false, bool set = false) {\r\n\t\t\tstore.Add(new AssetTraceArgs() {\r\n\t\t\t\tID = id, Type = type, IsDefinition = definition,\r\n\t\t\t\tIsImported = import, IsAssignment = set\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tpublic string ToFileContents() {\r\n\t\t\tStringBuilder builder = new StringBuilder();\r\n\r\n\t\t\tforeach (AssetTrace.AssetTraceArgs args in store) {\r\n\t\t\t\tif (args.ValueAssigned) builder.AppendLine(args.ToFileContents());\r\n\t\t\t}\r\n\r\n\t\t\treturn builder.ToString();\r\n\t\t}\r\n\r\n\t\tpublic void DeleteAssetValue(string id) {\r\n\t\t\tstore[GetIndexFromKey(id)].Value = null;\r\n\t\t}\r\n\r\n\t\tpublic void DeleteAsset(string id) {\r\n\t\t\tstore.RemoveAt(GetIndexFromKey(id));\r\n\t\t}\r\n\r\n\t\tpublic void SetValue(string id, string value) {\r\n\t\t\tstore[GetIndexFromKey(id)].Value = value;\r\n\t\t}\r\n\r\n\t\tprivate int GetIndexFromKey(string id) {\r\n\t\t\tforeach (int X in Enumerable.Range(0, store.Count)) {\r\n\t\t\t\tif (store[X].ID == id) return X; // Found at X\r\n\t\t\t}\r\n\r\n\t\t\treturn -1;\r\n\t\t}\r\n\r\n\t\tpublic bool Exists(string id) {\r\n\t\t\tforeach (AssetTraceArgs args in store) {\r\n\t\t\t\tif (id == args.ID) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false; // Not Found\r\n\t\t}\r\n\r\n\t\tprivate static Asset[] globalAssetsClone;\r\n\t\tpublic List<AssetTraceArgs> store = new List<AssetTraceArgs>();\r\n\t}\r\n}" }, { "alpha_fraction": 0.7498318552970886, "alphanum_fraction": 0.7511768937110901, "avg_line_length": 40.485713958740234, "blob_id": "4a9c07044ee6deb461a12b2638115553953947a3", "content_id": "598db754b8cc53defb8922245bcc90f0bfe833d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 121, "num_lines": 35, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/HUDExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tclass HUDHealthRangeException : HollowAetherException {\r\n\t\tpublic HUDHealthRangeException(int HUDSpan, int newHUDHealth, String message) : base(message) {\r\n\t\t\thudSpan = HUDSpan; hudHealth = newHUDHealth;\r\n\t\t}\r\n\r\n\t\tpublic HUDHealthRangeException(int HUDSpan, int newHUDHealth, String message, Exception inner) : base(message, inner) {\r\n\t\t\thudSpan = HUDSpan; hudHealth = newHUDHealth;\r\n\t\t}\r\n\r\n\t\tint hudSpan, hudHealth;\r\n\t}\r\n\r\n\tclass HUDHealthAdditionException : HUDHealthRangeException {\r\n\t\tpublic HUDHealthAdditionException(int HUDSpan, int newHUDHealth)\r\n\t\t\t: base(HUDSpan, newHUDHealth, $\"Cannot increase Hud health to {newHUDHealth}. Max span is {HUDSpan}\") { }\r\n\r\n\t\tpublic HUDHealthAdditionException(int HUDSpan, int newHUDHealth, Exception inner)\r\n\t\t\t: base(HUDSpan, newHUDHealth, $\"Cannot increase Hud health to {newHUDHealth}. Max span is {HUDSpan}\", inner) { }\r\n\t}\r\n\r\n\tclass HUDHealthSubtractionException : HUDHealthRangeException {\r\n\t\tpublic HUDHealthSubtractionException(int HUDSpan, int newHUDHealth)\r\n\t\t\t: base(HUDSpan, newHUDHealth, $\"Cannot health Hud health to {newHUDHealth}. Min span is 0\") { }\r\n\r\n\t\tpublic HUDHealthSubtractionException(int HUDSpan, int newHUDHealth, Exception inner)\r\n\t\t\t: base(HUDSpan, newHUDHealth, $\"Cannot increase Hud health to {newHUDHealth}. Min span is 0\", inner) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7081360220909119, "alphanum_fraction": 0.7163150906562805, "avg_line_length": 43.698360443115234, "blob_id": "43802606288fd927ff3e1fcb6a082379840a0309", "content_id": "aaa72b1a801b0e6a13b43f6264b4da3845a58431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 27878, "license_type": "no_license", "max_line_length": 135, "num_lines": 610, "path": "/HollowAether/Lib/GAssets/Living/Player.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic enum PlayerPerks {\r\n\t\tSetWaterGravityToNothing,\r\n\t\tPlayerImmortal,\r\n\t\tInfiniteShuriken\r\n\t}\r\n\r\n\t/// <summary>Player Object Instance</summary>\r\n\tpublic sealed partial class Player : BodySprite {\r\n\t\t#region Constructors\r\n\t\tstatic Player() { defaultJumpVelocity = -GV.Physics.GetJumpVelocity(GV.MonoGameImplement.gravity, maxJumpHeight); }\r\n\r\n\t\tpublic Player() : this(new Vector2()) { }\r\n\r\n\t\tpublic Player(Vector2 position, bool aRunning = true) : base(position, 32, 32, aRunning) {\r\n\t\t\tInitialize(@\"cs\\main\"); // Initialize directly from construction\r\n\t\t\tLayer = 0.5f; // set sprite layer to just above block\r\n\t\t\tImplementPerks(PlayerPerks.SetWaterGravityToNothing);\r\n\t\t}\r\n\t\t#endregion\r\n\t\t\r\n\t\tpublic void Attack(int damage) {\r\n\t\t\tif (timeInvincible <= 0 && !CurrentWeapon.Attacking) { // Attack when player isn't invincible\r\n\t\t\t\tGV.MonoGameImplement.GameHUD.TryTakeDamage(damage); // Take from health\r\n\r\n\t\t\t\tif (GV.MonoGameImplement.GameHUD.Health == 0) GameWindow.GameRunning.InvokePlayerDeceased(); else {\r\n\t\t\t\t\tHitSprite hs = new HitSprite(Position, 18, 18, HitSprite.HitType.Red);\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(hs); // Add to local store\r\n\r\n\t\t\t\t\tIMonoGameObject[] effect = FX.ValueChangedEffect.Create(\r\n\t\t\t\t\t\tPosition /*- new Vector2(50)*/, -damage, colors: FX.ValueChangedEffect.FlickerColor.Red\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tforeach (IMonoGameObject effectSprite in effect) GV.MonoGameImplement.additionBatch.AddNameless(effectSprite);\r\n\r\n\t\t\t\t\tAnimation.Opacity = 0.65f; // Make somewhat see through\r\n\t\t\t\t\ttimeInvincible = 1200; // Can't be hurt for 1.2 seconds\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey);\r\n\t\t\tsword = new Weapons.Sword(Vector2.Zero);\r\n\t\t\tshuriken = new Weapons.Shuriken(Vector2.Zero);\r\n\r\n\t\t\tweapons = new Weapon[] { sword, shuriken };\r\n\r\n\t\t\tEquip(sword); // Starter weapon = sword\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() { base.Draw(); CurrentWeapon.Draw(); }\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed gametime as well\r\n\r\n\t\t\t#region Inputs\r\n\t\t\tbool leftInput = GV.PeripheralIO.currentControlState.Left;\r\n\t\t\tbool rightInput = GV.PeripheralIO.currentControlState.Right;\r\n\t\t\tbool jumpInput = GV.PeripheralIO.currentControlState.Jump;\r\n\t\t\tbool dashInput = GV.PeripheralIO.currentControlState.Dash;\r\n\t\t\tbool previousLeftInput = GV.PeripheralIO.previousControlState.Left;\r\n\t\t\tbool previousRightInput = GV.PeripheralIO.previousControlState.Right;\r\n\t\t\tbool prevJumpInput = GV.PeripheralIO.previousControlState.Jump;\r\n\t\t\tbool weaponAttackInput = GV.PeripheralIO.currentControlState.Attack;\r\n\t\t\tbool weaponThrowInput = GV.PeripheralIO.currentControlState.Throw;\r\n\t\t\tbool weaponSwitchInput = GV.PeripheralIO.currentControlState.WeaponNext;\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region Weapons\r\n\t\t\tif (!thrownButtonReleased && !weaponThrowInput) thrownButtonReleased = true;\r\n\r\n\t\t\tif (weaponThrowInput && !CurrentWeapon.Thrown) {\r\n\t\t\t\tThrowWeapon(); thrownButtonReleased = false;\r\n\t\t\t} else if (CurrentWeapon.Thrown) {\r\n\t\t\t\tif (CurrentWeapon.returningToPlayer && Intersects(CurrentWeapon)) {\r\n\t\t\t\t\tEquip(CurrentWeapon); // Re equip once intersected with player & looking for player\r\n\t\t\t\t} else if (thrownButtonReleased && weaponThrowInput) {\r\n\t\t\t\t\tCallThrownWeaponBack();\r\n\t\t\t\t}\r\n\t\t\t} \r\n\r\n\t\t\tif (weaponSwitchTimeout > 0) {\r\n\t\t\t\t// If button released, erase timeout, else complete timeout\r\n\r\n\t\t\t\tif (!weaponSwitchInput) weaponSwitchTimeout = 0; else {\r\n\t\t\t\t\tweaponSwitchTimeout -= elapsedMilitime;\r\n\t\t\t\t}\r\n\t\t\t} else if (weaponSwitchInput) {\r\n\t\t\t\tSwitchToNextWeapon(); // Move to next weapon in inventory\r\n\t\t\t\tweaponSwitchTimeout = 500; // Half a second timeout\r\n\t\t\t}\r\n\r\n\t\t\tCurrentWeapon.Update(updateAnimation); // Update anim as well\r\n\r\n\t\t\tif (weaponAttackInput) AttackWeapon();\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region CheckDamage\r\n\t\t\tif (timeInvincible > 0) {\r\n\t\t\t\ttimeInvincible -= elapsedMilitime;\r\n\r\n\t\t\t\tif (timeInvincible <= 0) Animation.Opacity = 1.0f; // Make opaque\r\n\t\t\t} else {\r\n\t\t\t\tIMonoGameObject[] playerDamagingProjectiles = CompoundIntersects<IDamagingToPlayer>();\r\n\r\n\t\t\t\tif (playerDamagingProjectiles.Length > 0) {\r\n\t\t\t\t\tint damage = (from X in playerDamagingProjectiles select (X as IDamaging).GetDamage()).Aggregate((a, b) => a + b);\r\n\t\t\t\t\tAttack(damage); // Attack player with given damage. Note if simultaneously attacked by multiple then sum damage\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region BurstPointGeneration\r\n\t\t\tif (CanGenerateBurstPoints()) { // Player is capable of generating burst points\r\n\t\t\t\ttimeNotMoving += elapsedTime; // Increment the known time in which player is not moving\r\n\r\n\t\t\t\tif (timeNotMoving > TIME_BEFORE_POINT_GEN) { // Time before points start being generated\r\n\t\t\t\t\tpointGenerationRate += pointGenerationAcceleration * elapsedTime;\r\n\t\t\t\t\tgeneratingBurstPoints += pointGenerationRate * elapsedTime; // Increment generated burst points\r\n\r\n\t\t\t\t\t// if (generatingBurstPoints >= 1) {\r\n\t\t\t\t\t\tint incrementValue = (int)Math.Floor(generatingBurstPoints); // Value to increase\r\n\t\t\t\t\t\tgeneratingBurstPoints = generatingBurstPoints - incrementValue; // Set to point val\r\n\r\n\t\t\t\t\t\tburstPoints = (burstPoints + incrementValue < maxBurstPoints) ? burstPoints + incrementValue : maxBurstPoints;\r\n\t\t\t\t\t// }\r\n\t\t\t\t}\r\n\t\t\t} else { timeNotMoving = 0; generatingBurstPoints = 0; pointGenerationRate = DEFAULT_POINT_GENERATION_RATE; }\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region Interaction\r\n\t\t\tif (interaction_timeout > 0) interaction_timeout -= elapsedMilitime; else if (GV.PeripheralIO.currentControlState.Interact) {\r\n\t\t\t\tforeach (var interactable in CompoundIntersects<IInteractable>()) {\r\n\t\t\t\t\tbool isAutoInteractable = interactable is IAutoInteractable;\r\n\r\n\t\t\t\t\tif (!isAutoInteractable) ((IInteractable)interactable).Interact();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region LinearMovement\r\n\t\t\tif ((previousLeftInput && rightInput) || (previousRightInput && leftInput)) {\r\n\t\t\t\tvelocity.X = 0; // If direction of movement has changed\r\n\t\t\t}\r\n\r\n\t\t\tif (!Dashing) { // Only allow player movement control when not dashing\r\n\t\t\t\tif ((leftInput && rightInput) || !(leftInput || rightInput)) { // If both or neither\r\n\t\t\t\t\tStopRunning(); // Reset any forward velocity/acceleration until desired\r\n\t\t\t\t\tStallAnimation(); // Stop movement and keep facing in same direction\r\n\t\t\t\t} else { // Left input ^| Right input\r\n\t\t\t\t\tString facingDirection = (leftInput) ? \"Left\" : \"Right\";\r\n\r\n\t\t\t\t\tbool facingDirectionChanged = (FacingLeft && facingDirection == \"Right\") || (FacingRight && facingDirection == \"Left\");\r\n\r\n\t\t\t\t\tAnimation.SetAnimationSequence($\"running{facingDirection}\"); // Set running in facing direction for animation\r\n\r\n\t\t\t\t\tif (facingDirectionChanged) { // Re-Adjust position of sword\r\n\t\t\t\t\t\tif (!(CurrentWeapon.Thrown || CurrentWeapon.Attacking)) CurrentWeapon.AttachToPlayer(this); // Also sets position\r\n\t\t\t\t\t\t//if (!CurrentWeapon.Thrown) CurrentWeapon.SetWeaponPositionRelativeToPlayer(this);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tImplementRunning(leftInput); // run in input direction\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region Jumping\r\n\t\t\tif (prevJumpInput && !jumpInput) StopJumping(); else if (jumpInput) ImplementJumping(); // Implement jumping\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region Dashing Or Gravity\r\n\t\t\tif (dashInput && CanDash()) {\r\n\t\t\t\tdashArgs = new DashArgs(this, Animation.sequenceKey.Contains(\"Left\"));\r\n\t\t\t\tvelocity = Vector2.Zero; // Switch off velocity temporarily\r\n\t\t\t\tStallAnimation(); // Stall animation in facing direction\r\n\r\n\t\t\t\tSubtractBurstPoints(GV.Variables.playerDashCost); // Cost to dash\r\n\t\t\t} else if (Dashing) ImplementDashing(); else ImplementGravity();\r\n\t\t\t#endregion\r\n\r\n\t\t\tif (GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Top\")) {\r\n\t\t\t\tVerticalUpwardBoundaryFix();\r\n\t\t\t\tif (jumpInput || prevJumpInput) StopJumping();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region BurstPointManagement\r\n\t\t/// <summary>Gives player more burst points</summary>\r\n\t\t/// <param name=\"increment\">Value to add</param>\r\n\t\tpublic void AddBurstPoints(int increment) {\r\n\t\t\tburstPoints = (burstPoints + increment < maxBurstPoints) ? burstPoints + increment : maxBurstPoints;\r\n\t\t}\r\n\r\n\t\t/// <summary>Takes burst points from user</summary>\r\n\t\t/// <param name=\"value\">Value to subtract</param>\r\n\t\tpublic void SubtractBurstPoints(int value) {\r\n\t\t\tburstPoints = (burstPoints - value > 0) ? burstPoints - value : 0;\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region MovementImplementation\r\n\t\t/// <summary>Implements dashing</summary>\r\n\t\tprivate void ImplementDashing() {\r\n\t\t\tif (dashArgs.Update()) return; // Still dashing\r\n\r\n\t\t\tvelocity = dashArgs.dashingVelocity;\r\n\t\t\tdashArgs = null; // Delete dash args\r\n\t\t}\r\n\r\n\t\t/// <summary>Makes player runi in desired direction</summary>\r\n\t\t/// <param name=\"runningLeft\">Direction player is running. False = runningRight</param>\r\n\t\tprivate void ImplementRunning(bool runningLeft) {\r\n\t\t\tif (velocity.X == 0) velocity.X = defaultRunningVelocity; // At start = default\r\n\r\n\t\t\tvelocity.X += Acceleration.X * elapsedTime; // Horizontal Velocity\r\n\t\t\tOffsetSpritePosition(X: (runningLeft ? -1 : 1) * XDisplacement);\r\n\r\n\t\t\tif (HasIntersectedTypes(new Vector2(0, -1), GV.MonoGameImplement.BlockTypes)) {\r\n\t\t\t\tIMonoGameObject[] collided = CompoundIntersects(GV.MonoGameImplement.BlockTypes); // All collided objects\r\n\r\n\t\t\t\tString[] intersectingLabels = GetIntersectedBoundaryLabels(collided, GV.MonoGameImplement.BlockTypes);\r\n\r\n\t\t\t\tbool leftIntersection = intersectingLabels.Contains(\"Left\"), rightIntersection = intersectingLabels.Contains(\"Right\");\r\n\t\t\t\tbool verticalIntersection = intersectingLabels.Contains(\"Top\") || intersectingLabels.Contains(\"Bottom\"); // Top || Bottom\r\n\r\n\t\t\t\tif (!(leftIntersection || rightIntersection) && verticalIntersection) {\r\n\t\t\t\t\tfloat cornerLeft = ((IBRectangle)TrueBoundary[\"Top\"]).Left, cornerRight = ((IBRectangle)TrueBoundary[\"Top\"]).Right;\r\n\r\n\t\t\t\t\tfloat furthestRight = (from X in collided select (X as ICollideable).Boundary.Container.Right).Aggregate(Math.Max);\r\n\t\t\t\t\tfloat furthestLeft = (from X in collided select (X as ICollideable).Boundary.Container.Left ).Aggregate(Math.Min);\r\n\r\n\t\t\t\t\tbool pastLeft = cornerLeft > furthestLeft, beforeRight = cornerRight < furthestRight;\r\n\r\n\t\t\t\t\tif (pastLeft && beforeRight) {\r\n\t\t\t\t\t\tbool fixRight = cornerLeft - furthestLeft > furthestRight - cornerRight; // Determines\r\n\t\t\t\t\t\t// Whether further into block on left or on right & chooses appropriate collision handler\r\n\t\t\t\t\t\tif (fixRight) HorizontalMovingRightBoundaryFix(); else HorizontalMovingLeftBoundaryFix();\r\n\t\t\t\t\t} else if (pastLeft) HorizontalMovingLeftBoundaryFix(); else if (beforeRight) HorizontalMovingRightBoundaryFix();\r\n\r\n\t\t\t\t} else if (leftIntersection) HorizontalMovingLeftBoundaryFix(); else if (rightIntersection) HorizontalMovingRightBoundaryFix();\r\n\r\n\t\t\t\tStopRunning(); // Reset forward or backward velocity\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void StopRunning() {\r\n\t\t\tvelocity.X = 0;\r\n\t\t}\r\n\r\n\t\tprivate void ImplementJumping() {\r\n\t\t\tif (!Falling(1, 0) && !Falling(-1, 0)) {\r\n\t\t\t\tvelocity.Y = defaultJumpVelocity; // Set players horizontal velocity\r\n\t\t\t\tOffsetSpritePosition(Y: YDisplacement); // Push sprites vertical position\r\n\t\t\t\tjumpButtonReleased = false; // Can't dash until jump button released\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void StopJumping() {\r\n\t\t\tjumpButtonReleased = true; // Released so if player enters again, dashing is enabled and player dashes in desired direction\r\n\t\t\tvelocity.Y = GV.Physics.GetEarlyJumpEndVelocity(velocity.Y, GV.MonoGameImplement.gravity, maxJumpHeight, minJumpHeight);\r\n\t\t}\r\n\r\n\t\tprotected override void StopFalling() {\r\n\t\t\tbase.StopFalling(); // Call child method\r\n\t\t\tjumpButtonReleased = false; // Prevent dash\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region ConditionalCalculators\r\n\t\tpublic bool CanDash() { return (Falling(-1, 0) || Falling(-1, 0)) && burstPoints >= GV.Variables.playerDashCost && !Dashing; }\r\n\r\n\t\tpublic bool CanJump() { return (!Falling(new Vector2(1, 0)) || !Falling(new Vector2(-1, 0))) && !jumpButtonReleased; }\r\n\r\n\t\tprivate bool CanGenerateBurstPoints() {\r\n\t\t\treturn (\r\n\t\t\t\t\tGV.PeripheralIO.currentControlState.GamepadNotPressed() &&\r\n\t\t\t\t\tGV.PeripheralIO.currentControlState.KeyboardNotPressed()\r\n\t\t\t\t)\r\n\r\n\t\t\t\t&& !Dashing && burstPoints != maxBurstPoints && !Falling(0, 1);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region IntersectionCheckers\r\n\t\tpublic static String[] GetIntersectedBoundaryLabels(Player self, IMonoGameObject[] objects, params Type[] types) {\r\n\t\t\tHashSet<String> intersected = new HashSet<String>(); // Holds intersected boundaries\r\n\r\n\t\t\tforeach (IMonoGameObject IMGO in objects) {\r\n\t\t\t\tif (!(IMGO is ICollideable) || (types.Length > 0 && !types.Contains(IMGO.GetType())))\r\n\t\t\t\t\tcontinue; // If isn't collideable or doesn't match argument types then continue\r\n\r\n\t\t\t\tintersected.UnionWith(self.TrueBoundary.GetIntersectingBoundaryLabels((IMGO as ICollideable).Boundary));\r\n\t\t\t}\r\n\r\n\t\t\treturn intersected.ToArray(); // Convert to array and return to sender\r\n\t\t}\r\n\r\n\t\tpublic override bool Falling() {\r\n\t\t\treturn base.Falling() && !GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Bottom\"); \r\n\t\t}\r\n\r\n\t\tpublic String[] GetIntersectedBoundaryLabels(params Type[] types) {\r\n\t\t\treturn GetIntersectedBoundaryLabels(this, GV.MonoGameImplement.monogameObjects.ToArray(), types);\r\n\t\t}\r\n\r\n\t\tpublic String[] GetIntersectedBoundaryLabels(IMonoGameObject[] objects, params Type[] types) {\r\n\t\t\treturn GetIntersectedBoundaryLabels(this, objects, types);\r\n\t\t}\r\n\r\n\t\tpublic String[] GetIntersectedBoundaryLabels(Vector2 offset, IMonoGameObject[] objects, params Type[] types) {\r\n\t\t\treturn CheckOffsetMethodCaller(offset, () => GetIntersectedBoundaryLabels(this, objects, types));\r\n\t\t}\r\n\r\n\t\tpublic String[] GetIntersectedBoundaryLabels(Vector2 offset, params Type[] types) {\r\n\t\t\treturn CheckOffsetMethodCaller(offset, () => GetIntersectedBoundaryLabels(types));\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region CollisionHandling\r\n\t\t#region CollisionHandlerDelegates\r\n\t\tprivate delegate bool ValidityCheck(IBoundaryContainer boundary, bool horizontalCollision, bool VerticalCollision);\r\n\r\n\t\tprivate delegate float FinalCalculator(bool horizontalCollision, bool verticalCollision, float newPosition);\r\n\t\t#endregion\r\n\r\n\t\tprotected override bool FixDownwardCollisionAfterFalling() {\r\n\t\t\treturn base.FixDownwardCollisionAfterFalling() && GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Bottom\");\r\n\t\t}\r\n\r\n\t\tprivate float? BoundaryFixSharedHandler(Direction direction, ValidityCheck checker, FinalCalculator calc, Vector2? _offset=null) {\r\n\t\t\tVector2 offset = (_offset.HasValue) ? _offset.Value : Vector2.Zero; // If has value set to it, otherwise set to empty\r\n\r\n\t\t\tString[] intersectedLabels = GetIntersectedBoundaryLabels(offset, GV.MonoGameImplement.BlockTypes); // Get All Labels \r\n\t\t\tif (intersectedLabels.Length == 0) return null; // No collision has occured, return to sender. Almost impossible but just in case :)\r\n\r\n\t\t\tbool horizontalCollision = intersectedLabels.Contains(\"Left\") || intersectedLabels.Contains(\"Right\"); // Whether left or right\r\n\t\t\tbool verticalCollision = intersectedLabels.Contains(\"Bottom\"); // Contains bottom collision, just in case !leftRight but Bottom\r\n\r\n\t\t\tIMonoGameObject[] collided = CompoundIntersects(GV.MonoGameImplement.BlockTypes);\r\n\r\n\t\t\tif (collided.Length > 1) collided = (from X in collided where checker((X as ICollideable).Boundary, // Use alternative ->\r\n\t\t\t\thorizontalCollision, verticalCollision) select X).ToArray(); // Overloaded method accounting for labelled in boundary type\r\n\r\n\t\t\tif (collided.Length == 0) return null; // No collision has occured, return to sender just in case :)\r\n\r\n\t\t\t// Console.WriteLine((from X in collided select X.SpriteID).Aggregate((a, b) => $\"{a}, {b}\"));\r\n\r\n\t\t\t#region RebuildVariablesWithTrimmedCollidedList\r\n\t\t\t// This region is used to eliminate the bug where player is falling right on the edge between two blocks & passes into it\r\n\t\t\tintersectedLabels = GetIntersectedBoundaryLabels(offset, collided, GV.MonoGameImplement.BlockTypes); // Rebuilds intersected labels\r\n\r\n\t\t\thorizontalCollision = intersectedLabels.Contains(\"Left\") || intersectedLabels.Contains(\"Right\"); // Whether left or right\r\n\t\t\tverticalCollision = intersectedLabels.Contains(\"Bottom\"); // Contains bottom collision, just in case !leftRight but Bottom\r\n\t\t\t#endregion // May be repetitive, but effectively erases quite the pesky bug, DO NOT DELETE!!!\r\n\r\n\t\t\tfloat? setValue = LoopGetPositionFromDirection(collided.Cast<ICollideable>().ToArray(), direction); // Find New Position\r\n\r\n\t\t\tif (setValue.HasValue) return calc(horizontalCollision, verticalCollision, setValue.Value); else return null; \r\n\t\t}\r\n\r\n\t\tprivate void VerticalBoundaryFixSharedHandler(Direction direction, float multiplier) {\r\n\t\t\tFinalCalculator calculator = (h, v, n) => n + (multiplier * (h ? leftRightBoundaryYOffset : 0));\r\n\t\t\tfloat? pos = BoundaryFixSharedHandler(direction, VerticalBoundaryFixValidityCheck, calculator);\r\n\t\t\tif (pos.HasValue) { SetPosition(Y: pos.Value); BuildBoundary(); }\r\n\t\t}\r\n\r\n\t\tprivate void HorizontalBoundaryFixSharedHandler(Direction direction, float multiplier) {\r\n\t\t\tFinalCalculator calculator = (h, v, n) => n + (multiplier * (v /*&& !h*/ ? leftRightBoundaryXOffset - 2 : 0));\r\n\t\t\tfloat? pos = BoundaryFixSharedHandler(direction, HorizontalBoundaryFixValidityCheck, calculator, new Vector2(0, 0));\r\n\t\t\tif (pos.HasValue) { SetPosition(X: pos.Value); BuildBoundary(); } // Set position and rebuild boundary for player now\r\n\t\t\t// Remark // Boundary rebuilt because of Weird rounding bug where value is off by 0.00004. For now do this, fix later.\r\n\t\t}\r\n\r\n\t\tprotected override void VerticalDownwardBoundaryFix() { VerticalBoundaryFixSharedHandler(Direction.Top, +1); }\r\n\r\n\t\tprivate void VerticalUpwardBoundaryFix() { VerticalBoundaryFixSharedHandler(Direction.Bottom, -1); OffsetSpritePosition(0, 1); }\r\n\r\n\t\tprivate void HorizontalMovingLeftBoundaryFix() { HorizontalBoundaryFixSharedHandler(Direction.Right, -1); }\r\n\r\n\t\tprivate void HorizontalMovingRightBoundaryFix() { HorizontalBoundaryFixSharedHandler(Direction.Left, +1); }\r\n\r\n\t\tprivate bool VerticalBoundaryFixValidityCheck(IBoundaryContainer container, bool horizontal, bool vertical) {\r\n\t\t\tif (!horizontal && !vertical) return false; else /*(leftRight || bottom)*/ {\r\n\t\t\t\t// A = leftSpriteRect, B = rightSpriteRect, C = bottomSpriteRect, D = containerSpriteRect\r\n\t\t\t\tRectangle A = TrueBoundary[\"Left\"].Container, B = TrueBoundary[\"Right\"].Container;\r\n\t\t\t\tRectangle C = TrueBoundary[\"Bottom\"].Container, D = container.SpriteRect; // Get rects\r\n\r\n\t\t\t\tFunc<Rectangle, bool> finder = (R) => R.X >= D.X - R.Width && R.X + R.Width <= D.X + D.Width;\r\n\r\n\t\t\t\tbool bottomValid = finder(C); // Vertical valid, Top isn't really relevent here\r\n\t\t\t\tbool horizontalValid = finder(A) && finder(B); // F(A) = LeftValid, F(B) = RightValid\r\n\r\n\t\t\t\treturn ( horizontal && vertical && bottomValid && horizontalValid) // Bottom & Top Check \r\n\t\t\t\t\t|| (!horizontal && vertical && bottomValid && true ) // Bottom Check\r\n\t\t\t\t\t|| ( horizontal && !vertical && true && horizontalValid); // Top Check\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate bool HorizontalBoundaryFixValidityCheck(IBoundaryContainer container, bool horizontal, bool vertical) {\r\n\t\t\tif (!horizontal && !vertical) return false; else /*(leftRight || bottom)*/ {\r\n\t\t\t\t// A = TopSpriteRect, B = BottomSpriteRect, C = Left/RightSpriteRect, D = containerSpriteRect\r\n\t\t\t\tRectangle A = TrueBoundary[\"Top\"].Container, B = TrueBoundary[\"Bottom\"].Container;\r\n\t\t\t\tRectangle C = TrueBoundary[\"Left\"].Container, D = container.SpriteRect; // Get rects\r\n\t\t\t\t// S.N. Used left for left & right, because they share same Y-Value which're all needed\r\n\r\n\t\t\t\tFunc<Rectangle, bool> finder = (R) => D.Y + D.Height >= R.Y + R.Height && D.Y - R.Height < R.Y;\r\n\r\n\t\t\t\treturn finder(C) || finder(B) || finder(A); // F(C) = HorizontalValid, F(B) || F(A) = VerticalValid\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Perks\r\n\t\tpublic void ImplementPerks(params PlayerPerks[] _perks) {\r\n\t\t\tforeach (PlayerPerks perk in _perks) {\r\n\t\t\t\tswitch (perk) {\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t\tperks.Add(perk);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void RemovePerk(PlayerPerks perk) {\r\n\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tpublic override void OffsetSpritePosition(Vector2 XY) {\r\n\t\t\tbase.OffsetSpritePosition(XY); // Takes care of sprite push\r\n\r\n\t\t\tif (!CurrentWeapon.Thrown) CurrentWeapon.OffsetSpritePosition(XY);\r\n\t\t}\r\n\r\n\t\tpublic override void SetPosition(Vector2 nPos) {\r\n\t\t\tbase.SetPosition(nPos); // Sets position for sprite\r\n\r\n\t\t\tif (!CurrentWeapon.Thrown) CurrentWeapon.OffsetSpritePosition(nPos - Position);\r\n\t\t}\r\n\r\n\t\t#region Weapons\r\n\t\tprivate void Equip(Weapon weapon) {\r\n\t\t\tCurrentWeapon = weapon; // In case weapon was not equipped\r\n\t\t\tCurrentWeapon.Reset(this);\r\n\t\t}\r\n\r\n\t\tpublic float GetAnglePointedToByInput() {\r\n\t\t\tif (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.ThumbSticks.Right != Vector2.Zero) {\r\n\t\t\t\tVector2 rightThumbstick = GV.PeripheralIO.currentGPState.ThumbSticks.Right;\r\n\t\t\t\treturn (float)Math.Atan2(-rightThumbstick.Y, rightThumbstick.X); // Get angle\r\n\t\t\t} else { // Determine from regular input\r\n\t\t\t\tvar _default = FacingLeft ? DashArgs.DashingDirection.Left : DashArgs.DashingDirection.Right;\r\n\r\n\t\t\t\tDashArgs.DashingDirection direction = DashArgs.GetDashingDirection(_default); // Get direction\r\n\r\n\t\t\t\treturn GV.BasicMath.DegreesToRadians(45 * (int)direction); // Cast type to int and return to caller\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void ThrowWeapon() { if (CurrentWeapon.CanThrow) CurrentWeapon.Throw(GetAnglePointedToByInput()); }\r\n\r\n\t\tprivate void AttackWeapon() { if (CurrentWeapon.CanAttack) CurrentWeapon.Attack(this); }\r\n\r\n\t\tprivate void CallThrownWeaponBack() { if (CurrentWeapon.CanCallThrownWeaponBack) CurrentWeapon.ReturnThrownWeaponToPlayer(); }\r\n\r\n\t\tprivate void SwitchToNextWeapon() {\r\n\t\t\tint currentIndex = Array.IndexOf(weapons, CurrentWeapon); // Current Weapon\r\n\t\t\tEquip(weapons[(currentIndex + 1 < weapons.Length) ? currentIndex + 1 : 0]);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Animation\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"idleLeft\"] = AnimationSequence.FromRange(32, 32, 0, 0, 1, 32, 32);\r\n\t\t\tAnimation[\"idleRight\"] = AnimationSequence.FromRange(32, 32, 0, 1, 1, 32, 32);\r\n\t\t\tAnimation[\"runningLeft\"] = AnimationSequence.FromRange(32, 32, 0, 0, 3, 32, 32);\r\n\t\t\tAnimation[\"runningRight\"] = AnimationSequence.FromRange(32, 32, 0, 1, 3, 32, 32);\r\n\t\t\tAnimation[\"idleUpLeft\"] = AnimationSequence.FromRange(32, 32, 3, 0, 1, 32, 32);\r\n\t\t\tAnimation[\"idleUpRight\"] = AnimationSequence.FromRange(32, 32, 3, 1, 1, 32, 32);\r\n\t\t\t\r\n\t\t\tSequenceKey = \"idleRight\"; // Default sequence is player looking to the right\r\n\t\t}\r\n\r\n\t\t/// <summary>Get rid of running animation</summary>\r\n\t\tpublic void StallAnimation() {\r\n\t\t\tString lastLookingDirection = (Animation.sequenceKey.Contains(\"Left\")) ? \"Left\" : \"Right\";\r\n\t\t\tAnimation.SetAnimationSequence($\"idle{lastLookingDirection}\"); // Pointing but stationary\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\t#region SizeCalculations/Definitions\r\n\t\t\tint leftRightWidth = (SpriteRect.Width / 2) - leftRightBoundaryXOffset; // Left Right Boundary Width\r\n\t\t\tint leftRightHeight = SpriteRect.Height - (2 * leftRightBoundaryYOffset); // Left Right Boundary Height\r\n\r\n\t\t\tint topBottomHeight = (SpriteRect.Height - topBottomYOffset) / 2; // Top Bottom Boundary Height\r\n\t\t\tint topBottomWidth = SpriteRect.Width - (2 * topBottomXOffset); // Top Bottom Boundary Width\r\n\r\n\t\t\tVector2 leftRightSize = new Vector2(leftRightWidth, leftRightHeight);\r\n\t\t\tVector2 topBottomSize = new Vector2(topBottomWidth, topBottomHeight);\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region PositionCalculations/Definitions\r\n\t\t\tVector2 leftPos = new Vector2(SpriteRect.X + leftRightBoundaryXOffset, SpriteRect.Y + leftRightBoundaryYOffset);\r\n\t\t\tVector2 topPos = new Vector2(SpriteRect.X + topBottomXOffset, SpriteRect.Y + topBottomYOffset );\r\n\r\n\t\t\tVector2 rightPos = new Vector2(SpriteRect.X + leftRightBoundaryXOffset + leftRightWidth, SpriteRect.Y + leftRightBoundaryYOffset);\r\n\t\t\tVector2 bottomPos = new Vector2(SpriteRect.X + topBottomXOffset, SpriteRect.Y + topBottomYOffset + topBottomHeight);\r\n\t\t\t#endregion\r\n\r\n\t\t\tboundary = new LabelledBoundaryContainer(SpriteRect) {\r\n\t\t\t\t{ \"Left\", new IBRectangle(leftPos, leftPos + leftRightSize) },\r\n\t\t\t\t{ \"Right\", new IBRectangle(rightPos, rightPos + leftRightSize) },\r\n\t\t\t\t{ \"Top\", new IBRectangle(topPos, topPos + topBottomSize) },\r\n\t\t\t\t{ \"Bottom\", new IBRectangle(bottomPos, bottomPos + topBottomSize) }\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t#region ClassElements\r\n\t\t/// <summary>Variables used to build player boundary rectangles in TrueBoundary/LabelledBoundaryContainer</summary>\r\n\t\tprivate const int leftRightBoundaryXOffset = 6, leftRightBoundaryYOffset = 10, topBottomXOffset = 10, topBottomYOffset = 2;\r\n\r\n\t\t/// <summary>Maximum height player can jump, min height player should jump</summary>\r\n\t\tprivate static int maxJumpHeight = 64, minJumpHeight = 15;\r\n\r\n\t\t/// <summary>Default velocity when player jumping & when player running</summary>\r\n\t\tprivate static float defaultJumpVelocity, defaultRunningVelocity = 50 * 1f;\r\n\r\n\t\t/// <summary>Maximum value velocity can reach in either direction</summary>\r\n\t\tpublic override Vector2 TerminalVelocity { get; protected set; } = new Vector2(125, 125);\r\n\r\n\t\t/// <summary>Default acceleration when running and falling (not including gravity)</summary>\r\n\t\tpublic override Vector2 Acceleration { get; protected set; } = new Vector2(50, 0);\r\n\r\n\t\t/// <summary>Boundary casted to actual type, nicer when accessing player exclusive keys</summary>\r\n\t\tpublic LabelledBoundaryContainer TrueBoundary { get { return (LabelledBoundaryContainer)boundary; } }\r\n\r\n\t\t/// <summary>Value points used to determine player dashing capabilities</summary>\r\n\t\tpublic int burstPoints = maxBurstPoints;\r\n\r\n\t\t/// <summary>Assists in generation of burst points by standing still</summary>\r\n\t\tprivate float generatingBurstPoints, pointGenerationRate = DEFAULT_POINT_GENERATION_RATE, pointGenerationAcceleration=0.2f;\r\n\r\n\t\tprivate const float DEFAULT_POINT_GENERATION_RATE = 1f;\r\n\r\n\t\t/// <summary>Time spent where player is not moving</summary>\r\n\t\tpublic float timeNotMoving = 0;\r\n\r\n\t\tpublic static readonly int TIME_BEFORE_POINT_GEN = 4;\r\n\r\n\t\t/// <summary>Maximum amount of burst points player is allowed to have </summary>\r\n\t\tpublic static int maxBurstPoints = 25;\r\n\r\n\t\t/// <summary>Arguments used for dashing. When null, not dashing.</summary>\r\n\t\tprivate DashArgs dashArgs;\r\n\r\n\t\t/// <summary>Whether player has released jump button</summary>\r\n\t\tprivate bool jumpButtonReleased;\r\n\r\n\t\tpublic int interaction_timeout = 0;\r\n\r\n\t\tprivate bool thrownButtonReleased = false;\r\n\r\n\t\tpublic bool FacingLeft { get { return Animation.sequenceKey.Contains(\"Left\"); } }\r\n\r\n\t\tpublic bool FacingRight { get { return !FacingLeft; } }\r\n\r\n\t\tprivate List<PlayerPerks> perks = new List<PlayerPerks>();\r\n\r\n\t\tpublic Weapons.Sword sword;\r\n\r\n\t\tpublic Weapons.Shuriken shuriken;\r\n\r\n\t\tprivate Weapon[] weapons;\r\n\r\n\t\tprivate int weaponSwitchTimeout = 0;\r\n\r\n\t\tpublic Weapon CurrentWeapon { get; private set; }\r\n\r\n\t\tprivate int timeInvincible = 0;\r\n\r\n\t\tpublic PlayerPerks[] Perks { get { return perks.ToArray(); } }\r\n\r\n\t\t/// <summary>Whether player is cucrrently dashing</summary>\r\n\t\tprivate bool Dashing { get { return dashArgs != null; } }\r\n\t\t#endregion\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7006941437721252, "alphanum_fraction": 0.7011024951934814, "avg_line_length": 27.865854263305664, "blob_id": "90876b38d9eccb920a165a069380701bbf465673", "content_id": "9e4be2d98f16ed2b71686c35d7d898b2204b6d72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2451, "license_type": "no_license", "max_line_length": 102, "num_lines": 82, "path": "/HollowAether/Lib/Global/GlobalVars/MapZone.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class MapZone {\r\n\t\t\tpublic static Asset GetAsset(String ID, AssetContainer localAssets) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tif (globalAssets.ContainsKey(ID)) return globalAssets[ID];\r\n\r\n\t\t\t\t\tif (localAssets.ContainsKey(ID)) return localAssets[ID];\r\n\r\n\t\t\t\t\tthrow new HollowAetherException($\"Asset '{ID}' Not In Local Or Global Store\");\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Could Not Find Asset '{ID}' Value\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static IEnumerable<FlagAsset> GetFlagAssets() {\r\n\t\t\t\tforeach (Asset asset in globalAssets.Values) {\r\n\t\t\t\t\tif (asset is FlagAsset) yield return (asset as FlagAsset);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static FlagAsset GetFlagAsset(String assetID) {\r\n\t\t\t\tforeach (FlagAsset asset in GetFlagAssets()) {\r\n\t\t\t\t\tif (asset.assetID == assetID) return asset;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthrow new HollowAetherException($\"Flag '{assetID}' Not Found\");\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool FlagExists(String assetID) {\r\n\t\t\t\tforeach (FlagAsset flag in GetFlagAssets()) {\r\n\t\t\t\t\tif (flag.assetID == assetID) return true;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn false; // Not in flags\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void ClearFlags() {\r\n\t\t\t\tString[] flagAssets = new String[globalAssets.Count];\r\n\t\t\t\tint counter = 0; // Counter to decide when to store\r\n\r\n\t\t\t\tforeach (KeyValuePair<String, Asset> asset in globalAssets) {\r\n\t\t\t\t\tif (asset.Value.TypesMatch<Flag>()) { flagAssets[counter++] = asset.Key; }\r\n\t\t\t\t}\r\n\r\n\t\t\t\tforeach (String key in flagAssets) {\r\n\t\t\t\t\tif (key != null) globalAssets.Remove(key);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Dictionary<String, GameEntity> GlobalEntities = new Dictionary<String, GameEntity>();\r\n\t\t\tpublic static AssetContainer globalAssets;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7132172584533691, "alphanum_fraction": 0.7146532535552979, "avg_line_length": 34.97566223144531, "blob_id": "94477c535403eae4f777dcb9578bb65c224e5ad6", "content_id": "0cf6b2e02268ada529b22c39e464b8cac9d640cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16715, "license_type": "no_license", "max_line_length": 168, "num_lines": 452, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Classes/CanvasRegionBox.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Drawing.Drawing2D;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class CanvasRegionBox : PictureBox {\r\n\t\t#region Class & Enum Definitions\r\n\t\tpublic enum SelectType { Drag, GridClick, GridDrag, GridHighlight, Custom }\r\n\r\n\t\tpublic class SelectionRectBuildersEventArgs {\r\n\t\t\tpublic SelectionRectBuildersEventArgs(PointF current, SizeF gridSize) {\r\n\t\t\t\tCurrentPoint = current;\r\n\t\t\t\tGridSize = gridSize;\r\n\r\n\t\t\t\tCurrentGridPoint = new PointF() {\r\n\t\t\t\t\tX = GV.BasicMath.RoundDownToNearestMultiple(current.X, gridSize.Width, false),\r\n\t\t\t\t\tY = GV.BasicMath.RoundDownToNearestMultiple(current.Y, gridSize.Height, false)\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic SelectionRectBuildersEventArgs(PointF current, SizeF gridSize, RectangleF selectionRect) : this(current, gridSize) {\r\n\t\t\t\tcurrentRectangle = selectionRect;\r\n\t\t\t}\r\n\r\n\t\t\tpublic PointF GetOriginalPointBasedOnUseGrid() {\r\n\t\t\t\treturn (UseGrid) ? OriginalGridPoint : OriginalPoint;\r\n\t\t\t}\r\n\r\n\t\t\tpublic PointF GetCurrentPointBasedOnUseGrid() {\r\n\t\t\t\treturn (UseGrid) ? CurrentGridPoint : CurrentPoint;\r\n\t\t\t}\r\n\r\n\t\t\tpublic PointF CurrentGridPoint { get; private set; }\r\n\r\n\t\t\tpublic PointF CurrentPoint { get; private set; }\r\n\r\n\t\t\tpublic PointF OriginalGridPoint { get; set;}\r\n\r\n\t\t\tpublic PointF OriginalPoint { get; set; }\r\n\r\n\t\t\tpublic SizeF GridSize { get; private set; }\r\n\r\n\t\t\tpublic bool UseGrid { get; set; }\r\n\r\n\t\t\tpublic bool MousePressed { get; set; }\r\n\r\n\t\t\tpublic Rectangle CanvasDimensions { get; set; }\r\n\r\n\t\t\tpublic RectangleF currentRectangle = RectangleF.Empty;\r\n\t\t};\r\n\t\t#endregion\r\n\r\n\t\tpublic CanvasRegionBox() {\r\n\t\t\tPaint += (s, e) => { // Set Graphic Vars For Drawing\r\n\t\t\t\te.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;\r\n\t\t\t\te.Graphics.ScaleTransform(ZoomX, ZoomY); /*Implement Zoom X & Y*/\r\n\t\t\t};\r\n\r\n\t\t\tSizeMode = PictureBoxSizeMode.AutoSize;\r\n\r\n\t\t\t#region PaintEventHandlers\r\n\t\t\tPaint += (s, e) => { DrawToCanvas(s, e); };\r\n\t\t\tPaint += DrawGrid_PaintEventHandler;\r\n\t\t\tPaint += DrawBorder_PaintEventHandler;\r\n\t\t\tPaint += DrawCursor_PaintEventHandler;\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region MouseEventHandlers\r\n\t\t\tMouseDown += MouseDown_MouseBasedEventHandler;\r\n\t\t\tMouseUp += MouseUp_MouseBasedEventHandler;\r\n\t\t\tMouseMove += MouseMove_MouseBasedEventHandler;\r\n\t\t\tMouseLeave += MouseLeave_MouseBasedEventHandler;\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region BuildSelectionRectEventHandlers\r\n\t\t\tBuildSelectionRect += DragableSelectionRectBuildEventHandler;\r\n\t\t\tBuildSelectionRect += GridClickSelectionRectBuildEventHandler;\r\n\t\t\tBuildSelectionRect += HighlightSelectionRectBuilder;\r\n\t\t\t#endregion\r\n\r\n\t\t\tCanvasRegionExecute += CanvasRegionBox_CanvasRegionExecute;\r\n\r\n\t\t\tClickComplete += ClickComplete_MouseBasedEventHandler;\r\n\t\t}\r\n\r\n\t\tprivate void CanvasRegionBox_CanvasRegionExecute(SelectType arg1, RectangleF arg2, RectangleF[] arg3) {\r\n\t\t\thighlightedSelectRects.Clear();\r\n\t\t}\r\n\r\n\t\t~CanvasRegionBox() {\r\n\t\t\tgridPen.Dispose();\r\n\t\t\tcursorPen.Dispose();\r\n\t\t\tborderPen.Dispose();\r\n\t\t}\r\n\r\n\t\tpublic void Draw() { Refresh(); /*Invalidates & Updates*/ }\r\n\r\n\t\tpublic void ChangeSelectType(SelectType newType) {\r\n\t\t\tif (newType != selectOption) {\r\n\t\t\t\tselectOption = newType;\r\n\t\t\t\tmousePressed = false;\r\n\t\t\t\tclickPoint = gridClickPoint = PointF.Empty;\r\n\t\t\t\tSelectRect = RectangleF.Empty;\r\n\t\t\t\thighlightedSelectRects.Clear();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region EventHandlers\r\n\r\n\t\t#region SelectionRectBuilderEventHandlers\r\n\r\n\t\t#region ActualBuilders\r\n\t\tpublic static RectangleF ClickSelectionRectBuilder(PointF point, SizeF gridSize) {\r\n\t\t\treturn new RectangleF(point, gridSize); // Display Single Grid Square\r\n\t\t}\r\n\r\n\t\tpublic static RectangleF DragableSelectionRectBuilder(bool useGrid, SizeF gridSize, PointF newPosition, PointF originalPosition) {\r\n\t\t\tSizeF displacement = new SizeF(newPosition.X - originalPosition.X, newPosition.Y - originalPosition.Y);\r\n\t\t\tPointF point = originalPosition; // Store Original Point From Which Rectangle will eventually portrude\r\n\r\n\t\t\tif (newPosition == originalPosition) displacement = (useGrid) ? gridSize : displacement; else {\r\n\t\t\t\tbool forwardXRegion = displacement.Width >= 0, forwardYRegion = displacement.Height >= 0; // Regions\r\n\t\t\t\tdisplacement = new SizeF(Math.Abs(displacement.Width), Math.Abs(displacement.Height)); // Make +ve\r\n\r\n\t\t\t\tif (!forwardXRegion) point.X -= displacement.Width; if (!forwardYRegion) point.Y -= displacement.Height;\r\n\r\n\t\t\t\tif (forwardXRegion || forwardYRegion) displacement += (useGrid ? gridSize : SizeF.Empty); else if (useGrid) {\r\n\t\t\t\t\tif (!forwardXRegion) displacement.Width += gridSize.Width; if (!forwardYRegion) displacement.Height += gridSize.Height;\r\n\t\t\t\t\t// If backwards & uses grid, include clicked grid square, either on the horizontal or vertical axes of square\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn new RectangleF(point, displacement); // Calculate and return appropriate rectangle\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region BuilderCallers/ActualEventHandlers\r\n\t\tpublic static void HighlightSelectionRectBuilder(SelectType type, SelectionRectBuildersEventArgs e) {\r\n\t\t\tif (type == SelectType.GridHighlight) e.currentRectangle = new RectangleF(e.CurrentGridPoint, e.GridSize);\r\n\t\t}\r\n\r\n\t\tpublic void DragableSelectionRectBuildEventHandler(SelectType type, SelectionRectBuildersEventArgs e) {\r\n\t\t\tPointF currentPoint = e.GetCurrentPointBasedOnUseGrid(), originalPoint = e.GetOriginalPointBasedOnUseGrid();\r\n\r\n\t\t\tif (mousePressed && (type == SelectType.GridDrag || type == SelectType.Drag)) {\r\n\t\t\t\tRectangleF rect = DragableSelectionRectBuilder(e.UseGrid, e.GridSize, currentPoint, originalPoint);\r\n\t\t\t\te.currentRectangle = RectangleF.Intersect(rect, e.CanvasDimensions); // Get Clamped Rectangle\r\n\t\t\t} /*else if (type == SelectType.GridDrag && e.currentRectangle == RectangleF.Empty) {\r\n\t\t\t\te.currentRectangle = ClickSelectionRectBuilder(currentPoint, e.GridSize);\r\n\t\t\t}*/\r\n\t\t}\r\n\r\n\t\tpublic static void GridClickSelectionRectBuildEventHandler(SelectType type, SelectionRectBuildersEventArgs e) {\r\n\t\t\tif (type == SelectType.GridClick) e.currentRectangle = new RectangleF(e.CurrentGridPoint, e.GridSize);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\t#region MouseBasedEventHandlers\r\n\r\n\t\t#region AssistanceMethods\r\n\r\n\t\t#region ConditionVars\r\n\t\tprivate bool UseGridForSelection() { return SelectOption == SelectType.GridClick || SelectOption == SelectType.GridDrag || SelectOption == SelectType.GridHighlight; }\r\n\r\n\t\tprivate bool IsSelectTypeDragable() { return SelectOption == SelectType.Drag || SelectOption == SelectType.GridDrag; }\r\n\t\t#endregion\r\n\r\n\t\tprivate PointF TranslateLocationToZoomedLocation(PointF point) {\r\n\t\t\treturn new PointF(point.X / ZoomX, point.Y / ZoomY);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region MouseDown, MouseMove & MouseUp\r\n\t\tprivate void MouseDown_MouseBasedEventHandler(object sender, MouseEventArgs e) {\r\n\t\t\tif (AllowHighlighting && !mousePressed) {\r\n\t\t\t\tmousePressed = true; // Set mouse state to has been pressed\r\n\r\n\t\t\t\tclickPoint = TranslateLocationToZoomedLocation(e.Location);\r\n\r\n\t\t\t\tgridClickPoint = new PointF() {\r\n\t\t\t\t\tX = GV.BasicMath.RoundDownToNearestMultiple(clickPoint.X, gridSize.Width, false),\r\n\t\t\t\t\tY = GV.BasicMath.RoundDownToNearestMultiple(clickPoint.Y, gridSize.Height, false)\r\n\t\t\t\t};\r\n\r\n\t\t\t\tClickBegun(SelectOption, clickPoint, gridClickPoint, e.Button);\r\n\r\n\t\t\t\tSelectRect = InvokeBuildSelectionRect(clickPoint, clickPoint, gridClickPoint);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void MouseMove_MouseBasedEventHandler(object sender, MouseEventArgs e) {\r\n\t\t\tif (AllowHighlighting) {\r\n\t\t\t\tPointF original = (mousePressed) ? clickPoint : e.Location;\r\n\r\n\t\t\t\tPointF location = TranslateLocationToZoomedLocation(e.Location);\r\n\r\n\t\t\t\tSelectRect = InvokeBuildSelectionRect(location, original, gridClickPoint);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void MouseUp_MouseBasedEventHandler(object sender, MouseEventArgs e) {\r\n\t\t\tif (AllowHighlighting && mousePressed) {\r\n\t\t\t\tmousePressed = false; // Click has been completed, return to caller\r\n\t\t\t\tclickPoint = gridClickPoint = PointF.Empty;\r\n\r\n\t\t\t\tif (selectOption != SelectType.GridHighlight) {\r\n\t\t\t\t\tCanvasRegionExecute(SelectOption, SelectRect, null);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tClickComplete(selectOption, SelectRect); // Execute event handler\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate void MouseLeave_MouseBasedEventHandler(object sender, EventArgs e) {\r\n\t\t\tif (AllowHighlighting && !(/*mousePressed && */IsSelectTypeDragable())) {\r\n\t\t\t\tSelectRect = RectangleF.Empty; // Delete Rect When Exiting Canvas\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void ClickComplete_MouseBasedEventHandler(SelectType type, RectangleF rect) {\r\n\t\t\tif (type == SelectType.GridHighlight) highlightedSelectRects.Add(rect); // If Highligted then store\r\n\r\n\t\t\tif ((dragableSelectionRectsAreVolatile && IsSelectTypeDragable())) {\r\n\t\t\t\tDeselect(); // Deselect selected rectangle region and any highlited rectangle regions after click\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region DrawEventHandlers\r\n\r\n\t\t#region AssistantMethods\r\n\t\tprivate IEnumerable<float> GetMultiplesInRange(int span, float increment) {\r\n\t\t\tforeach (int X in Enumerable.Range(0, span)) {\r\n\t\t\t\tyield return increment * X; // Generate\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void DrawRectangleF(Graphics graphics, Pen pen, RectangleF rect) {\r\n\t\t\tgraphics.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate void DrawBorder_PaintEventHandler(object sender, PaintEventArgs e) {\r\n\t\t\tif (drawBorder) { // If draw border has been set to true, Draw the border\r\n\t\t\t\te.Graphics.DrawRectangle(borderPen, new Rectangle(Point.Empty, InitialSize));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void DrawGrid_PaintEventHandler(object sender, PaintEventArgs e) {\r\n\t\t\tif (drawGrid) { // If grid is supposed to be drawn\r\n\t\t\t\tint horizontalSpan = (int)Math.Ceiling(initialWidth / GridWidth);\r\n\t\t\t\tint verticalSpan = (int)Math.Ceiling(initialHeight / GridHeight);\r\n\r\n\t\t\t\t#region DrawLinesEncompassingDrawRegion\r\n\t\t\t\tforeach (float increment in GetMultiplesInRange(horizontalSpan, GridWidth)) {\r\n\t\t\t\t\te.Graphics.DrawLine(gridPen, increment, 0, increment, initialHeight);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tforeach (float increment in GetMultiplesInRange(verticalSpan, GridHeight)) {\r\n\t\t\t\t\te.Graphics.DrawLine(gridPen, 0, increment, initialWidth, increment);\r\n\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void DrawCursor_PaintEventHandler(object sender, PaintEventArgs e) {\r\n\t\t\tif (AllowHighlighting) {\r\n\t\t\t\tDrawRectangleF(e.Graphics, cursorPen, SelectRect);\r\n\r\n\t\t\t\tif (selectOption == SelectType.GridHighlight) {\r\n\t\t\t\t\tforeach (RectangleF rect in highlightedSelectRects)\r\n\t\t\t\t\t\tDrawRectangleF(e.Graphics, cursorPen, rect);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\t\t\r\n\t\t#region Set&Deselect Methods\r\n\t\tpublic void SetWidth(int width) {\r\n\t\t\tbase.Width = initialWidth = width;\r\n\t\t\tbase.Width = (int)Math.Ceiling(ZoomX * Width);\r\n\r\n\t\t\tDraw(); // Re invoke the draw event for the canvas\r\n\t\t}\r\n\r\n\t\tpublic void SetHeight(int height) {\r\n\t\t\tbase.Height = initialHeight = height;\r\n\t\t\tbase.Width = (int)Math.Ceiling(ZoomX * Width);\r\n\r\n\t\t\tDraw(); // Re invoke the draw event for the canvas\r\n\t\t}\r\n\r\n\t\tpublic void SetZoom(SizeF size) {\r\n\t\t\tzoom = size; // New Zoom Equivalent To The Argument\r\n\r\n\t\t\tSize = new Size(\r\n\t\t\t\t(int)Math.Ceiling(InitialSize.Width * size.Width),\r\n\t\t\t\t(int)Math.Ceiling(InitialSize.Height * size.Height)\r\n\t\t\t);\r\n\r\n\t\t\tDraw(); // Re draw Canvas With Adjusted Size \r\n\t\t}\r\n\r\n\t\tprivate void SetSelectionRect(RectangleF rect) {\r\n\t\t\tif (rect != SelectRect) { selectRect = rect; Draw(); }\r\n\t\t}\r\n\r\n\t\tpublic void ExternalSetSelectionRect(RectangleF rect) {\r\n\t\t\tSetSelectionRect(rect);\r\n\t\t}\r\n\r\n\t\tpublic void Deselect() {\r\n\t\t\thighlightedSelectRects.Clear();\r\n\r\n\t\t\tselectRect = RectangleF.Empty;\r\n\t\t\tmousePressed = false;\r\n\r\n\t\t\tDraw(); // Redraw canvas\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Events And Handlers\r\n\t\tpublic RectangleF InvokeBuildSelectionRect(PointF current, PointF original, PointF gridOriginal) {\r\n\t\t\tSelectionRectBuildersEventArgs args = new SelectionRectBuildersEventArgs(current, GridSize, SelectRect) {\r\n\t\t\t\tMousePressed\t = mousePressed,\r\n\t\t\t\tOriginalPoint\t = original,\r\n\t\t\t\tOriginalGridPoint = gridOriginal,\r\n\t\t\t\tUseGrid\t\t\t = UseGridForSelection(),\r\n\t\t\t\tCanvasDimensions = new Rectangle(Point.Empty, InitialSize)\r\n\t\t\t};\r\n\r\n\t\t\tBuildSelectionRect(SelectOption, args); // Execute/invoke event handler for building selection rect\r\n\r\n\t\t\treturn args.currentRectangle; // Return remaining rectangle value after execution of event handlers\r\n\t\t}\r\n\r\n\t\tpublic void InvokeCanvasRegionExecuteForHighlitedSelectionRects() {\r\n\t\t\tif (SelectOption == SelectType.GridHighlight) {\r\n\t\t\t\tCanvasRegionExecute(SelectOption, RectangleF.Empty, highlightedSelectRects.ToArray());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Extension event to allow drawing to canvas outside of class</summary>\r\n\t\tpublic event PaintEventHandler DrawToCanvas = (s, e) => { };\r\n\r\n\t\t/// <summary>Event called when single click/drag/highlight is completed</summary>\r\n\t\tpublic event Action<SelectType, RectangleF, RectangleF[]> CanvasRegionExecute;\r\n\r\n\t\t/// <summary>Delegate For Building Selection Rects During Mouse Movement Within Canvas</summary>\r\n\t\t/// <param name=\"type\">The selection type that the zonecanvas is currently using</param>\r\n\t\t/// <param name=\"e\">Event args including relevent canvas data for building selection rects</param>\r\n\t\tpublic delegate void SelectionRectBuilders(SelectType type, SelectionRectBuildersEventArgs e);\r\n\r\n\t\t/// <summary>Event to build a selection rectangle for the canvas region</summary>\r\n\t\tpublic event SelectionRectBuilders BuildSelectionRect = (t, e) => { };\r\n\r\n\t\t/// <summary>Event called when a single click is completed</summary>\r\n\t\tpublic event Action<SelectType, RectangleF> ClickComplete = (t, r) => { };\r\n\r\n\t\t/// <summary>Event called when a click is started by the program</summary>\r\n\t\tpublic event Action<SelectType, PointF, PointF, MouseButtons> ClickBegun = (t, p, gp, b) => { };\r\n\t\t#endregion\r\n\r\n\t\t#region ZoomVars\r\n\t\tprivate SizeF zoom = new SizeF(1, 1);\r\n\r\n\t\tpublic SizeF Zoom { get { return zoom; } set { SetZoom(value); } }\r\n\r\n\t\tpublic float ZoomX { get { return zoom.Width; } set { Zoom = new SizeF(value, zoom.Height); } }\r\n\r\n\t\tpublic float ZoomY { get { return zoom.Height; } set { Zoom = new SizeF(zoom.Width, value); } }\r\n\t\t#endregion\r\n\r\n\t\t#region Pen&ColorVars\r\n\t\tprivate Pen gridPen = new Pen(Color.Gray, 0.25f);\r\n\t\tprivate Pen cursorPen = new Pen(Color.HotPink, 1.00f);\r\n\t\tprivate Pen borderPen = new Pen(Color.HotPink, 2.00f);\r\n\r\n\t\tpublic Color GridColor { get { return gridPen.Color; } set { gridPen.Color = value; } }\r\n\r\n\t\tpublic Color CursorColor { get { return cursorPen.Color; } set { cursorPen.Color = value; } }\r\n\r\n\t\tpublic Color BorderColor { get { return borderPen.Color; } set { borderPen.Color = value; } }\r\n\t\t#endregion\r\n\r\n\t\t#region SizeVars\r\n\t\tprivate int initialWidth, initialHeight;\r\n\r\n\t\tpublic Size InitialSize { get { return new Size(initialWidth, initialHeight); } }\r\n\r\n\t\tpublic new int Width { get { return base.Width; } set { SetWidth(value); } }\r\n\r\n\t\tpublic new int Height { get { return base.Height; } set { SetHeight(value); } }\r\n\t\t#endregion\r\n\r\n\t\t#region GridVars\r\n\t\tprivate bool drawGrid = true;\r\n\r\n\t\tprivate SizeF gridSize = new Size(32, 32);\r\n\r\n\t\tpublic bool DrawGrid { get { return drawGrid; } set { drawGrid = value; Draw(); } }\r\n\r\n\t\tpublic float GridWidth { get { return gridSize.Width; } set { GridSize = new SizeF(value, gridSize.Height); } }\r\n\r\n\t\tpublic float GridHeight { get { return gridSize.Height; } set { GridSize = new SizeF(gridSize.Width, value); } }\r\n\r\n\t\tpublic SizeF GridSize { get { return gridSize; } set { gridSize = value; Draw(); } }\r\n\t\t#endregion\r\n\r\n\t\t#region BorderVars\r\n\t\tprivate bool drawBorder = true;\r\n\r\n\t\tpublic bool DrawBorder { get { return drawBorder; } set { drawBorder = value; Draw(); } }\r\n\t\t#endregion\r\n\r\n\t\t#region Click&SelectVars\r\n\t\tprivate SelectType selectOption = SelectType.GridHighlight;\r\n\r\n\t\tprivate PointF clickPoint { get; set; } //= PointF.Empty;\r\n\t\tprivate PointF gridClickPoint = PointF.Empty;\r\n\r\n\t\tprivate bool allowHighlighting = true;\r\n\r\n\t\tprivate bool mousePressed = false;\r\n\r\n\t\tpublic bool dragableSelectionRectsAreVolatile = false;\r\n\r\n\t\tprivate RectangleF selectRect;\r\n\r\n\t\tprivate HashSet<RectangleF> highlightedSelectRects = new HashSet<RectangleF>();\r\n\r\n\t\tpublic bool AllowHighlighting { get { return allowHighlighting; } set { allowHighlighting = value; Draw(); } }\r\n\r\n\t\tpublic SelectType SelectOption { get { return selectOption; } set { ChangeSelectType(value); } }\r\n\r\n\t\tpublic RectangleF SelectRect { get { return selectRect; } private set { SetSelectionRect(value); } }\r\n\t\t#endregion\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7005182504653931, "alphanum_fraction": 0.7037400007247925, "avg_line_length": 39.50581359863281, "blob_id": "981dfded8a4480413965cafa0c9a7e1f6cc49269", "content_id": "2d01576a4006fca2295f3cd6ea84bbbae05bbb03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7141, "license_type": "no_license", "max_line_length": 145, "num_lines": 172, "path": "/HollowAether/Lib/InputOutput/SaveManager.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\nusing HollowAether.Lib.MapZone;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing HollowAether.Lib.GAssets;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.InputOutput {\r\n\tpublic static class SaveManager {\r\n\t\tpublic struct SaveFile {\r\n\t\t\tpublic SaveFile(INIParser.SectionContainer section) {\r\n\t\t\t\tbool gsExists = section.ContainsKey(\"GameState\");\r\n\t\t\t\tbool psExists = section.ContainsKey(\"PlayerState\");\r\n\t\t\t\tbool paExists = section.ContainsKey(\"PerksAcquired\");\r\n\t\t\t\tbool ftExists = section.ContainsKey(\"FlagsTripped\");\r\n\r\n\t\t\t\tif (gsExists && psExists && paExists && ftExists) {\r\n\t\t\t\t\tcurrentZone = Parser.Vector2Parser(section[\"GameState\"][\"Zone\"]);\r\n\t\t\t\t\tplayerPosition = Parser.Vector2Parser(section[\"PlayerState\"][\"Position\"]);\r\n\r\n\t\t\t\t\tflags = (from X in section[\"FlagsTripped\"] select new Tuple<String, bool>(X.Key, Parser.BooleanParser(X.Value))).ToArray();\r\n\r\n\t\t\t\t\tint? healthMaybe = GV.Misc.StringToInt(section[\"PlayerState\"][\"Health\"]);\r\n\r\n\t\t\t\t\tif (healthMaybe.HasValue) health = healthMaybe.Value; else {\r\n\t\t\t\t\t\tthrow new SaveSystemException($\"Invalid Health Value '{section[\"PlayerState\"][\"Health\"]}'\");\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tint? heartCountMaybe = GV.Misc.StringToInt(section[\"PlayerState\"][\"HeartCount\"]);\r\n\r\n\t\t\t\t\tif (heartCountMaybe.HasValue) heartCount = heartCountMaybe.Value; else {\r\n\t\t\t\t\t\tthrow new SaveSystemException($\"Invalid Heart Count Value '{section[\"PlayerState\"][\"HeartCount\"]}'\");\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tperks = (from X in section[\"PerksAcquired\"] select (PlayerPerks)Enum.Parse(typeof(PlayerPerks), X.Value)).ToArray();\r\n\t\t\t\t} else { // Doesn't exist, throw error\r\n\t\t\t\t\tif (!gsExists) throw new SaveFileCorruptedException($\"GameState\");\r\n\t\t\t\t\telse if (!psExists) throw new SaveFileCorruptedException($\"PlayerState\");\r\n\t\t\t\t\telse if (!paExists) throw new SaveFileCorruptedException($\"PerksAcquired\");\r\n\t\t\t\t\telse /*(!ftExists)*/ throw new SaveFileCorruptedException($\"FlagsTripped\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic SaveFile(Vector2 zoneIndex, Vector2 playerPos, int playerHealth, int numOfHearts, PlayerPerks[] _perks, Tuple<String, bool>[] _flags) {\r\n\t\t\t\tcurrentZone = zoneIndex;\r\n\t\t\t\tplayerPosition = playerPos;\r\n\t\t\t\thealth = playerHealth;\r\n\t\t\t\theartCount = numOfHearts;\r\n\t\t\t\tperks = _perks;\r\n\t\t\t\tflags = _flags;\r\n\t\t\t}\r\n\r\n\t\t\tpublic INIParser.SectionContainer ToINIContainer() {\r\n\t\t\t\tINIParser.SectionContainer container = new INIParser.SectionContainer();\r\n\r\n\t\t\t\tcontainer.AddSection(\"GameState\");\r\n\t\t\t\tcontainer[\"GameState\"][\"Zone\"] = Converters.ValueToString(typeof(Vector2), currentZone);\r\n\r\n\t\t\t\tcontainer.AddSection(\"PlayerState\"); // Current player details\r\n\t\t\t\tcontainer[\"PlayerState\"][\"Health\"] = health.ToString(); // Int representing health\r\n\t\t\t\tcontainer[\"PlayerState\"][\"Position\"] = Converters.ValueToString(typeof(Vector2), playerPosition);\r\n\t\t\t\tcontainer[\"PlayerState\"][\"HeartCount\"] = heartCount.ToString(); // Int representing number of hearts\r\n\r\n\t\t\t\tcontainer.AddSection(\"PerksAcquired\");\r\n\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, perks.Length)) {\r\n\t\t\t\t\tcontainer[\"PerksAcquired\"][$\"Perk{X + 1}\"] = perks[X].ToString();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcontainer.AddSection(\"FlagsTripped\"); // Section for any tripped flags etc.\r\n\r\n\t\t\t\tforeach (Tuple<String, bool> flagTuple in flags) {\r\n\t\t\t\t\tcontainer[\"FlagsTripped\"][flagTuple.Item1] = Converters.ValueToString(typeof(bool), flagTuple.Item2);\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn container;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static SaveFile GetCurrentSave() {\r\n\t\t\t\tVector2 playerPos = GV.MonoGameImplement.Player.Position;\r\n\r\n\t\t\t\treturn new SaveFile() {\r\n\t\t\t\t\tcurrentZone = GV.MonoGameImplement.map.Index,\r\n\t\t\t\t\thealth = GV.MonoGameImplement.GameHUD.GetDisplayedHealth(),\r\n\t\t\t\t\tplayerPosition = new Vector2((float)Math.Round(playerPos.X), (float)Math.Round(playerPos.Y)),\r\n\t\t\t\t\theartCount = GV.MonoGameImplement.GameHUD.HeartsCount,\r\n\t\t\t\t\tperks = GV.MonoGameImplement.Player.Perks,\r\n\t\t\t\t\tflags\t\t = (from X in GV.MapZone.GetFlagAssets() where (X.asset as Flag).ValueChangedFromDefault()\r\n\t\t\t\t\t\tselect new Tuple<String, bool>(X.assetID, (X.asset as Flag).Value)).ToArray()\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic static SaveFile GetEmptySave() {\r\n\t\t\t\treturn new SaveFile(\r\n\t\t\t\t\tGV.MonoGameImplement.map.GetStartZoneIndexOrEmpty(),\r\n\t\t\t\t\tnew Vector2(0, 0), \r\n\t\t\t\t\t32, 8,\r\n\t\t\t\t\tnew PlayerPerks[] { },\r\n\t\t\t\t\tnew Tuple<string, bool>[] { }\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tpublic Vector2 currentZone, playerPosition;\r\n\t\t\tpublic int health, heartCount;\r\n\t\t\tpublic PlayerPerks[] perks;\r\n\t\t\tpublic Tuple<String, bool>[] flags;\r\n\t\t}\r\n\r\n\t\tpublic static void CreateBlankSave(int slotIndex) {\r\n\t\t\tString path = GetSaveFilePathFromSlotIndex(slotIndex);\r\n\t\t\tstring contents = $\"{SAVE_HEADER}\\n\\n{SaveFile.GetEmptySave().ToINIContainer().ToFileContents()}\";\r\n\t\t\tInputOutputManager.WriteEncryptedFile(path, contents, GV.Encryption.oneTimePad);\r\n\t\t}\r\n\r\n\t\tpublic static void SaveCurrentGameState(int slotIndex) {\r\n\t\t\tString path = GetSaveFilePathFromSlotIndex(slotIndex); // Get file path\r\n\t\t\tString contents = $\"{SAVE_HEADER}\\n\\n{SaveFile.GetCurrentSave().ToINIContainer().ToFileContents()}\";\r\n\t\t\tInputOutputManager.WriteEncryptedFile(path, contents, GV.Encryption.oneTimePad); // Write file\r\n\t\t\tInputOutputManager.WriteFile(path+\".NEC\", contents); // Save unencrypted as well for now\r\n\t\t}\r\n\r\n\t\tpublic static SaveFile GetSave(int slotIndex) {\r\n\t\t\tString path = GetSaveFilePathFromSlotIndex(slotIndex);\r\n\r\n\t\t\tif (!InputOutputManager.FileExists(path)) // If save doesn't exist\r\n\t\t\t\tthrow new SaveFileDoesntExistAtChosenSlotException(slotIndex, path);\r\n\r\n\t\t\tString decryptedContents = InputOutputManager.ReadEncryptedFile(path, GV.Encryption.oneTimePad);\r\n\r\n\t\t\tINIParser.SectionContainer contents = INIParser.Parse(decryptedContents, path, false, true);\r\n\r\n\t\t\treturn new SaveFile(contents); // Read file contents and parse to desired data structure\r\n\t\t}\r\n\r\n\t\tpublic static void DeleteSave(int slotIndex) {\r\n\t\t\tString path = GetSaveFilePathFromSlotIndex(slotIndex);\r\n\r\n\t\t\tif (InputOutputManager.FileExists(path)) // Shouldn't need to\r\n\t\t\t\tSystem.IO.File.Delete(path); // If exists delete\r\n\t\t}\r\n\r\n\t\tpublic static bool SaveExists(int index) {\r\n\t\t\treturn InputOutputManager.FileExists(GetSaveFilePathFromSlotIndex(index));\r\n\t\t}\r\n\r\n\t\tpublic static String GetSaveFilePathFromSlotIndex(int slotIndex) {\r\n\t\t\tif (slotIndex > SAVE_SLOTS || slotIndex < 0)\r\n\t\t\t\tthrow new SaveSlotOutOfRangeException(slotIndex, SAVE_SLOTS);\r\n\r\n\t\t\treturn InputOutputManager.Join(GV.FileIO.assetPaths[\"Save\"], $\"Save {slotIndex+1}.SVE\");\r\n\t\t}\r\n\r\n\t\tpublic const int SAVE_SLOTS = 3;\r\n\r\n\t\tpublic const String SAVE_HEADER = \"SVE\";\r\n\r\n\t\t/// <summary>Holds current game slot statically for many uses</summary>\r\n\t\t/// <remarks>Will throw exception with default value</remarks>\r\n\t\tpublic static int CurrentSlot { get; private set; } = -1;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7452667951583862, "alphanum_fraction": 0.7487091422080994, "avg_line_length": 25.66666603088379, "blob_id": "ba4e9e8bbc13a8aad78376bb24e2062cd660daff", "content_id": "9589832fbb47415e1e29990f310307c90bb3fc86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 583, "license_type": "no_license", "max_line_length": 44, "num_lines": 21, "path": "/HollowAether/Lib/Interfaces/IPushable.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic interface IPushable {\r\n\t\tvoid Push(PushArgs args);\r\n\t\tvoid PushTo(Vector2 position, float over);\r\n\t\tPushArgs PushPack { get; }\r\n\t\tbool BeingPushed { get; }\r\n\t\tVector2 Position { get; set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7194228172302246, "alphanum_fraction": 0.7213114500045776, "avg_line_length": 44.77385330200195, "blob_id": "aafd471c33d98a8b8c05a2d849ca029e6b1e99af", "content_id": "29827fab7aa0cf6f28cd6282c17de19a7cfc0585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13239, "license_type": "no_license", "max_line_length": 130, "num_lines": 283, "path": "/HollowAether/Lib/GAssets/EntityAttributes/Definitions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Converter = HollowAether.Lib.InputOutput.Parsers.Converters;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Sprite : IMonoGameObject {\r\n\t\tpublic virtual bool ImplementEntityAttribute(String attrName, Object value, bool throwExcept = true) {\r\n\t\t\tswitch (attrName) {\r\n\t\t\t\tcase \"Position\": SetPosition((Vector2)value);\t\t\t return true;\r\n\t\t\t\tcase \"Width\": Width = (int)value;\t\t\t\t\t return true;\r\n\t\t\t\tcase \"Height\": Height = (int)value;\t\t\t\t\t return true;\r\n\t\t\t\tcase \"Texture\": animation.TextureID = value.ToString(); return true;\r\n\t\t\t\tcase \"AnimationRunning\": animation.animationRunning = (bool)value; return true;\r\n\t\t\t\tcase \"Layer\":\t\t\t animation.layer = (float)value; return true;\r\n\t\t\t\r\n\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void AttatchEntity(GameEntity entity) {\r\n\t\t\tforeach (String attr in entity.GetEntityAttributes()) {\r\n\t\t\t\tif (entity[attr].IsAssigned)\r\n\t\t\t\t\tImplementEntityAttribute(attr, entity[attr].GetActualValue());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static GameEntity GetGameEntity() {\r\n\t\t\treturn new GameEntity(typeof(Player).Name, GetAdditionalEntityAttributes().ToArray());\r\n\t\t}\r\n\r\n\t\tpublic static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[0]; // Return empty entity array for now\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class GenericSprite : Sprite, IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (base.ImplementEntityAttribute(attrName, value, false)) return true; else {\r\n\t\t\t\tswitch (attrName) {\r\n\t\t\t\t\tcase \"DefaultAnimation\": Animation[GV.MonoGameImplement.defaultAnimationSequenceKey] = (AnimationSequence)value; return true;\r\n\r\n\t\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"DefaultAnimation\", new EntityAttribute(typeof(AnimationSequence), false))\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t// Not really applicable\r\n\t\t}\r\n\t}\r\n\r\n\tpublic partial class Player : IInitializableEntity {\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"cs\\main\", typeof(string), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH, typeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT, typeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"player\\idleright\"].GetFrame(false);\r\n\t\t}\r\n\t}\r\n\r\n\t#region Enemies\r\n\tpublic partial class Bat : IInitializableEntity {\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"enemies\\bat\", typeof(string), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH, typeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT, typeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"bat\\rest\"].GetFrame(false);\r\n\t\t}\r\n\t}\r\n\r\n\t/*public partial class Crawler : IInitializableEntity {\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"enemies\\crawler\", typeof(string), true)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH,\t\t typeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT,\t\t typeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"player\\idleRight\"].GetFrame(false);\r\n\t\t}\r\n\t}*/\r\n\r\n\tpublic partial class Crusher : IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (attrName == \"Position\") initialPosition = (Vector2)value;\r\n\t\t\treturn base.ImplementEntityAttribute(attrName, value, true);\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"enemies\\crusher\", typeof(string), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH,\t\t typeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT,\t\t typeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"crusher\\idle\"].GetFrame(false);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic partial class Fortress : IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (attrName == \"Position\") defaultPosition = (Vector2)value;\r\n\t\t\treturn base.ImplementEntityAttribute(attrName, value, true);\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"enemies\\badeye\", typeof(string), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH,\t\ttypeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT,\t\ttypeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"fortress\\stationary\"].GetFrame(false);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic partial class Jumper : IInitializableEntity {\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"enemies\\jumper\", typeof(string), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH,\t\ttypeof(int), false)),\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT,\t\ttypeof(int), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\treturn GV.MonoGameImplement.importedAnimations[@\"jumper\\idle\"].GetFrame(false);\r\n\t\t}\r\n\t}\r\n\t#endregion\r\n\r\n\t#region Platforms And Blocks\r\n\tpublic partial class Block : IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (base.ImplementEntityAttribute(attrName, value, false)) return true; else {\r\n\t\t\t\tswitch (attrName) {\r\n\t\t\t\t\tcase \"DefaultAnimation\": Animation[GV.MonoGameImplement.defaultAnimationSequenceKey] = (AnimationSequence)value; return true;\r\n\r\n\t\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"DefaultAnimation\", new EntityAttribute(typeof(AnimationSequence), false))\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\r\n\t/*public partial class AngledBlock : IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (base.ImplementEntityAttribute(attrName, value, false)) return true; else {\r\n\t\t\t\tswitch (attrName) {\r\n\t\t\t\t\tcase \"DefaultAnimation\": Animation[GV.MonoGameImplement.defaultAnimationSequenceKey] = (AnimationSequence)value; return true;\r\n\t\t\t\t\t\r\n\t\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"DefaultAnimation\", new EntityAttribute(typeof(AnimationSequence), false))\r\n\t\t\t};\r\n\t\t}\r\n\t}*/\r\n\r\n\tpublic partial class GravityBlock : IInitializableEntity {\r\n\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\tif (base.ImplementEntityAttribute(attrName, value, false)) return true; else {\r\n\t\t\t\tswitch (attrName) {\r\n\t\t\t\t\tcase \"DefaultAnimation\": Animation[GV.MonoGameImplement.defaultAnimationSequenceKey] = (AnimationSequence)value; return true;\r\n\r\n\t\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"DefaultAnimation\", new EntityAttribute(typeof(AnimationSequence), false))\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\t#endregion\r\n\r\n\t#region Items And Pickups\r\n\tnamespace Items {\r\n\t\tpublic partial class SaveStation : IInitializableEntity {\r\n\t\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"cs\\npcsym\", typeof(string), false)),\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(FRAME_WIDTH, typeof(int), false)),\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(FRAME_HEIGHT, typeof(int), false)),\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\t\treturn new Frame(6, 1, FRAME_WIDTH, FRAME_HEIGHT, FRAME_WIDTH, FRAME_HEIGHT);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// public partial class Key : IInitializableEntity { }\r\n\r\n\t\t// public partial class HeartCanister : IInitializableEntity { }\r\n\r\n\t\tpublic partial class TreasureChest : IInitializableEntity {\r\n\t\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"items\\chest\", typeof(string), false)),\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH, typeof(int), false)),\r\n\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT, typeof(int), false)),\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\t\treturn new Frame(0, 0, FRAME_WIDTH, FRAME_HEIGHT, FRAME_WIDTH, FRAME_HEIGHT);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tnamespace Gates {\r\n\t\t\tpublic partial class OpenGate : IInitializableEntity {\r\n\t\t\t\tpublic override bool ImplementEntityAttribute(string attrName, object value, bool throwExcept = true) {\r\n\t\t\t\t\tif (base.ImplementEntityAttribute(attrName, value, false)) return true; else {\r\n\t\t\t\t\t\tswitch (attrName) {\r\n\t\t\t\t\t\t\tcase \"TargetZone\": TakesToZone = (Vector2)value; return true;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tdefault: if (throwExcept) throw new HollowAetherException(attrName); return false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic new static ICollection<KeyValuePair<String, EntityAttribute>> GetAdditionalEntityAttributes() {\r\n\t\t\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Texture\", new EntityAttribute(@\"cs\\npcsym\", typeof(string), false)),\r\n\t\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Width\", new EntityAttribute(SPRITE_WIDTH, typeof(int), false)),\r\n\t\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Height\", new EntityAttribute(SPRITE_HEIGHT, typeof(int), false)),\r\n\t\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"Layer\", new EntityAttribute(0.5f, typeof(float), false)),\r\n\t\t\t\t\t\tnew KeyValuePair<String, EntityAttribute>(\"TargetZone\", new EntityAttribute(typeof(Vector2), false)),\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic static Frame GetEntityFrame() {\r\n\t\t\t\t\treturn new Frame(384, 224, 32, 32, 1, 1, 1);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.7060465216636658, "alphanum_fraction": 0.7083721160888672, "avg_line_length": 29.159420013427734, "blob_id": "2446a15fe42c5d2dbf5bdb7b0cf4149364993d46", "content_id": "5ac3f80fb85e249a289c28bbc59950840f976672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4302, "license_type": "no_license", "max_line_length": 108, "num_lines": 138, "path": "/HollowAether/Lib/GAssets/Boundary/Container/Sequential.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing HollowAether.Lib.GAssets.Boundary;\r\nusing System.Collections;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tstruct SequentialBoundaryContainer : IBoundaryContainer {\r\n\t\tpublic SequentialBoundaryContainer(Rectangle spriteRect, params IBoundary[] boundaries) {\r\n\t\t\tthis.boundaries = new List<IBoundary>(boundaries);\r\n\r\n\t\t\t#region StructDefinitionDefaultValues\r\n\t\t\t_container = initialDimensions = Rectangle.Empty;\r\n\t\t\t_deltaPositions = DeltaPositions.Empty;\r\n\t\t\tSpriteRect = spriteRect;\r\n\t\t\t#endregion\r\n\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t\tBuildDeltaPositions(spriteRect);\r\n\t\t}\r\n\r\n\t\tpublic void BuildDeltaPositions(Rectangle? spriteRect) {\r\n\t\t\tif (boundaries.Count >= 1)\r\n\t\t\t\t_deltaPositions = (spriteRect.HasValue) ? BoundaryShared.GetDeltaPositions(spriteRect.Value, Container) \r\n\t\t\t\t\t: _deltaPositions = DeltaPositions.Empty; // If has value build, otherwise create empty positions\r\n\t\t}\r\n\r\n\t\tpublic void Add(IBoundary boundary) {\r\n\t\t\tthis.boundaries.Add(boundary);\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t}\r\n\r\n\t\tpublic void RemoveBoundary(IBoundary other) {\r\n\t\t\ttry { this.boundaries.Remove(other); } catch { return; }\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t}\r\n\r\n\t\tpublic void Offset(float X=0, float Y=0) {\r\n\t\t\tforeach (IBoundary b in boundaries)\r\n\t\t\t\tb.Offset(X, Y);\r\n\r\n\t\t\t_container.Offset(X, Y);\r\n\t\t}\r\n\r\n\t\tpublic void Offset(Vector2 offset) {\r\n\t\t\tOffset(offset.X, offset.Y);\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundaryContainer other) {\r\n\t\t\tif (!other.Container.Intersects(this._container))\r\n\t\t\t\treturn false; // prevent CPU waste\r\n\r\n\t\t\tforeach (IBoundary tarBoundary in other.Boundaries) {\r\n\t\t\t\tif (Intersects(tarBoundary, true)) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundaryContainer other, Vector2? offset) {\r\n\t\t\tif (offset.HasValue) Offset(offset.Value);\r\n\t\t\tbool success = Intersects(other);\r\n\t\t\tif (offset.HasValue) Offset(-offset.Value);\r\n\r\n\t\t\treturn success; // return successful collision after offset\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundary boundary, bool checkContainerCollision=true) {\r\n\t\t\tif (checkContainerCollision) {\r\n\t\t\t\tif (!boundary.Container.Intersects(this._container))\r\n\t\t\t\t\treturn false; // prevent CPU waste\r\n\t\t\t\t// else Ignore returning and carry on \r\n\t\t\t}\r\n\r\n\t\t\tforeach (IBoundary selfBoundary in Boundaries) {\r\n\t\t\t\tif (selfBoundary.Intersects(boundary))\r\n\t\t\t\t\treturn true; // first collision return\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic IBoundaryContainer GetCopy(Vector2? offset) {\r\n\t\t\tIBoundaryContainer returnValue = this;\r\n\r\n\t\t\tif (offset.HasValue)\r\n\t\t\t\treturnValue.Offset(offset.Value);\r\n\r\n\t\t\treturn returnValue;\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle GetBoundaryArea() {\r\n\t\t\treturn BoundaryShared.GetBoundaryArea(this);\r\n\t\t}\r\n\r\n\t\tIEnumerator IEnumerable.GetEnumerator() {\r\n\t\t\treturn GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IEnumerator<IBoundary> GetEnumerator() {\r\n\t\t\treturn Boundaries.Cast<IBoundary>().GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IntersectingPositions GetNonIntersectingPositions(IBoundaryContainer other) {\r\n\t\t\tIntersectingPositions positions = IntersectingPositions.Empty;\r\n\r\n\t\t\tforeach (IBoundary b in Boundaries) {\r\n\t\t\t\tforeach (IBoundary b2 in other.Boundaries) {\r\n\t\t\t\t\tif (!b.Intersects(b2)) continue; // No collision, so skip 4ward\r\n\t\t\t\t\tpositions.Set(CollisionCalculators.CalculateCollision(b, b2));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpositions -= new IntersectingPositions() {\r\n\t\t\t\t{Direction.Top, Container.Height + DeltaPositions.height },\r\n\t\t\t\t{Direction.Bottom, DeltaPositions.height },\r\n\t\t\t\t{Direction.Left, Container.Width + DeltaPositions.right },\r\n\t\t\t\t{Direction.Right, DeltaPositions.left },\r\n\t\t\t};\r\n\r\n\t\t\treturn positions;\r\n\t\t}\r\n\r\n\t\tprivate List<IBoundary> boundaries { get; set; }\r\n\t\tpublic IBRectangle Container { get { return _container; } }\r\n\t\tpublic DeltaPositions DeltaPositions { get { return _deltaPositions; } }\r\n\r\n\t\tpublic IBoundary[] Boundaries { get { return boundaries.ToArray(); } }\r\n\r\n\t\tpublic IBRectangle initialDimensions; // for collision purpose;\r\n\t\tprivate DeltaPositions _deltaPositions; // Changes between delta\r\n\t\tprivate IBRectangle _container; // bounding box for whole container\r\n\t\tpublic Rectangle SpriteRect { get; private set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7271627187728882, "alphanum_fraction": 0.7280701994895935, "avg_line_length": 39.84810256958008, "blob_id": "7f4e7d917434e2212d21e24f98178264fbcd0d8d", "content_id": "bb799e5e19ea93ca2b994b5db9fb8878ba31ac35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3308, "license_type": "no_license", "max_line_length": 99, "num_lines": 79, "path": "/HollowAether/Lib/Interfaces/IBoundaryContainer.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing HollowAether.Lib.GAssets.Boundary;\r\nusing IP = HollowAether.Lib.GAssets.IntersectingPositions;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary>Interface for a class which can hold a number of boundaries</summary>\r\n\tpublic interface IBoundaryContainer : IEnumerable<IBoundary>, IEnumerable {\r\n\t\t/// <summary>Adds boundary to boundary container</summary>\r\n\t\t/// <param name=\"boundary\">Boundary to add</param>\r\n\t\tvoid Add(IBoundary boundary);\r\n\r\n\t\t/// <summary>Removes boundary from boundary container</summary>\r\n\t\t/// <param name=\"boundary\">Boundary to remove</param>\r\n\t\tvoid RemoveBoundary(IBoundary boundary);\r\n\r\n\t\t/// <summary>Pushes all stored boundaries by a given amount</summary>\r\n\t\t/// <param name=\"X\">Horizontal displacement</param> <param name=\"Y\">Vertical displacement</param>\r\n\t\tvoid Offset(float X, float Y);\r\n\r\n\t\t/// <summary>Pushes all stored boundaries by a given amount</summary>\r\n\t\t/// <param name=\"offset\">Value by which to offset boundaries</param>\r\n\t\tvoid Offset(Vector2 offset);\r\n\r\n\t\t/// <summary>Whether any boundary in two containers intersect</summary>\r\n\t\t/// <param name=\"other\">Other boundary to check for collision with</param>\r\n\t\tbool Intersects(IBoundaryContainer other);\r\n\r\n\t\t/// <summary>Whether any boundary in two containers intersect with an offset</summary>\r\n\t\t/// <param name=\"other\">Other boundary to check for collision with</param>\r\n\t\t/// <param name=\"offset\">Value by which to offset</param>\r\n\t\tbool Intersects(IBoundaryContainer other, Vector2? offset);\r\n\r\n\t\t/// <summary>Creates a shallow clone of boundary</summary>\r\n\t\t/// <param name=\"offset\">Allows to push boundary afterwards as well</param>\r\n\t\tIBoundaryContainer GetCopy(Vector2? offset);\r\n\r\n\t\t/// <summary>Get rectangle encompassing all boundaries within container</summary>\r\n\t\tIBRectangle GetBoundaryArea();\r\n\r\n\t\t/// <summary>Get all intersecting positions between two boundaries</summary>\r\n\t\t/// <param name=\"other\">Other boundary</param>\r\n\t\tIP GetNonIntersectingPositions(IBoundaryContainer other);\r\n\r\n\t\t/// <summary>GetBoundaryArea()</summary>\r\n\t\tIBRectangle Container { get; }\r\n\r\n\t\t/// <summary>Duplicate of value stored in animation</summary>\r\n\t\tRectangle SpriteRect { get; }\r\n\r\n\t\t/// <summary>All boundaries in container</summary>\r\n\t\tIBoundary[] Boundaries { get; }\r\n\r\n\t\t/// <summary>Difference between spriterect and boundary</summary>\r\n\t\tDeltaPositions DeltaPositions { get; }\r\n\t}\r\n\r\n\t/// <summary>Boundary container resembling dictionary like object</summary>\r\n\tpublic interface ILabelledBoundaryContainer : IBoundaryContainer {\r\n\t\t/// <summary>Gets any intersected boundary labels</summary>\r\n\t\t/// <param name=\"other\">Boundary to check intersection with</param>\r\n\t\tString[] GetIntersectingBoundaryLabels(IBoundaryContainer other);\r\n\r\n\t\t/// <summary>Adds boundary</summary>\r\n\t\t/// <param name=\"name\">ID of boundary</param>\r\n\t\t/// <param name=\"boundary\">Value of boundary</param>\r\n\t\tvoid Add(String name, IBoundary boundary);\r\n\r\n\t\t/// <summary>Removes boundary from container</summary>\r\n\t\t/// <param name=\"name\">ID of boundary</param>\r\n\t\tvoid RemoveBoundary(String name);\r\n \t}\r\n}\r\n" }, { "alpha_fraction": 0.7138789892196655, "alphanum_fraction": 0.7281138896942139, "avg_line_length": 31.452381134033203, "blob_id": "fadc95fb704639e580013d2f9e45b1ee631d87f9", "content_id": "1b765e74f48c4ce2c14e2cc411d52718698c1b71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 113, "num_lines": 42, "path": "/HollowAether/Lib/GAssets/Effects/HitSprite.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic class HitSprite : VolatileSprite {\r\n\t\tpublic enum HitType { Red, Blue }\r\n\r\n\t\tpublic HitSprite(Vector2 position, int width, int height, HitType type) : base(position, width, height, true) {\r\n\t\t\thitType = type; // Store hit type\r\n\t\t\tInitialize(@\"fx\\hitfx\");\r\n\t\t\tInitializeVolatility(VolatilityType.Other, new ImplementVolatility(ReadyToDelete));\r\n\t\t}\r\n\r\n\t\tprivate bool ReadyToDelete(IMonoGameObject _object) {\r\n\t\t\treturn Animation.CurrentSequence.FrameIndex + 1 >= Animation.CurrentSequence.Length;\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tint blockDimensions = hitType == HitType.Red ? RED_SPRITE_DIMENSIONS : BLUE_SPRITE_DIMENSIONS;\r\n\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(\r\n\t\t\t\tblockDimensions, blockDimensions, 0, (int)hitType, \r\n\t\t\t\t(hitType == HitType.Red ? 3 : 4)+1, blockDimensions,\r\n\t\t\t\tRED_SPRITE_DIMENSIONS, 5, true, 0\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tprivate HitType hitType;\r\n\r\n\t\tpublic const int RED_SPRITE_DIMENSIONS = 32; // 32 by 32\r\n\r\n\t\tpublic const int BLUE_SPRITE_DIMENSIONS = 48; // 48 by 48\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.755958080291748, "alphanum_fraction": 0.755958080291748, "avg_line_length": 35.46428680419922, "blob_id": "a502d09d7b7e1bde1de891fbb7c7ab51226f6d67", "content_id": "4bde1f6dc6bb843af7c6922c35608eb4f4fd3de1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 146, "num_lines": 28, "path": "/HollowAether/Lib/GAssets/Boundary/PositionsContainer.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t#region PositionsContainerTypeDef\r\n\tpublic class PositionsContainer : Dictionary<String, List<Dictionary<String, int>>> {\r\n\t\tpublic PositionsContainer() : base() { }\r\n\r\n\t\tpublic PositionsContainer(int capacity) : base(capacity) { }\r\n\r\n\t\tpublic PositionsContainer(IEqualityComparer<String> comparer) : base(comparer) { }\r\n\r\n\t\tpublic PositionsContainer(Dictionary<String, List<Dictionary<String, int>>> dict) : base(dict) { }\r\n\r\n\t\tpublic PositionsContainer(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\r\n\t\tpublic PositionsContainer(int capacity, IEqualityComparer<String> comparer) : base(capacity, comparer) { }\r\n\r\n\t\tpublic PositionsContainer(Dictionary<String, List<Dictionary<String, int>>> dict, IEqualityComparer<String> comparer) : base(dict, comparer) { }\r\n\t}\r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.6935318112373352, "alphanum_fraction": 0.6960985660552979, "avg_line_length": 28.4375, "blob_id": "b53c66fe14a40bc334bdcab10863cb1b38b208eb", "content_id": "3a70332ee0969acecfa0bc487869b054533000ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1950, "license_type": "no_license", "max_line_length": 86, "num_lines": 64, "path": "/HollowAether/Lib/Global/Batches.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic class RemovalBatch {\r\n\t\t/// <summary>Batch of items to remove from stored MGObjects</summary>\r\n\t\t/// <param name=\"capacity\">Minimum batch length before resizing</param>\r\n\t\tpublic RemovalBatch(int capacity=35) {\r\n\t\t\ttoRemove = new List<IMonoGameObject>(capacity);\r\n\t\t}\r\n\r\n\t\t/// <summary>Marks object which is to be removed</summary>\r\n\t\t/// <param name=\"monogameObjectID\">ID of target object</param>\r\n\t\tpublic void Add(IMonoGameObject monogameObject) {\r\n\t\t\ttoRemove.Add(monogameObject);\r\n\t\t}\r\n\r\n\t\t/// <summary>Executes removal batch</summary>\r\n\t\tpublic void Execute() {\r\n\t\t\tforeach (IMonoGameObject _object in toRemove) {\r\n\t\t\t\tGV.MonoGameImplement.monogameObjects.Remove(_object); // delete object\r\n\t\t\t}\r\n\r\n\t\t\ttoRemove.Clear(); // Remove all stored elements in batch\r\n\t\t}\r\n\r\n\t\tprivate List<IMonoGameObject> toRemove;\r\n\t}\r\n\r\n\tpublic class AdditionBatch {\r\n\t\tpublic AdditionBatch() {\r\n\t\t\tbatch = new List<Tuple<bool, IMonoGameObject>>();\r\n\t\t}\r\n\r\n\t\tpublic void Add(String ID, IMonoGameObject _object) {\r\n\t\t\t_object.SpriteID = ID; // Store to object instance\r\n\t\t\tbatch.Add(new Tuple<bool, IMonoGameObject>(true, _object));\r\n\t\t}\r\n\r\n\t\tpublic void AddRangeNameless(params IMonoGameObject[] args) {\r\n\t\t\tbatch.AddRange((from X in args select new Tuple<bool, IMonoGameObject>(false, X)));\r\n\t\t}\r\n\r\n\t\tpublic void AddNameless(IMonoGameObject _object) {\r\n\t\t\tbatch.Add(new Tuple<bool, IMonoGameObject>(false, _object));\r\n\t\t}\r\n\r\n\t\tpublic void Execute() {\r\n\t\t\tforeach (var X in batch) {\r\n\t\t\t\tif (X.Item1) { GV.MonoGameImplement.monogameObjects.Add(X.Item2); }\r\n\t\t\t\telse { GV.MonoGameImplement.monogameObjects.AddNameless(X.Item2); }\r\n\t\t\t}\r\n\r\n\t\t\tbatch.Clear();\r\n\t\t}\r\n\r\n\t\tprivate List<Tuple<bool, IMonoGameObject>> batch;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6978769898414612, "alphanum_fraction": 0.7103973627090454, "avg_line_length": 38.82222366333008, "blob_id": "44574ec82ac7598f1f423ab8144b71712b32d79f", "content_id": "945afbcf3cd9690558434c983798eb1bb0e43a6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3676, "license_type": "no_license", "max_line_length": 166, "num_lines": 90, "path": "/HollowAether/Lib/GAssets/Effects/ValueChangedEffect.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.FX {\r\n\tpublic sealed class ValueChangedEffect : FXSprite {\r\n\t\tpublic enum FlickerColor { White, Red, Blue, Gold }\r\n\r\n\t\tpublic enum FlickerValue { Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Plus, Minus}\r\n\r\n\t\tValueChangedEffect(Vector2 position, FlickerValue _value, bool _changeAlpha, bool _move, int timeout, params FlickerColor[] _colors) \r\n\t\t\t: base(position, SPRITE_WIDTH, SPRITE_HEIGHT, timeout) {\r\n\t\t\t// if (_amount < 0 || _amount > 9) throw new HollowAetherException($\"FX only supports amount values between 1 and 9\");\r\n\t\t\tif (_colors.Length == 0) throw new HollowAetherException($\"A minimum of at least one colours must be displayed\");\r\n\r\n\t\t\tvalue = _value; colors = _colors; changeAlpha = _changeAlpha; move = _move; // Store used sprite variables\r\n\r\n\t\t\tInitialize($\"cs\\\\incrementeffects\"); // Increment effects from Cave Story is the texture used here\r\n\t\t}\r\n\r\n\t\tpublic static IMonoGameObject[] Create(Vector2 position, int _value, bool changeAlpha=false, bool move=true, int timeout = TIME_OUT, params FlickerColor[] colors) {\r\n\t\t\tString value = (_value < 0) ? _value.ToString().Substring(1) : _value.ToString();\r\n\t\t\tIMonoGameObject[] objects = new IMonoGameObject[value.Length+1]; // Hold\r\n\r\n\t\t\tint counter = 0; // Counts indexes within value effect objects array\r\n\t\t\tFlickerValue _operator = _value < 0 ? FlickerValue.Minus : FlickerValue.Plus;\r\n\t\t\tobjects[counter++] = new ValueChangedEffect(position, _operator, changeAlpha, move, timeout, colors);\r\n\r\n\t\t\tforeach (char c in value.ToCharArray()) {\r\n\t\t\t\tposition.X += SPRITE_WIDTH; // Increment horizontal sprite positioning\r\n\t\t\t\tFlickerValue fVal = (FlickerValue)Enum.Parse(typeof(FlickerValue), c.ToString());\r\n\t\t\t\tobjects[counter++] = new ValueChangedEffect(position, fVal, changeAlpha, move, timeout, colors);\r\n\t\t\t}\r\n\r\n\t\t\treturn objects; // Return all valid effect objects\r\n\t\t}\r\n\r\n\t\tpublic static IMonoGameObject[] CreateStatic(Vector2 position, int value, int timeout, params FlickerColor[] colors) {\r\n\t\t\treturn Create(position, value, false, false, timeout, colors);\r\n\t\t}\r\n\r\n\t\tprotected override void ImplementEffect() {\r\n\t\t\tif (changeAlpha) {\r\n\t\t\t\tAnimation.Opacity -= elapsedTime * 1000 / TIME_OUT;\r\n\t\t\t\tif (Animation.Opacity < 0.5) VolatilityManager.Delete(this);\r\n\t\t\t}\r\n\r\n\t\t\tif (move) {\r\n\t\t\t\tvelocity += acceleration * elapsedTime;\r\n\t\t\t\tOffsetSpritePosition(Y: velocity * elapsedTime);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimationSequence sequence; // Sequence to assign default animation to\r\n\r\n\t\t\tif (colors.Length == 1) sequence = new AnimationSequence(0, GetFrame(colors[0])); {\r\n\t\t\t\t// Otherwise sequence flickers between multiple colours values throughout existence\r\n\t\t\t\tsequence = new AnimationSequence(0, (from X in colors select GetFrame(X)).ToArray());\r\n\t\t\t}\r\n\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = sequence;\r\n\t\t}\r\n\r\n\t\tprivate Frame GetFrame(FlickerColor color, int runCount=4) {\r\n\t\t\treturn new Frame((int)color, (int)value, 16, 16, 16, 16, runCount);\r\n\t\t}\r\n\r\n\t\tprivate bool changeAlpha, move;\r\n\t\tprivate int amount;\r\n\t\tprivate FlickerColor[] colors;\r\n\t\tprivate FlickerValue value;\r\n\r\n\t\tfloat acceleration = -100;\r\n\t\tfloat velocity = -050;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 12, SPRITE_HEIGHT = 12, TIME_OUT = 5000;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7631976008415222, "alphanum_fraction": 0.7699849009513855, "avg_line_length": 28.837209701538086, "blob_id": "88586e5f1f2a1f7e9b1238f4009e0ffe7c783d98", "content_id": "616fda1b8ac4685dde4ef4609cc398c7da0dc20e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 94, "num_lines": 43, "path": "/HollowAether/Lib/Global/GlobalVars/Variables.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class Variables {\r\n\t\t\tpublic static Vector2 GetScaledScreenSize(float scale) {\r\n\t\t\t\treturn new Vector2(Variables.windowWidth, Variables.windowHeight) * new Vector2(scale);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Vector2 windowSize { get { return new Vector2(windowWidth, windowHeight); } }\r\n\r\n\t\t\tpublic static Random random = new Random();\r\n\t\t\tpublic static readonly float degrees45ToRadians = (float)Math.Sin(Math.PI / 4);\r\n\t\t\tpublic static int windowWidth, windowHeight, displayWidth, displayHeight;\r\n\t\t\tpublic static int playerDashCost = 5;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6991525292396545, "alphanum_fraction": 0.7063431143760681, "avg_line_length": 53.23404312133789, "blob_id": "2e0c29a0eb137c74145649cfa2baaaf362da6224", "content_id": "f0ce519d6f5816c073d43dd7af7cb06d00dbe28c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7790, "license_type": "no_license", "max_line_length": 142, "num_lines": 141, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/CommandLineExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\t/// <summary>Root Exception For All Command Line Exceptions</summary>\r\n\tclass CommandLineException : HollowAetherException {\r\n\t\tpublic CommandLineException(int _minArgs, int _maxArgs, String _cmdAssist, String command) : base() {\r\n\t\t\tminArgs = _minArgs; maxArgs = _maxArgs; commandAssistance = _cmdAssist; cmd = command;\r\n\t\t}\r\n\t\tpublic CommandLineException(String msg, int _minArgs, int _maxArgs, String _cmdAssist, String command) : base(msg) {\r\n\t\t\tminArgs = _minArgs; maxArgs = _maxArgs; commandAssistance = _cmdAssist; cmd = command;\r\n\t\t}\r\n\t\tpublic CommandLineException(String msg, Exception inner, int _minArgs, int _maxArgs, String _cmdAssist, String command) : base(msg, inner) {\r\n\t\t\tminArgs = _minArgs; maxArgs = _maxArgs; commandAssistance = _cmdAssist; cmd = command;\r\n\t\t}\r\n\t\tpublic CommandLineException(SerializationInfo info, StreamingContext context, int _minArgs, int _maxArgs, String _cmdAssist, String command)\r\n\t\t\t: base(info, context) { minArgs = _minArgs; maxArgs = _maxArgs; commandAssistance = _cmdAssist; cmd = command; }\r\n\r\n\t\tpublic int maxArgs, minArgs;\r\n\t\tpublic String commandAssistance, cmd; // = ' \"Arg1\" ?\"OptionalArg2\" '\r\n\t}\r\n\r\n\t#region RootExceptions\r\n\t/// <summary>Encrypt File Command Line Exception</summary>\r\n\tclass EncryptFileException : CommandLineException {\r\n\t\tpublic EncryptFileException()\r\n\t\t\t: base(1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"encryptFile\") { }\r\n\t\tpublic EncryptFileException(String msg)\r\n\t\t\t: base(msg, 1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"encryptFile\") { }\r\n\t\tpublic EncryptFileException(String msg, Exception inner)\r\n\t\t\t: base(msg, inner, 1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"encryptFile\") { }\r\n\t}\r\n\r\n\t/// <summary>Decrypt File Command Line Exception</summary>\r\n\tclass DecryptFileException : CommandLineException {\r\n\t\tpublic DecryptFileException()\r\n\t\t\t: base(1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"decryptFile\") { }\r\n\t\tpublic DecryptFileException(String msg)\r\n\t\t\t: base(msg, 1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"decryptFile\") { }\r\n\t\tpublic DecryptFileException(String msg, Exception inner)\r\n\t\t\t: base(msg, inner, 1, 2, \"\\\"Path\\\\To\\\\File\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\File\\\"\", \"decryptFile\") { }\r\n\t}\r\n\r\n\t/// <summary>Encrypt Directory Command Line Exception</summary>\r\n\tclass EncryptDirectoryException : CommandLineException {\r\n\t\tpublic EncryptDirectoryException()\r\n\t\t\t: base(1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"encryptDirectory\") { }\r\n\t\tpublic EncryptDirectoryException(String msg)\r\n\t\t\t: base(msg, 1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"encryptDirectory\") { }\r\n\t\tpublic EncryptDirectoryException(String msg, Exception inner)\r\n\t\t\t: base(msg, inner, 1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Encrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"encryptDirectory\") { }\r\n\t}\r\n\r\n\t/// <summary>Decrypt Directory Command Line Exception</summary>\r\n\tclass DecryptDirectoryException : CommandLineException {\r\n\t\tpublic DecryptDirectoryException()\r\n\t\t\t: base(1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"decryptDirectory\") { }\r\n\t\tpublic DecryptDirectoryException(String msg)\r\n\t\t\t: base(msg, 1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"decryptDirectory\") { }\r\n\t\tpublic DecryptDirectoryException(String msg, Exception inner)\r\n\t\t\t: base(msg, inner, 1, 2, \"\\\"Path\\\\To\\\\Directory\\\\To\\\\Decrypt\\\" ?\\\"Path\\\\To\\\\Target\\\\Directory\\\"\", \"decryptDirectory\") { }\r\n\t}\r\n\r\n\t/// <summary>Set target map Command Line Exception</summary>\r\n\tclass SetMapException : CommandLineException {\r\n\t\tpublic SetMapException() : base(1, 1, \"\\\"Path\\\\To\\\\Map-File\\\"\", \"map\") { }\r\n\t\tpublic SetMapException(String msg) : base(msg, 1, 1, \"\\\"Path\\\\To\\\\Map-File\\\"\", \"map\") { }\r\n\t\tpublic SetMapException(String msg, Exception inner) : base(msg, inner, 1, 1, \"\\\"Path\\\\To\\\\Map-File\\\"\", \"map\") { }\r\n\t}\r\n\r\n\t/// <summary>Set game zoom Command Line Exception</summary>\r\n\tclass SetGameZoomException : CommandLineException {\r\n\t\tpublic SetGameZoomException() : base(1, 1, \"new-game-zoom\", \"zoom\") { }\r\n\t\tpublic SetGameZoomException(String msg) : base(msg, 1, 1, \"new-game-zoom\", \"zoom\") { }\r\n\t\tpublic SetGameZoomException(String msg, Exception inner) : base(msg, inner, 1, 1, \"new-game-zoom\", \"zoom\") { }\r\n\t}\r\n\r\n\t/* // Kind of Impossible to throw, but in case later needed I'll leave it here\r\n\t\r\n\tclass SetFullScreenException : CommandLineException {\r\n\t\tpublic SetFullScreenException() : base(0, 0, null) { }\r\n\t\tpublic SetFullScreenException(String msg) : base(msg, 1, 1, null) { }\r\n\t\tpublic SetFullScreenException(String msg, Exception inner) : base(msg, inner, 1, 1, null) { }\r\n\t}\r\n\r\n\tclass SetWindowedScreenException : CommandLineException {\r\n\t\tpublic SetWindowedScreenException() : base(0, 0, null) { }\r\n\t\tpublic SetWindowedScreenException(String msg) : base(msg, 1, 1, null) { }\r\n\t\tpublic SetWindowedScreenException(String msg, Exception inner) : base(msg, inner, 1, 1, null) { }\r\n\t}\r\n\r\n\tclass SetFPSException : CommandLineException {\r\n\t\tpublic SetFPSException() : base(0, 0, null) { }\r\n\t\tpublic SetFPSException(String msg) : base(msg, 1, 1, null) { }\r\n\t\tpublic SetFPSException(String msg, Exception inner) : base(msg, inner, 1, 1, null) { }\r\n\t}*/\r\n\t#endregion\r\n\r\n\r\n\t#region ArgumentExceptions\r\n\t/// <summary>Thrown when an argument for encrypt file doesn't exist</summary>\r\n\tclass EncryptFileArgNotFoundException : EncryptFileException {\r\n\t\tpublic EncryptFileArgNotFoundException(String fpath) : base($\"Could Not Find File '{fpath}'\") { }\r\n\t\tpublic EncryptFileArgNotFoundException(String fpath, Exception inner) : base($\"Could Not Find File '{fpath}'\", inner) { }\r\n\t}\r\n\r\n\t/// <summary>Thrown when an argument for decrypt file doesn't exist</summary>\r\n\tclass DecryptFileArgNotFoundException : EncryptFileException {\r\n\t\tpublic DecryptFileArgNotFoundException(String fpath) : base($\"Could Not Find File '{fpath}'\") { }\r\n\t\tpublic DecryptFileArgNotFoundException(String fpath, Exception inner) : base($\"Could Not Find File '{fpath}'\", inner) { }\r\n\t}\r\n\r\n\t/// <summary>Thrown when an argument for encrypt directory doesn't exist</summary>\r\n\tclass EncryptDirectoryArgNotFoundException : EncryptDirectoryException {\r\n\t\tpublic EncryptDirectoryArgNotFoundException(String dpath) : base($\"Could Not Found The Directory '{dpath}'\") { }\r\n\t\tpublic EncryptDirectoryArgNotFoundException(String dpath, Exception inner) : base($\"Could Not Found The Directory '{dpath}'\", inner) { }\r\n\t}\r\n\r\n\t/// <summary>Thrown when an argument for decrypt directory doesn't exist</summary>\r\n\tclass DecryptDirectoryArgNotFoundException : EncryptDirectoryException {\r\n\t\tpublic DecryptDirectoryArgNotFoundException(String dpath) : base($\"Could Not Found The Directory '{dpath}'\") { }\r\n\t\tpublic DecryptDirectoryArgNotFoundException(String dpath, Exception inner) : base($\"Could Not Found The Directory '{dpath}'\", inner) { }\r\n\t}\r\n\r\n\t/// <summary>Thrown when set zoom argument isn't valid</summary>\r\n\tclass SetGameZoomArgumentIncorrectTypeException : SetGameZoomException {\r\n\t\tpublic SetGameZoomArgumentIncorrectTypeException(String argument)\r\n\t\t\t: base($\"Argument '{argument}' Could Not Be Converted To A Float\") { }\r\n\t\tpublic SetGameZoomArgumentIncorrectTypeException(String argument, Exception inner)\r\n\t\t\t: base($\"Argument '{argument}' Could Not Be Converted To A Float\", inner) { }\r\n\t}\r\n\t#endregion\r\n\r\n\t#region ArgumentValidationExceptions\r\n\t//public class EncryptFileTargetNotFoundException : \r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.7241039276123047, "alphanum_fraction": 0.7244327664375305, "avg_line_length": 29.03061294555664, "blob_id": "0ed16fdb942c37dde468a1e1c945e8b788640993", "content_id": "61d668f3d698b8f1a3eb6c07c82f25e2b1c22cf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3043, "license_type": "no_license", "max_line_length": 89, "num_lines": 98, "path": "/HollowAether/Lib/God.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GameWindow;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Debug;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.GAssets.Items;\r\nusing FC = HollowAether.Lib.GAssets.FX.ValueChangedEffect.FlickerColor;\r\nusing HollowAether.Lib.GAssets.FX;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic class God {\r\n\t\tpublic God() {\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\tpublic void Initialize() {\r\n\t\t\tGV.FileIO.settingsManager = new SettingsManager();\r\n\r\n\t\t\tGV.MonoGameImplement.Player = new Player(); // Create Player First!!!\r\n\r\n\t\t\tGV.MonoGameImplement.camera = new Camera2D(zoom: GV.MonoGameImplement.gameZoom);\r\n\r\n\t\t\tGV.MonoGameImplement.map = new Map();\r\n\t\t\tGV.MonoGameImplement.map.Initialize();\r\n\r\n\t\t\tGV.MonoGameImplement.GameHUD = new HUD();\r\n\r\n\t\t\t#if DEBUG // Will have no impact on release build CPU usage\r\n\t\t\tDebugPrinter.Add(\"Position\", null);\r\n\t\t\tDebugPrinter.Add(\"CameraPosition\", null);\r\n\t\t\tDebugPrinter.Add(\"BurstPoints\", null);\r\n\t\t\tDebugPrinter.Add(\"BurstPointWait\", null);\r\n\t\t\tDebugPrinter.Add(\"Money\", null);\r\n\t\t\tDebugPrinter.Add(\"Intersected\", null);\r\n\t\t\tDebugPrinter.Add(\"ObjectsCount\", null);\r\n\t\t\t#endif\r\n\t\t}\r\n\r\n\t\tpublic void Update(GameTime gt) {\r\n\t\t\tGV.MonoGameImplement.gameTime = gt;\r\n\r\n\t\t\t#region ControlUpdates\r\n\t\t\tGV.PeripheralIO.previousKBState = GV.PeripheralIO.currentKBState;\r\n\t\t\tGV.PeripheralIO.currentKBState = Keyboard.GetState();\r\n\t\t\tGV.PeripheralIO.previousGPState = GV.PeripheralIO.currentGPState;\r\n\t\t\tGV.PeripheralIO.currentGPState = GamePad.GetState(PlayerIndex.One);\r\n\r\n\t\t\tGV.PeripheralIO.previousControlState = GV.PeripheralIO.currentControlState;\r\n\t\t\tGV.PeripheralIO.currentControlState.Update(); // Assign new ControlState vars\r\n\t\t\t#endregion\r\n\t\t\t \r\n\t\t\tif (GV.PeripheralIO.currentKBState.IsKeyDown(Keys.Enter) && // Enter has to be pressed\r\n\t\t\t\tGV.PeripheralIO.CheckMultipleKeys(keys: new Keys[] { Keys.LeftAlt, Keys.RightAlt }))\r\n\t\t\t\tGV.hollowAether.ToggleFullScreen(); // fscreen->!fscreen || !fscreen->fscreen\r\n\r\n\t\t\tif (GV.PeripheralIO.currentKBState.IsKeyDown(Keys.Escape)) EndGame();\r\n\r\n\t\t\tGameWindows.UpdateCurrentGameWindow();\r\n\r\n\t\t\tif (GV.MonoGameImplement.background != null)\r\n\t\t\t\tGV.MonoGameImplement.background.Update();\r\n\t\t}\r\n\r\n\t\tpublic void EndGame() {\r\n\t\t\tif (GV.FileIO.settingsManager != null)\r\n\t\t\t\tGV.FileIO.settingsManager.Save();\r\n\r\n\t\t\tGV.hollowAether.Exit();\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tif (GV.MonoGameImplement.background != null)\r\n\t\t\t\tGV.MonoGameImplement.background.Draw();\r\n\r\n\t\t\tGameWindows.DrawCurrentGameWindow();\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6842408776283264, "alphanum_fraction": 0.6848170757293701, "avg_line_length": 32.884422302246094, "blob_id": "96ca29f22a267b617501721b4e6c6b0827137e4c", "content_id": "03c16f0b0d05671482ca9acc18edc382e5d68fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6944, "license_type": "no_license", "max_line_length": 131, "num_lines": 199, "path": "/HollowAether/Lib/Entity/Asset.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.GAssets;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether {\r\n\tpublic class AssetContainer : Dictionary<String, Asset> {\r\n\t\t#region BaseConstructorImplement\r\n\t\tpublic AssetContainer() : base() { }\r\n\t\tpublic AssetContainer(int capacity) : base(capacity) { }\r\n\t\tpublic AssetContainer(IEqualityComparer<String> comp) : base(comp) { }\r\n\t\tpublic AssetContainer(IDictionary<String, Asset> dict) : base(dict) { }\r\n\t\tpublic AssetContainer(int cap, IEqualityComparer<String> comp) : base(cap, comp) { }\r\n\t\tpublic AssetContainer(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t\tpublic AssetContainer(IDictionary<String, Asset> dictionary, IEqualityComparer<String> comparer) : base(dictionary, comparer) { }\r\n\t\t#endregion\r\n\t}\r\n\r\n\t#region AssetDefinitions\r\n\t/// <summary>Holder of assets defined in zone files</summary>\r\n\tpublic class Asset : Object, ICloneable {\r\n\t\t/// <summary>Default asset constructor</summary>\r\n\t\t/// <param name=\"type\">Type of asset</param>\r\n\t\t/// <param name=\"_ID\">ID of asset</param>\r\n\t\t/// <param name=\"assetValue\">Value of asset</param>\r\n\t\tpublic Asset(Type type, String _ID, Object assetValue) {\r\n\t\t\t_assetType = type;\r\n\t\t\t_assetID = _ID;\r\n\t\t\tSetAsset(assetValue);\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts instance to human readable string</summary>\r\n\t\tpublic override string ToString() { return $\"({assetID}): Asset of Type '{assetType}'\"; }\r\n\r\n\t\tpublic Object Clone() { return (Asset)MemberwiseClone(); }\r\n\r\n\t\t/// <summary>Sets value of asset</summary>\r\n\t\t/// <param name=\"value\">Value to set asset</param>\r\n\t\tpublic void SetAsset(Object value) {\r\n\t\t\t_asset = value; // Set asset for later checks\r\n\t\t\tCheckType(); // Check type\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks whether given type is compatible with current asset</summary>\r\n\t\t/// <param name=\"checkType\">Type to compare to current asset type</param>\r\n\t\tprotected virtual void CheckType() {\r\n\t\t\tif (_asset.GetType() != assetType)\r\n\t\t\t\tthrow new AssetAssignmentException(assetType, _asset.GetType());\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks Whether Asset Type Matches Argument Type</summary>\r\n\t\t/// <param name=\"type\">Type to compare with</param>\r\n\t\t/// <returns>Boolean indicating match</returns>\r\n\t\tpublic bool TypesMatch(Type type) {\r\n\t\t\treturn GV.Misc.DoesExtend(type, _assetType);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks Whether Asset Type Matches Argument Type</summary>\r\n\t\t/// <param name=\"arg\">Argument to compare types with</param>\r\n\t\t/// <returns>Boolean indicating match</returns>\r\n\t\tpublic bool TypesMatch(Object arg) {\r\n\t\t\treturn TypesMatch(arg.GetType());\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks Whether Asset Type Matches Argument Type</summary>\r\n\t\t/// <typeparam name=\"T\">Type to compare with asset</typeparam>\r\n\t\t/// <returns>Boolean indicating match</returns>\r\n\t\tpublic bool TypesMatch<T>() {\r\n\t\t\treturn TypesMatch(typeof(T));\r\n\t\t}\r\n\r\n\t\tpublic virtual object GetValue() {\r\n\t\t\treturn _asset;\r\n\t\t}\r\n\r\n\t\tpublic virtual void Delete() {\r\n\t\t\t_asset = null;\r\n\t\t}\r\n\r\n\t\tprotected Object _asset; // Value of asset\r\n\t\tprotected Type _assetType; // Type of Asset\r\n\t\tprotected String _assetID; // ID given to Asset\r\n\r\n\t\tpublic Type assetType { get { return _assetType; } }\r\n\r\n\t\tpublic String assetID { get { return _assetID; } }\r\n\r\n\t\tpublic Object asset { get { return GetValue(); } set { SetAsset(value); } }\r\n\r\n\t\tpublic Boolean IsImportedAsset { get; set; } = false;\r\n\t}\r\n\r\n\tpublic class BooleanAsset : Asset {\r\n\t\tpublic BooleanAsset(String id, bool value) : base(typeof(Boolean), id, value) { }\r\n\r\n\t\tpublic BooleanAsset(String id, Object value) : base(typeof(Boolean), id, value) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Boolean Asset of Type '{assetType}'\";\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class FlagAsset : Asset {\r\n\t\tpublic FlagAsset(String id, bool initialValue = false) : base(typeof(Flag), id, new Flag(initialValue)) {\r\n\t\t\tInitialValue = initialValue;\r\n\t\t}\r\n\r\n\t\tpublic FlagAsset(String id, Object initialValue) : base(typeof(Flag), id, new Flag((bool)initialValue)) {\r\n\t\t\tInitialValue = (bool)initialValue;\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Flag Asset of Type '{assetType}'\";\r\n\t\t}\r\n\r\n\t\tpublic bool InitialValue { get; private set; }\r\n\t}\r\n\r\n\tpublic class TextureAsset : Asset {\r\n\t\tpublic TextureAsset(String id, String textureKey) : base(typeof(String), id, textureKey) { }\r\n\r\n\t\tpublic TextureAsset(String id, Object textureKey) : base(typeof(String), id, (String)textureKey) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Texture Asset of Type '{assetType}'\";\r\n\t\t}\r\n\r\n\t\tprotected override void CheckType() {\r\n\t\t\tbase.CheckType(); // Checks whether value types match\r\n\r\n\t\t\tif (!GV.MonoGameImplement.textures.ContainsKey(asset.ToString()))\r\n\t\t\t\tthrow new HollowAetherException($\"Texture defined in zone '{_asset}' Not Found\");\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class PositionAsset : Asset {\r\n\t\tpublic PositionAsset(String id, Vector2 position) : base(typeof(Vector2), id, position) { }\r\n\r\n\t\tpublic PositionAsset(String id, Object position) : base(typeof(Vector2), id, (Vector2)position) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Position Asset of Type '{assetType}'\";\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class IntegerAsset : Asset {\r\n\t\tpublic IntegerAsset(String id, int value) : base(typeof(int), id, value) { }\r\n\r\n\t\tpublic IntegerAsset(String id, Object value) : base(typeof(int), id, (int)value) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Integer Asset of Type '{assetType}'\";\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class FloatAsset : Asset {\r\n\t\tpublic FloatAsset(String id, float value) : base(typeof(float), id, value) { }\r\n\r\n\t\tpublic FloatAsset(String id, Object value) : base(typeof(float), id, (float)value) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): Float Asset of Type '{assetType}'\";\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class StringAsset : Asset {\r\n\t\tpublic StringAsset(String id, String value) : base(typeof(String), id, value) { }\r\n\r\n\t\tpublic StringAsset(String id, Object value) : base(typeof(String), id, (String)value) { }\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"({assetID}): String Asset of Type '{assetType}'\";\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class AnimationAsset : Asset {\r\n\t\tpublic AnimationAsset(String id, AnimationSequence value) : base(typeof(AnimationSequence), id, value) { }\r\n\r\n\t\tpublic AnimationAsset(String id, Object value) : base(typeof(AnimationSequence), id, (AnimationSequence)value) { }\r\n\r\n\t\tpublic override string ToString() { return $\"({assetID}): Animation Asset of Type '{assetType}'\"; }\r\n\t}\r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.6899458169937134, "alphanum_fraction": 0.6935580968856812, "avg_line_length": 35.75, "blob_id": "df6126c32f3ac525eb7cdff6d99bbd4dd4dd7833", "content_id": "cdd355c1a77740e5332b50e021313d23a795a5e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 123, "num_lines": 44, "path": "/HollowAether/Lib/GAssets/Boundary/Container/Assistance/DeltaPositions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib.GAssets.Boundary {\r\n\tpublic struct DeltaPositions {\r\n\t\tpublic DeltaPositions(float deltaX, float deltaY, float deltaTop, float deltaBottom, float deltaLeft, float deltaRight) {\r\n\t\t\t_deltaX = deltaX;\r\n\t\t\t_deltaY = deltaY;\r\n\t\t\t_deltaLeft = deltaLeft;\r\n\t\t\t_deltaRight = deltaRight;\r\n\t\t\t_deltaTop = deltaTop;\r\n\t\t\t_deltaBottom = deltaBottom;\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"DeltaPosition: (W: {_deltaX}, H: {_deltaY}) T:{_deltaTop} L:{_deltaLeft} R:{_deltaRight} B:{_deltaBottom}\";\r\n\t\t}\r\n\r\n\t\tpublic static DeltaPositions Empty { get { return new DeltaPositions(0,0,0,0,0,0); } }\r\n\r\n\t\tprivate float _deltaX, _deltaY, _deltaTop, _deltaBottom, _deltaLeft, _deltaRight;\r\n\r\n\t\t/// <summary>Total change in width between boundary and spriteRect</summary>\r\n\t\tpublic float width { get { return _deltaX; } }\r\n\r\n\t\t/// <summary>Total change in height between boundary and spriterect</summary>\r\n\t\tpublic float height { get { return _deltaY; } }\r\n\r\n\t\t/// <summary>Change between top of boundary and top of spriterect</summary>\r\n\t\tpublic float top { get { return _deltaTop; } }\r\n\r\n\t\t/// <summary>Change between bottom of boundary and bottom of spriterect</summary>\r\n\t\tpublic float bottom { get { return _deltaBottom; } }\r\n\r\n\t\t/// <summary>Change between left of boundary and left of spriterect</summary>\r\n\t\tpublic float left { get { return _deltaLeft; } }\r\n\r\n\t\t/// <summary>Change between right of boundary and right of spriterect</summary>\r\n\t\tpublic float right { get { return _deltaRight; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7295364737510681, "alphanum_fraction": 0.7317554354667664, "avg_line_length": 29.6875, "blob_id": "ce2d06aed61ec3217e4a9ea72c77a2c0b88eaa5d", "content_id": "12799b476b43a631b6341c3136c4e33ded068b76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4058, "license_type": "no_license", "max_line_length": 119, "num_lines": 128, "path": "/HollowAether/HollowAether.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing SUM = HollowAether.StartUpMethods;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nusing GW = HollowAether.Lib.GameWindow;\r\n\r\nnamespace HollowAether {\r\n\tpublic class HollowAetherGame : Game {\r\n\t\tpublic HollowAetherGame() {\r\n\t\t\tgraphics = new GraphicsDeviceManager(this);\r\n\t\t\tContent.RootDirectory = \"Content\";\r\n\r\n\t\t\tGV.Variables.windowWidth = graphics.PreferredBackBufferWidth;\r\n\t\t\tGV.Variables.windowHeight = graphics.PreferredBackBufferHeight;\r\n\t\t\tGV.Variables.displayWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;\r\n\t\t\tGV.Variables.displayHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;\r\n\r\n\t\t\tFullScreenChanged = (newState) => { };\r\n\r\n\t\t\tFullScreenChanged += GW.Home.FullScreenReset;\r\n\t\t\tFullScreenChanged += GW.GameRunning.FullScreenReset;\r\n\t\t\tFullScreenChanged += GW.SaveLoad.FullScreenReset;\r\n\t\t\tFullScreenChanged += GW.Settings.FullScreenReset;\r\n\t\t\tFullScreenChanged += GW.PlayerDeceased.FullScreenReset;\r\n\t\t\tFullScreenChanged += GW.Settings.FullScreenReset;\r\n\t\t}\r\n\t\t\r\n\t\tprotected override void Initialize() {\r\n\t\t\tbase.Initialize();\r\n\t\t\t\r\n\t\t\tgod = new God();\r\n\t\t\tgod.Initialize();\r\n\r\n\t\t\tif (GV.FileIO.settingsManager.shouldBeFullScreen)\r\n\t\t\t\tIsFullScreen = true;\r\n\t\t}\r\n\r\n\t\tpublic void SetWindowDimensions(Vector2 XY) {\r\n\t\t\tSetWindowDimensions(X: (int)XY.X, Y: (int)XY.Y);\r\n\t\t}\r\n\r\n\t\tpublic void SetWindowDimensions(int X, int Y) {\r\n\t\t\tgraphics.PreferredBackBufferWidth = X;\r\n\t\t\tgraphics.PreferredBackBufferHeight = Y;\r\n\r\n\t\t\tGlobalVars.Variables.windowWidth = X;\r\n\t\t\tGlobalVars.Variables.windowHeight = Y;\r\n\r\n\t\t\tLib.GameWindow.GameWindows.WindowSizeChanged();\r\n\r\n\t\t\tCentreAlignWindow(); // always align \r\n\t\t\tgraphics.ApplyChanges(); // Save Changes\r\n\t\t}\r\n\r\n\t\tpublic void CentreAlignWindow() {\r\n\t\t\tif (graphics.IsFullScreen) { return; } // Would Throw Error but BLARG :)\r\n\r\n\t\t\tVector2 centerOfScreen = new Vector2(GlobalVars.Variables.displayWidth / 2, GlobalVars.Variables.displayHeight / 2);\r\n\t\t\tVector2 windowOffsetXY = new Vector2(GlobalVars.Variables.windowWidth / 2, GlobalVars.Variables.windowHeight / 2);\r\n\t\t\tWindow.Position = (centerOfScreen - windowOffsetXY).ToPoint(); // set centre position\r\n\t\t}\r\n\r\n\t\tpublic void ToggleFullScreen() {\r\n\t\t\tgraphics.ToggleFullScreen(); // Switch type\r\n\t\t\tif (!graphics.IsFullScreen) CentreAlignWindow();\r\n\t\t\tFullScreenChanged(graphics.IsFullScreen);\r\n\t\t}\r\n\r\n\t\tprotected override void LoadContent() {\r\n\t\t\tspriteBatch = new SpriteBatch(GraphicsDevice); // Built in, DO NOT REMOVE\r\n\r\n\t\t\tGV.Content.LoadContent();\r\n\r\n\t\t\t#region NonContentManagerContentDefinitions\r\n\t\t\tGV.MonoGameImplement.textures[\"debugFrame\"] = GV.TextureCreation.GenerateBlankTexture(Color.White);\r\n\t\t\tGV.MonoGameImplement.textures[\"tri\"] = GV.TextureCreation.GenerateBlankTexture(Color.Red);\r\n\t\t\t#endregion\r\n\t\t}\r\n\r\n\t\tprotected override void UnloadContent() {\r\n\t\t\tGV.MonoGameImplement.textures[\"debugFrame\"].Dispose();\r\n\t\t\tGV.MonoGameImplement.textures[\"tri\"].Dispose();\r\n\t\t}\r\n\t\t\r\n\t\tprotected override void Update(GameTime gameTime) {\r\n\t\t\tbase.Update(gameTime);\r\n\t\t\tgod.Update(gameTime);\r\n\t\t}\r\n\t\t\r\n\t\tprotected override void Draw(GameTime gameTime) {\r\n\t\t\tGraphicsDevice.Clear(Color.Blue);\r\n\t\t\t\r\n\t\t\tgod.Draw(); // Draw - pass to game\r\n\t\t\t\r\n\t\t\tbase.Draw(gameTime);\r\n\t\t}\r\n\r\n\t\tpublic GraphicsDeviceManager graphics;\r\n\t\tpublic SpriteBatch spriteBatch;\r\n\t\tpublic God god;\r\n\r\n\t\tpublic static event Action<bool> FullScreenChanged;\r\n\r\n\t\tpublic bool IsFullScreen { get { return graphics.IsFullScreen; } set {\r\n\t\t\tif (graphics.IsFullScreen != value) ToggleFullScreen();\r\n\t\t} }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6883424520492554, "alphanum_fraction": 0.6918032765388489, "avg_line_length": 30.294116973876953, "blob_id": "b36f494a455055a3ff4a77382960dd6c698f6374", "content_id": "31b562e7c20e2641bfa847e2419e354cfbc44344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5492, "license_type": "no_license", "max_line_length": 104, "num_lines": 170, "path": "/HollowAether/Lib/GAssets/Sprite.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Object which can be drawn to the screen and holds an animation</summary>\r\n\tpublic abstract partial class Sprite : IMonoGameObject {\r\n\t\tpublic Sprite() : this(new Vector2(), 0, 0, true) { }\r\n\r\n\t\tpublic Sprite(Vector2 position, int width, int height, bool animationRunning) {\r\n\t\t\tanimation = new Animation(position, width, height, animationRunning);\r\n\t\t}\r\n\r\n\t\t/// <summary>Initializes sprite with base properties</summary>\r\n\t\t/// <param name=\"textureKey\">Key of texture used alongside sprite</param>\r\n\t\tpublic virtual void Initialize(String textureKey) {\r\n\t\t\tBuildSequenceLibrary(); // Builds all animations used by sprite instance\r\n\r\n\t\t\ttry { animation.Initialize(textureKey); } catch (Exception e) {\r\n\t\t\t\tthrow new HollowAetherException($\"Entity '{SpriteID}' Animation Initialisation Exception\", e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Updates sprite</summary>\r\n\t\tpublic virtual void Update(bool updateAnimation) {\r\n\t\t\telapsedTime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds * (float)Math.Pow(10, -3);\r\n\t\t\telapsedMilitime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds; // Elapsed milleseconds\r\n\r\n\t\t\tif (updateAnimation) animation.Update(); // Updates animation when it should be, otherwise ignore\r\n\t\t}\r\n\r\n\t\t/// <summary>Update run immeadiately after first update</summary>\r\n\t\tpublic virtual void LateUpdate() { }\r\n\r\n\t\t/// <summary>Builds all animations used with sprite</summary>\r\n\t\t/// <remarks>Cannot be abstract because most work for sprite</remarks>\r\n\t\tprotected abstract void BuildSequenceLibrary();\r\n\r\n\t\t/// <summary>Draws Sprite to screen</summary>\r\n\t\tpublic virtual void Draw() { animation.Draw(); }\r\n\r\n\t\t/// <summary>Adds animation sequence to sprite</summary>\r\n\t\t/// <param name=\"key\">Key/ID of new animation sequence</param>\r\n\t\t/// <param name=\"sequence\">Sequence to add to sprite-store</param>\r\n\t\tpublic void AddAnimationSequence(String key, AnimationSequence sequence) {\r\n\t\t\tanimation.AddAnimationSequence(key, sequence);\r\n\t\t}\r\n\r\n\t\t/// <summary>Pushes sprite by a given vector</summary>\r\n\t\t/// <param name=\"offset\">offset</param>\r\n\t\tpublic virtual void OffsetSpritePosition(Vector2 offset) {\r\n\t\t\tanimation.position += offset;\r\n\t\t}\r\n\r\n\t\tpublic void OffsetSpritePosition(float X = 0, float Y = 0) {\r\n\t\t\tOffsetSpritePosition(new Vector2(X, Y));\r\n\t\t}\r\n\r\n\t\tpublic virtual void SetPosition(Vector2 nPos) {\r\n\t\t\tSetPosition(nPos.X, nPos.Y);\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets position to given new position</summary>\r\n\t\t/// <param name=\"nPos\">New position of sprite instance</param>\r\n\t\tpublic virtual void SetPosition(float? X = null, float? Y = null) {\r\n\t\t\tVector2 offset = new Vector2(\r\n\t\t\t\t(X.HasValue) ? X.Value - Position.X : 0,\r\n\t\t\t\t(Y.HasValue) ? Y.Value - Position.Y : 0\r\n\t\t\t);\r\n\r\n\t\t\tOffsetSpritePosition(offset);\r\n\t\t}\r\n\r\n\t\tpublic Point Size { get { return new Point(Width, Height); } }\r\n\r\n\t\t/// <summary>Attribute holding width of sprite</summary>\r\n\t\tpublic int Width {\r\n\t\t\tget { return animation.width; }\r\n\t\t\tset { animation.width = value; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Attribute holding height of sprite</summary>\r\n\t\tpublic int Height {\r\n\t\t\tget { return animation.height; }\r\n\t\t\tset { animation.height = value; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Layer of sprite within game</summary>\r\n\t\tpublic float Layer {\r\n\t\t\tget { return animation.layer; }\r\n\t\t\tset { animation.layer = value; }\r\n\t\t}\r\n\r\n\t\tpublic float Rotation {\r\n\t\t\tget { return animation.rotation; }\r\n\t\t\tset { animation.rotation = value; }\r\n\t\t}\r\n\r\n\t\tpublic float Scale {\r\n\t\t\tget { return animation.scale; }\r\n\t\t\tset { animation.scale = value; }\r\n\t\t}\r\n\r\n\t\tpublic Vector2 Origin {\r\n\t\t\tget { return animation.origin; }\r\n\t\t\tset { animation.origin = value; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Positional Rectangle of sprite</summary>\r\n\t\tpublic Rectangle SpriteRect {\r\n\t\t\tget { return animation.SpriteRect; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Sprites position in the game field</summary>\r\n\t\tpublic Vector2 Position {\r\n\t\t\tget { return animation.position; }\r\n\t\t\tset { SetPosition(value); }\r\n\t\t}\r\n\r\n\t\t/// <summary>Retrieves key of current animation sequence </summary>\r\n\t\tprotected String SequenceKey {\r\n\t\t\tget { return animation.sequenceKey; }\r\n\t\t\tset { animation.SetAnimationSequence(value); }\r\n\t\t}\r\n\r\n\t\t/// <summary>Name of texture for sprite</summary>\r\n\t\tpublic String TextureKey {\r\n\t\t\tget { return animation.TextureID; }\r\n\t\t\tprivate set { animation.TextureID = value; }\r\n\t\t}\r\n\t\t\r\n\t\tprotected Texture2D Texture {\r\n\t\t\tget { return GV.MonoGameImplement.textures[TextureKey]; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Animation of given sprite</summary>\r\n\t\tprivate Animation animation;\r\n\r\n\t\t/// <summary>Public accessor, with private modification priviliges for animation</summary>\r\n\t\tpublic Animation Animation {\r\n\t\t\tget { return animation; }\r\n\t\t\tprivate set { animation = value; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Time elapsed since last update</summary>\r\n\t\tprotected float elapsedTime;\r\n\r\n\t\tprotected int elapsedMilitime;\r\n\r\n\t\t/// <summary>ID of given sprite</summary>\r\n\t\tpublic String SpriteID { get; set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7017327547073364, "alphanum_fraction": 0.7037350535392761, "avg_line_length": 40.43463897705078, "blob_id": "454ea1a62d4c25a8486ee6ffd2428d318940846e", "content_id": "00779462291bc6fe81c32457b7f60e271b2d6699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12987, "license_type": "no_license", "max_line_length": 166, "num_lines": 306, "path": "/HollowAether/Lib/GAssets/Animation/Animation.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.InputOutput;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic class Animation {\r\n\t\t/// <summary>Assignment constructor</summary>\r\n\t\t/// <param name=\"_position\">Position of animation on screen</param>\r\n\t\t/// <param name=\"_width\">Width of animation on screen</param>\r\n\t\t/// <param name=\"_height\">Height of animation on screen</param>\r\n\t\t/// <param name=\"aRunning\">Whether animation is running</param>\r\n\t\t/// <param name=\"_textureID\">Reference to texture stored</param>\r\n\t\tAnimation(Vector2 _position, int _width, int _height, bool aRunning, String _textureID) {\r\n\t\t\tif (!String.IsNullOrWhiteSpace(_textureID))\r\n\t\t\t\tTextureID = _textureID;\r\n\r\n\t\t\tposition = _position;\r\n\t\t\tanimationRunning = aRunning;\r\n\t\t\twidth = _width;\r\n\t\t\theight = _height;\r\n\t\t}\r\n\r\n\t\t/// <summary>Animation from stored sequences passed as tuples</summary>\r\n\t\t/// <param name=\"_position\">Position of animation on screen</param>\r\n\t\t/// <param name=\"_width\">Width of animation on screen</param>\r\n\t\t/// <param name=\"_height\">Height of animation on screen</param>\r\n\t\t/// <param name=\"aRunning\">Whether animation is running</param>\r\n\t\t/// <param name=\"_textureID\">Reference to texture stored</param>\r\n\t\t/// <param name=\"sequences\">Key = sequence name, Value = actual sequence</param>\r\n\t\tpublic Animation(Vector2 _position, int _width=32, int _height=32, bool aRunning=true, String _textureID=null, params Tuple<String, AnimationSequence>[] sequences) \r\n\t\t\t: this(_position, _width, _height, aRunning, _textureID) {\r\n\r\n\t\t\tforeach (Tuple<String, AnimationSequence> sequence in sequences) {\r\n\t\t\t\tsequenceLibrary[sequence.Item1] = sequence.Item2;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Reads all sequences known from an animation file</summary>\r\n\t\t/// <param name=\"fPath\">Path to an animation file to read from</param>\r\n\t\tpublic static Dictionary<String, AnimationSequence> FromFile(String fPath) {\r\n\t\t\tif (!InputOutputManager.FileExists(fPath)) throw new AnimationFileNotFoundException(fPath);\r\n\r\n\t\t\tString _aniContents; // String to store the contents of the animation file once opened\r\n\t\t\tDictionary<String, AnimationSequence> container = new Dictionary<String, AnimationSequence>();\r\n\r\n\t\t\ttry {\r\n\t\t\t\t_aniContents = InputOutputManager.ReadEncryptedFile(fPath, GlobalVars.Encryption.oneTimePad).Replace(\"\\r\", \"\");\r\n\t\t\t} catch {\r\n\t\t\t\tthrow new AnimationFileNotFoundException(fPath); // Couldn't read animation file, therefore throw exception\r\n\t\t\t}\r\n\r\n\t\t\tif (!InputOutput.Parsers.Parser.HeaderCheck(_aniContents, FILE_HEADER))\r\n\t\t\t\tthrow new AnimationIncorrectHeaderException(fPath); // Map file doesn't have the correct header\r\n\r\n\t\t\tGV.Misc.RemoveComments(ref _aniContents); // remove comment notations from contents\r\n\t\t\tMatchCollection animations = Regex.Matches(_aniContents, \"\\\\\\\"[^ ]+\\\\\\\"[ {]+[^}]+\\\\}\");\r\n\r\n\t\t\tforeach (Match match in animations) {\r\n\t\t\t\tString regMatch = Regex.Match(match.Value, \"\\\\\\\"[^ ]+\\\\\\\"\").Value;\r\n\t\t\t\tString animName = regMatch.Substring(1, regMatch.Length - 2).Trim();\r\n\r\n\t\t\t\tcontainer.Add(animName, new AnimationSequence(0) { IsImported = true });\r\n\r\n\t\t\t\tString contMatch = Regex.Match(match.Value, \"\\\\{[^}]+\\\\}\").Value;\r\n\t\t\t\tString contents = contMatch.Substring(1, contMatch.Length - 2).Trim();\r\n\r\n\t\t\t\tforeach (String frameLine in contents.Split('\\n')) { // Frame Line\r\n\t\t\t\t\tif (!string.IsNullOrWhiteSpace(frameLine)) {\r\n\t\t\t\t\t\ttry { container[animName].AddFrame(Frame.FromFileContents(frameLine.Trim(' ', '\\t', '\\r'))); }\r\n\t\t\t\t\t\tcatch { Console.WriteLine($\"Warning, Couldn't Read Animation {fPath}\\\\{animName}\"); }\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn container;\r\n\t\t}\r\n\r\n\t\tprivate static IEnumerable<Match> YieldRegexMatchCollection(MatchCollection matched) {\r\n\t\t\tforeach (Match m in matched) yield return m;\r\n\t\t}\r\n\r\n\t\t/// <summary>Initialises used animation variables</summary>\r\n\t\t/// <param name=\"_textureID\">Reference to texture stored</param>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.AnimationException\">If texture not set or if sequence doesn't exist</exception>\r\n\t\tpublic void Initialize(String _textureID) {\r\n\t\t\tif (String.IsNullOrWhiteSpace(_textureID))\r\n\t\t\t\tthrow new AnimationException(\"Texture not set\");\r\n\t\t\telse TextureID = _textureID; // Set texture ID\r\n\r\n\t\t\tif (!sequenceLibrary.Keys.Contains(sequenceKey)) // Not texture exists\r\n\t\t\t\tthrow new AnimationException($\"Animation sequence '{sequenceKey}' doesn't exist\");\r\n\r\n\t\t\tcurrentFrame = CurrentSequence.GetFrame(false); // Set current frame, without increment\r\n\t\t}\r\n\r\n\t\tpublic String ToAnimationFile(String prefix=\"\") {\r\n\t\t\tStringBuilder builder = new StringBuilder($\"{FILE_HEADER}\\n\\n\"); // Holds animation details\r\n\r\n\t\t\tforeach (var tuple in sequenceLibrary) // Key value pair\r\n\t\t\t\tbuilder.Append(tuple.Value.ToFileContents(prefix+tuple.Key)+\"\\n\");\r\n\r\n\t\t\treturn builder.ToString();\r\n\t\t}\r\n\r\n\t\t/// <summary>Updates animation by moving to next sequence</summary>\r\n\t\tpublic void Update() {\r\n\t\t\tif (!animationRunning) return; // Animation isn't running, don't update\r\n\r\n\t\t\tif (frameRunCount < currentFrame.RunCount) { frameRunCount += 1; } else {\r\n\t\t\t\tif (ChainAttatched) {\r\n\t\t\t\t\tif (chain.Update()) currentFrame = chain.GetFrame(); else DeleteChain();\r\n\t\t\t\t\t// Chain no longer active, so set to null so can be deleted by GC\r\n\t\t\t\t} else currentFrame = CurrentSequence.GetFrame();\r\n\r\n\t\t\t\tframeRunCount = 1; // reset run count to minimum run count\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Deletes animation chain</summary>\r\n\t\tpublic void DeleteChain() {\r\n\t\t\tChainFinished(chain); // Event to call when chain has been completed\r\n\t\t\tchain = null; // Allocate chain for deletion by garbage collecter\r\n\t\t\tcurrentFrame = CurrentSequence.GetFrame(false); // Without update\r\n\t\t}\r\n\r\n\t\t/// <summary>Draws animation to canvas</summary>\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\ttexture:\t\t\t Texture, \r\n\t\t\t\tdestinationRectangle: SpriteRect, \r\n\t\t\t\tsourceRectangle:\t GetFrame().frame, \r\n\t\t\t\tcolor:\t\t\t\t Color.White * Opacity,\r\n\t\t\t\tlayerDepth:\t\t\t layer,\r\n\t\t\t\tscale: new Vector2(scale),\r\n\t\t\t\trotation: rotation, \r\n\t\t\t\torigin: origin\r\n\t\t\t);\r\n\r\n\t\t}\r\n\r\n\t\t/// <summary>Get current frame</summary>\r\n\t\t/// <returns>Current frame</returns>\r\n\t\tprivate Frame GetFrame() { return currentFrame; }\r\n\r\n\t\t/// <summary>Add sequence to current animation instance</summary>\r\n\t\t/// <param name=\"key\">Key for stored animation</param>\r\n\t\t/// <param name=\"sequence\">Sequence of animation</param>\r\n\t\tpublic void AddAnimationSequence(String key, AnimationSequence sequence) {\r\n\t\t\tsequenceLibrary[key] = sequence;\r\n\t\t}\r\n\r\n\t\t/// <summary>Overlays chain above animation</summary>\r\n\t\t/// <param name=\"_chain\">Chain to attatch</param>\r\n\t\tpublic void AttatchAnimationChain(AnimationChain _chain) {\r\n\t\t\tchain = _chain;\r\n\t\t\tChainLinked(chain);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks if sequence exists</summary>\r\n\t\t/// <param name=\"sequence\">Key of sequence</param>\r\n\t\tpublic bool SequenceExists(String sequence) {\r\n\t\t\treturn sequenceLibrary.ContainsKey(sequence);\r\n\t\t}\r\n\r\n\t\t/// /// <summary>Checks if sequence exists</summary>\r\n\t\t/// <param name=\"sequence\">Sequence instance</param>\r\n\t\tpublic bool SequenceExists(AnimationSequence sequence) {\r\n\t\t\treturn sequenceLibrary.ContainsValue(sequence);\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets animation sequence using sequence key from library</summary>\r\n\t\t/// <param name=\"key\">Key of animation to set sequence to. Can skip check using next arg.</param>\r\n\t\t/// <param name=\"skipCheck\">Doesnt bother to check if animation sequence exists, dangerous :(</param>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.AnimationException\">When sequence doesn't exist</exception>\r\n\t\tpublic void SetAnimationSequence(String key, bool skipCheck=false) {\r\n\t\t\tif (sequenceKey == key) return; // use reset when setting same\r\n\r\n\t\t\tif (!skipCheck && !sequenceLibrary.Keys.Contains(key))\r\n\t\t\t\tthrow new AnimationException($\"Key: \\\"{key}\\\" not found\");\r\n\r\n\t\t\tSequenceChanged(sequenceKey, key); // Event for when sequence has changed.\r\n\t\t\t\r\n\t\t\tif (CurrentSequenceExists) CurrentSequence.ResetSequence(); // Resets previous sequence\r\n\t\t\tsequenceKey = key; // Set new sequence key to over-write previous animation sequence\r\n\t\t\tcurrentFrame = CurrentSequence.GetFrame(false); // Assign new frame after assignment\r\n\t\t}\r\n\r\n\t\t/// <summary>Changes animation sequence</summary>\r\n\t\t/// <param name=\"sequence\">Sequence to set animation to</param>\r\n\t\tprivate void SetAnimationSequence(AnimationSequence sequence) {\r\n\t\t\tString newSequenceKey = GV.CollectionManipulator.DictionaryGetKeyFromValue(sequenceLibrary, sequence);\r\n\t\t\tSequenceChanged(sequenceKey, newSequenceKey); // Event for when sequence has changed.\r\n\r\n\t\t\tif (CurrentSequenceExists) CurrentSequence.ResetSequence(); // Resets previous sequence\r\n\t\t\tsequenceKey = newSequenceKey; // Assign new animation sequnece key\r\n\t\t\tcurrentFrame = CurrentSequence.GetFrame(false); // Assign new frame after assignment\r\n\t\t}\r\n\r\n\t\t/// <summary>Square bracket notation for adding sequences</summary>\r\n\t\t/// <param name=\"name\">Name of sequence to add to library</param>\r\n\t\tpublic AnimationSequence this[String name] {\r\n\t\t\tget { return sequenceLibrary[name]; }\r\n\t\t\tset { AddAnimationSequence(name, value); }\r\n\t\t}\r\n\r\n\t\t/// <summary>Whether chain is attatched to animation</summary>\r\n\t\tpublic bool ChainAttatched { get { return chain != null; } }\r\n\r\n\t\t/// <summary>Tries and returns animation texture if texture exists, else throws new exception</summary>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.AnimationException\">When texture doesn't exist</exception>\r\n\t\tprivate Texture2D Texture {\r\n\t\t\tget {\r\n\t\t\t\ttry { return GV.MonoGameImplement.textures[TextureID]; } // When exists return\r\n\t\t\t\tcatch { throw new AnimationException($\"Texture Key \\\"{TextureID}\\\" not found\"); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets current animation sequence using current sequence key from sequence library</summary>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.AnimationException\">When sequence doesn't exist</exception>\r\n\t\tpublic AnimationSequence CurrentSequence {\r\n\t\t\tget {\r\n\t\t\t\ttry { return sequenceLibrary[sequenceKey]; } // When sequence exists return it to user\r\n\t\t\t\tcatch { throw new AnimationException($\"Animation with Key:'{sequenceKey}' Not Found\"); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate bool CurrentSequenceExists {\r\n\t\t\tget { return sequenceLibrary.ContainsKey(sequenceKey); }\r\n\t\t}\r\n\r\n\t\t/// <summary>ID of texture used by animation</summary>\r\n\t\tpublic String TextureID { get; set; }\r\n\r\n\t\t/// <summary>Rectangle holding sprite when drawn onto screen</summary>\r\n\t\tpublic Rectangle SpriteRect { get { return new Rectangle(position.ToPoint(), new Point(width, height)); } }\r\n\r\n\t\t/// <summary>Keys of animation sequences in animation</summary>\r\n\t\tpublic String[] SequenceKeys { get { return sequenceLibrary.Keys.ToArray(); } }\r\n\r\n\t\t/// <summary>All sequences in animation</summary>\r\n\t\tpublic AnimationSequence[] Sequences { get { return sequenceLibrary.Values.ToArray(); } }\r\n\r\n\t\t/// <summary>Event to call when a sequence change has occured</summary>\r\n\t\tpublic event Action<String, String> SequenceChanged = (prev, next) => { };\r\n\r\n\t\t/// <summary>Event to call when chain has been added to animation</summary>\r\n\t\tpublic event Action<AnimationChain> ChainLinked = (chain) => { };\r\n\r\n\t\t/// <summary>Event to call when chain has been removed from animation</summary>\r\n\t\tpublic event Action<AnimationChain> ChainFinished = (chain) => { };\r\n\r\n\t\tpublic float Opacity { get; set; } = 1.0f;\r\n\r\n\t\t/// <summary>Chain which overlaps sequence</summary>\r\n\t\tprivate AnimationChain chain;\r\n\r\n\t\t/// <summary>Current frame for animation</summary>\r\n\t\tpublic Frame currentFrame;\r\n\r\n\t\tprivate int frameRunCount = 1;\r\n\r\n\t\t/// <summary>Position of frame on screen</summary>\r\n\t\tpublic Vector2 position;\r\n\r\n\t\t/// <summary>With and height of frame on screen</summary>\r\n\t\tpublic int width, height;\r\n\r\n\t\t/// <summary>Layer for animation</summary>\r\n\t\tpublic float layer = 0f;\r\n\r\n\t\tpublic float scale = 1f;\r\n\r\n\t\tpublic float rotation = 0f;\r\n\r\n\t\tpublic Vector2 origin = Vector2.Zero;\r\n\r\n\t\t/// <summary>Whether animation should update frames</summary>\r\n\t\tpublic bool animationRunning;\r\n\r\n\t\t/// <summary>Sequence key at start of animation</summary>\r\n\t\tpublic String sequenceKey = GV.MonoGameImplement.defaultAnimationSequenceKey;\r\n\r\n\t\t/// <summary>Sequences stored in animation. Accessible with String keys per sequence</summary>\r\n\t\tprivate Dictionary<String, AnimationSequence> sequenceLibrary = new Dictionary<String, AnimationSequence>();\r\n\r\n\t\tpublic const String FILE_HEADER = \"ANI\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 14.315789222717285, "blob_id": "6e150450ec4f59f6543c49f8b8c8cdc931c3a0ef", "content_id": "d4212734b414b0c357894da680395be7b078f316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 312, "license_type": "no_license", "max_line_length": 43, "num_lines": 19, "path": "/HollowAether/Lib/Interfaces/IDamage.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib {\r\n\tinterface IDamaging {\r\n\t\tint GetDamage();\r\n\t}\r\n\r\n\tinterface IDamagingToPlayer : IDamaging {\r\n\r\n\t}\r\n\r\n\tinterface IDamagingToEnemies : IDamaging {\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7020862102508545, "alphanum_fraction": 0.7123783230781555, "avg_line_length": 45.30263137817383, "blob_id": "5888cbef293c2a448180172e6e62c3f22f3257d8", "content_id": "e72ee2add460a217d5d8bbb9277fd113a88865e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7192, "license_type": "no_license", "max_line_length": 154, "num_lines": 152, "path": "/HollowAether/Lib/Misc/PushArgs.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/*public class PushArgs {\r\n\t\tpublic PushArgs(Vector2 newPos, Vector2 currentPos, float over, bool skipCheck = true) {\r\n\t\t\tif (!skipCheck && PushValid(newPos, currentPos)) // Invalid push\r\n\t\t\t\tthrow new HollowAetherException($\"One vector value must match\");\r\n\r\n\t\t\tpushingHorizontally = currentPos.X != newPos.X; // pushingVertically = !currentPos.Y != newPos.Y\r\n\r\n\t\t\tfloat maxDisplacement = (pushingHorizontally) ? currentPos.X - newPos.X : currentPos.Y - newPos.Y;\r\n\r\n\t\t\tpushPosition = newPos; // Store variables needed to push sprite in desired direction \r\n\t\t\tpushAcceleration = GV.Physics.CalculateGravity(maxDisplacement, over);\r\n\t\t\tpushVelocity = GV.Physics.GetJumpVelocity(pushAcceleration, maxDisplacement);\r\n\r\n\t\t\tif (pushAcceleration < 0 && pushVelocity < 0) pushVelocity = Math.Abs(pushVelocity);\r\n\t\t\telse if (pushAcceleration > 0 && pushVelocity > 0) pushVelocity = -pushVelocity;\r\n\t\t\t// If velocity and acceleration act in same direction, sprite will never stop travelling\r\n\r\n\t\t\tpushingDirection = (pushVelocity < 0) ? -1 : +1; // Determine which direction init displacement is\r\n\t\t\tPushCompleted = UponCompletion; // Default event handler needed for initialisation of push args\r\n\t\t\tSpriteOffset = (s, v) => { s.Position += v; }; // Event needs at least one handler\r\n\t\t\tSpriteSet = (s, v, o) => { s.Position = v; }; // Event needs at least one handler\r\n\t\t}\r\n\r\n\t\tprivate static void UponCompletion(IPushable _object, PushArgs self) { self.pushVelocity = 0; }\r\n\r\n\t\tpublic static bool PushValid(Vector2 newPos, Vector2 currentPos) {\r\n\t\t\treturn currentPos != newPos && (currentPos.X == newPos.X ^ currentPos.Y == newPos.Y);\r\n\t\t}\r\n\r\n\t\tpublic bool Update(IPushable self, float elapsedTime) {\r\n\t\t\tpushVelocity = (float)Math.Round(pushVelocity + (pushAcceleration * elapsedTime), 3);\r\n\r\n\t\t\tfloat displacement = (float)Math.Round(pushVelocity * elapsedTime, 5); // Store locally\r\n\r\n\t\t\tSpriteOffset(self, new Vector2(\r\n\t\t\t\t(pushingHorizontally) ? displacement : 0,\r\n\t\t\t\t(pushingHorizontally) ? 0 : displacement\r\n\t\t\t));\r\n\t\t\t\r\n\t\t\tif (pushVelocity == 0 || pushingDirection < 0 && pushVelocity > 0 || pushingDirection > 0 && pushVelocity < 0) {\r\n\t\t\t\t// If velocity has changed direction then Apex height reached\r\n\t\t\t\tSpriteSet(self, pushPosition, self.Position); PushCompleted(self, this);\r\n\t\t\t\treturn false; // Return false to allow caller to delete push args\r\n\t\t\t}\r\n\r\n\t\t\treturn true; // Push still valid/continuing thus return true\r\n\t\t}\r\n\r\n\t\tprivate float pushVelocity, pushAcceleration;\r\n\t\tprivate Vector2 pushPosition;\r\n\t\tprivate bool pushingHorizontally;\r\n\t\tprivate int pushingDirection;\r\n\r\n\t\tpublic event Action<IPushable, PushArgs> PushCompleted;\r\n\t\tpublic event Action<IPushable, Vector2> SpriteOffset;\r\n\t\tpublic event Action<IPushable, Vector2, Vector2> SpriteSet;\r\n\t}*/\r\n\r\n\tpublic class PushArgs {\r\n\t\tpublic PushArgs(Vector2 newPos, Vector2 currentPos, float over, bool skipCheck = true) {\r\n\t\t\tif (!skipCheck && PushValid(newPos, currentPos)) // Invalid push\r\n\t\t\t\tthrow new HollowAetherException($\"One vector value must match\");\r\n\r\n\t\t\tpushTarget = newPos; // Store final position sprite should've reached by the end\r\n\t\t\tVector2 positionDifference = currentPos - newPos; // Determine Width Height Travel\r\n\r\n\t\t\tfloat travelLength = (float)Math.Sqrt(Math.Pow(positionDifference.X, 2) + Math.Pow(positionDifference.Y, 2));\r\n\r\n\t\t\tdouble theta = Math.Atan2(positionDifference.Y, positionDifference.X);\r\n\t\t\tVector2 sinCosRatio = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));\r\n\r\n\t\t\tsinCosRatio.X = (float)Math.Round(sinCosRatio.X, 5); // In case of rounding error\r\n\t\t\tsinCosRatio.Y = (float)Math.Round(sinCosRatio.Y, 5); // In case of rounding error\r\n\r\n\t\t\tfloat scalarPushAcceleration = GV.Physics.CalculateGravity(travelLength, over); // acceleration\r\n\t\t\tfloat scalarPushVelocity = GV.Physics.GetJumpVelocity(scalarPushAcceleration, travelLength);\r\n\r\n\t\t\tpushAcceleration = sinCosRatio * scalarPushAcceleration; // Get acceleration with direction\r\n\t\t\tpushVelocity\t = sinCosRatio * scalarPushVelocity; // Get velocity with direction included\r\n\r\n\t\t\tpushVelocity.X = ((pushAcceleration.X < 0 && pushVelocity.X < 0) || (pushAcceleration.X > 0 && pushVelocity.X > 0)) ? -pushVelocity.X : pushVelocity.X;\r\n\t\t\tpushVelocity.Y = ((pushAcceleration.Y < 0 && pushVelocity.Y < 0) || (pushAcceleration.Y > 0 && pushVelocity.Y > 0)) ? -pushVelocity.Y : pushVelocity.Y;\r\n\r\n\t\t\tpushingDirection = new Vector2(\r\n\t\t\t\t(int)GV.BasicMath.Clamp<float>(pushVelocity.X, -1, 1),\r\n\t\t\t\t(int)GV.BasicMath.Clamp<float>(pushVelocity.Y, -1, 1)\r\n\t\t\t);\r\n\t\t\t\r\n\t\t\tPushCompleted = UponCompletion; // Default event handler needed for initialisation of push args\r\n\t\t\tSpriteOffset = (s, v) => { s.Position += v; }; // Event needs at least one handler\r\n\t\t\tSpriteSet = (s, v, o) => { s.Position = v; }; // Event needs at least one handler\r\n\t\t}\r\n\r\n\t\tpublic static bool PushValid(Vector2 newPos, Vector2 currentPos) {\r\n\t\t\treturn currentPos != newPos;\r\n\t\t}\r\n\r\n\t\tprivate void UponCompletion(IPushable _object, PushArgs self) { pushVelocity = Vector2.Zero; }\r\n\r\n\t\tpublic bool Update(IPushable self, float elapsedTime) {\r\n\t\t\tpushVelocity += pushAcceleration * elapsedTime;\r\n\r\n\t\t\tpushVelocity.X = (float)Math.Round(pushVelocity.X, 3);\r\n\t\t\tpushVelocity.Y = (float)Math.Round(pushVelocity.Y, 3);\r\n\r\n\t\t\tVector2 displacement = pushVelocity * elapsedTime;\r\n\r\n\t\t\tdisplacement.X = (float)Math.Round(displacement.X, 5);\r\n\t\t\tdisplacement.Y = (float)Math.Round(displacement.Y, 5);\r\n\r\n\t\t\tSpriteOffset(self, displacement);\r\n\r\n\t\t\tbool horizontallyChanged = !NotPushedHorizontally && DirectionChanged(pushVelocity.X, pushingDirection.X);\r\n\t\t\tbool verticallyChanged = !NotPushedVertically && DirectionChanged(pushVelocity.Y, pushingDirection.Y);\r\n\r\n\t\t\tif (horizontallyChanged) { pushingDirection.X = 0; pushVelocity.X = 0; pushAcceleration.X = 0; }\r\n\t\t\tif (verticallyChanged) { pushingDirection.Y = 0; pushVelocity.Y = 0; pushAcceleration.Y = 0; }\r\n\r\n\t\t\tif (pushVelocity == Vector2.Zero) {\r\n\t\t\t\tSpriteSet(self, pushTarget, self.Position); PushCompleted(self, this);\r\n\t\t\t\treturn false; // Return false to allow caller to delete push args\r\n\t\t\t} else return true; // Push Not yet finished\r\n\t\t}\r\n\r\n\t\tprivate static bool DirectionChanged(float velocity, float thrownDirection) {\r\n\t\t\treturn (velocity > 0 && thrownDirection < 0) || (velocity < 0 && thrownDirection > 0);\r\n\t\t}\r\n\r\n\t\tprivate bool NotPushedHorizontally { get { return pushingDirection.X == 0; } }\r\n\r\n\t\tprivate bool NotPushedVertically { get { return pushingDirection.Y == 0; } }\r\n\r\n\t\tprivate Vector2 pushTarget, pushVelocity, pushAcceleration, pushingDirection;\r\n\r\n\t\tpublic event Action<IPushable, PushArgs> PushCompleted;\r\n\t\tpublic event Action<IPushable, Vector2> SpriteOffset;\r\n\t\tpublic event Action<IPushable, Vector2, Vector2> SpriteSet;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7022035121917725, "alphanum_fraction": 0.7066590785980225, "avg_line_length": 38.87417221069336, "blob_id": "5dbcf7eaf5330d01a2b83a1a4c46588556a35301", "content_id": "0b26c35f94fec4d6de41c5bead48dee21ffed270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12346, "license_type": "no_license", "max_line_length": 139, "num_lines": 302, "path": "/HollowAether/Lib/Global/GameWindow/GameRunning.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.GAssets; // game assets\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GameWindow;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Debug;\r\nusing HollowAether.Lib.GAssets.Items;\r\nusing FC = HollowAether.Lib.GAssets.FX.ValueChangedEffect.FlickerColor;\r\nusing HollowAether.Lib.GAssets.FX;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tstatic class GameRunning {\r\n\t\tprivate static class EventHandlers {\r\n\t\t\t#region ItemAcquired\r\n\t\t\tpublic static void CoinAcquiredFX(Coin coin) {\r\n\t\t\t\tVector2 position = new Vector2(coin.SpriteRect.Right, coin.Position.Y); // Top right edge\r\n\r\n\t\t\t\tforeach (IMonoGameObject _object in ValueChangedEffect.Create(position, coin.Value, colors: new FC[] { FC.White, FC.Gold }))\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(_object); // Store object to global object store\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void BurstPointAcquiredFX(BurstPoint point) {\r\n\t\t\t\tVector2 position = new Vector2(point.SpriteRect.Right, point.Position.Y); // Top right edge\r\n\r\n\t\t\t\tforeach (IMonoGameObject _object in ValueChangedEffect.Create(position, point.Value, colors: FC.Blue))\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(_object); // Store object to global object store\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void GotItem(IItem item) {\r\n\t\t\t\tif (!(item is IMonoGameObject)) return; // Should be impossible, but u never know\r\n\r\n\t\t\t\tGAssets.HUD.ContextMenu.CreateText($\"{item.OutputString}#SYS:WAITFORINPUT;\");\r\n\t\t\t\tGV.MonoGameImplement.removalBatch.Add((IMonoGameObject)item); // Cast\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\t#region ZoneChangedEventHandlers\r\n\t\t\tpublic static void ZoneTransition(Vector2 oldZone, Vector2 newZone) {\r\n\t\t\t\tGAssets.Transition.CreateTransition();\r\n\r\n\t\t\t\t//GV.MonoGameImplement.monogameObjects.ClearAll();\r\n\t\t\t\tGameRunning.MoveZones(newZone); // Move zones\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\tpublic static void PlayerDead() {\r\n\t\t\t\tGV.MonoGameImplement.gameState = GameState.PlayerDeceased;\r\n\t\t\t\tGameWindow.PlayerDeceased.Reset(); // Reset dead game window\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic GameRunning() {\r\n\t\t\tBuildEventHandlers();\r\n\t\t\tDebugInit(); // Where map would go later\r\n\t\t\t// GV.MonoGameImplement.background = new Background();\r\n\t\t}\r\n\r\n\t\tprivate static void BuildEventHandlers() {\r\n\t\t\tGotItem = (item) => { };\r\n\t\t\tCoinAcquired = (coin) => { GV.MonoGameImplement.money += coin.Value; };\r\n\t\t\tBurstPointAcquired = (point) => { GV.MonoGameImplement.Player.AddBurstPoints(point.Value); };\r\n\t\t\tGotHealthPickup = (health) => { GV.MonoGameImplement.GameHUD.TryAddHealth(health.Value); };\r\n\t\t\tTransitionZone = (nZ, oZ) => { invokeTransitionZone = false; };\r\n\r\n\t\t\tTransitionZone += EventHandlers.ZoneTransition;\r\n\t\t\tGotItem += EventHandlers.GotItem;\r\n\t\t\tCoinAcquired += EventHandlers.CoinAcquiredFX;\r\n\t\t\tBurstPointAcquired += EventHandlers.BurstPointAcquiredFX;\r\n\r\n\t\t\tPlayerDeceased = EventHandlers.PlayerDead;\r\n\r\n\t\t\tPlayerDeceased += () => { Console.WriteLine(\"Deceased\"); };\r\n\t\t}\r\n\t\t\r\n\t\tpublic static void DebugInit() {\r\n\t\t\tGV.MonoGameImplement.textures.Add(\"angledTemp\", GV.TextureCreation.GenerateBlankTexture(Color.Red));\r\n\t\t\tGV.MonoGameImplement.textures.Add(\"blue\", GV.TextureCreation.GenerateBlankTexture(Color.Blue));\r\n\t\t\tGV.MonoGameImplement.textures.Add(\"green\", GV.TextureCreation.GenerateBlankTexture(Color.Green));\r\n\t\t\tGV.MonoGameImplement.textures.Add(\"pink\", GV.TextureCreation.GenerateBlankTexture(Color.HotPink));\r\n\t\t}\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\t// GV.MonoGameImplement.background.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch();\r\n\r\n\t\t\tGV.MonoGameImplement.Player.Draw();\r\n\r\n\t\t\tforeach (IMonoGameObject mgo in GV.MonoGameImplement.monogameObjects) mgo.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\r\n\t\t\tGV.MonoGameImplement.GameHUD.Draw();\r\n\r\n\t\t\tif (GAssets.HUD.ContextMenu.Active) GAssets.HUD.ContextMenu.Draw();\r\n\r\n\t\t\t#if DEBUG\r\n\t\t\tDebugPrinter.Set(\"Money\", GV.MonoGameImplement.money);\r\n\t\t\tDebugPrinter.Set(\"Position\", GV.MonoGameImplement.Player.Position);\r\n\t\t\tDebugPrinter.Set(\"CameraPosition\", GV.MonoGameImplement.camera.Position);\r\n\t\t\tDebugPrinter.Set(\"BurstPoints\", GV.MonoGameImplement.Player.burstPoints);\r\n\t\t\tDebugPrinter.Set(\"ObjectsCount\", GV.MonoGameImplement.monogameObjects.Length);\r\n\t\t\tDebugPrinter.Set(\"BurstPointWait\", Math.Round(GV.MonoGameImplement.Player.timeNotMoving, 3));\r\n\r\n\t\t\tIMonoGameObject[] collided = GV.MonoGameImplement.Player.CompoundIntersects();\r\n\t\t\tDebugPrinter.Set(\"Intersected\", (collided.Length > 0) ? (from X in collided select X.SpriteID).Aggregate((a, b) => $\"{a}, {b}\") : null);\r\n\t\t\tDebug.DebugPrinter.Draw(); // Draw\r\n\t\t\t#endif\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() {\r\n\r\n\t\t} // ignore for now.\r\n\r\n\t\tpublic static void Update() {\r\n\t\t\tif (GV.PeripheralIO.ImplementWaitForInputToBeRemoved(ref WaitForInputToBeRemoved))\r\n\t\t\t\treturn; // If Still Waiting For Input Retrieval Then Return B4 Update\r\n\r\n\t\t\tif (GV.PeripheralIO.currentControlState.Pause) {\r\n\t\t\t\tGV.MonoGameImplement.gameState = GameState.GamePaused;\r\n\t\t\t\tGameWindow.GamePaused.WaitForInputToBeRemoved = true;\r\n\t\t\t} else {\r\n\t\t\t\telapsedGameTime += GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t\tbool updateAnimation = elapsedGameTime >= GV.MonoGameImplement.MilisecondsPerFrame;\r\n\t\t\t\tif (updateAnimation) elapsedGameTime = 0; // Reset animation update counter\r\n\r\n\t\t\t\tif (GAssets.HUD.ContextMenu.Active) { GAssets.HUD.ContextMenu.Update(); } else {\r\n\t\t\t\t\tGV.MonoGameImplement.Player.Update(updateAnimation);\r\n\r\n\t\t\t\t\tforeach (IMonoGameObject mgo in GV.MonoGameImplement.monogameObjects) {\r\n\t\t\t\t\t\tmgo.Update(updateAnimation);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tGV.MonoGameImplement.Player.LateUpdate();\r\n\r\n\t\t\t\t\tforeach (IMonoGameObject mgo in GV.MonoGameImplement.monogameObjects) {\r\n\t\t\t\t\t\tmgo.LateUpdate();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t// GV.MonoGameImplement.background.Update();\r\n\r\n\t\t\t\t\tGV.MonoGameImplement.removalBatch.Execute(); // Remove any allocated sprites\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.Execute(); // Add any designated sprites\r\n\r\n\t\t\t\t\tGV.MonoGameImplement.camera.Update(); // camera has to monitor player\r\n\t\t\t\t\tGV.MonoGameImplement.GameHUD.Update(updateAnimation); // HUD has to maintain position\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (PlayerExitedZoneRegion()) {\r\n\t\t\t\t\tVector2? adjacent = GV.MonoGameImplement.map.ZoneExistsAdjacentTo(GV.MonoGameImplement.map.Index);\r\n\r\n\t\t\t\t\tif (!adjacent.HasValue) { PlayerDeceased(); /*Kill when no where to fall to*/ } else {\r\n\t\t\t\t\t\tVector2 playerPos = GV.MonoGameImplement.Player.Position; // Get player position\r\n\t\t\t\t\t\tPoint playerSize = GV.MonoGameImplement.Player.Size; // Get player size\r\n\r\n\t\t\t\t\t\tbool wentLeft = playerPos.X + playerSize.X < 0;\r\n\t\t\t\t\t\tbool wentRight = playerPos.X > GV.MonoGameImplement.map.CurrentZone.ZoneWidth;\r\n\t\t\t\t\t\tbool wentUp = playerPos.Y + playerSize.Y < 0;\r\n\t\t\t\t\t\tbool wentDown = playerPos.Y > GV.MonoGameImplement.map.CurrentZone.ZoneHeight;\r\n\r\n\t\t\t\t\t\tVector2 current = GV.MonoGameImplement.map.Index, newZone;\r\n\r\n\t\t\t\t\t\tif (wentLeft) newZone = new Vector2(current.X-1, current.Y);\r\n\t\t\t\t\t\telse if (wentRight) newZone = new Vector2(current.X+1, current.Y);\r\n\t\t\t\t\t\telse if (wentUp) newZone = new Vector2(current.X, current.Y-1);\r\n\t\t\t\t\t\telse if (wentDown) newZone = new Vector2(current.X, current.Y+1);\r\n\t\t\t\t\t\telse { PlayerDeceased(); return; } // Should be IMPOSSIBLE\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (!GV.MonoGameImplement.map.ContainsZone(newZone)) PlayerDeceased(); else {\r\n\t\t\t\t\t\t\tEventHandlers.ZoneTransition(current, newZone);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (invokeTransitionZone) InvokeTransitionZone();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static bool PlayerExitedZoneRegion() {\r\n\t\t\tVector2 position = GV.MonoGameImplement.Player.Position; // Get player position\r\n\r\n\t\t\tif (GV.MonoGameImplement.map.CurrentZone.Contains(position)) return false; else {\r\n\t\t\t\tif (position.X >= 0 && position.Y >= 0) return true; else { // \r\n\t\t\t\t\tPoint size = GV.MonoGameImplement.Player.Size;\r\n\r\n\t\t\t\t\tVector2 adjustedPosition = new Vector2() {\r\n\t\t\t\t\t\tX = position.X + (position.X < 0 ? size.X : 0),\r\n\t\t\t\t\t\tY = position.Y + (position.Y < 0 ? size.Y : 0)\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\treturn !GV.MonoGameImplement.map.CurrentZone.Contains(adjustedPosition);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void InvokeTransitionZone() {\r\n\t\t\tif (!transitionZoneEventArg_New.HasValue)\r\n\t\t\t\tthrow new HollowAetherException($\"Tranisition allocated, but no target set\");\r\n\r\n\t\t\tTransitionZone(GV.MonoGameImplement.map.Index, transitionZoneEventArg_New.Value);\r\n\t\t}\r\n\r\n\t\tpublic static void LoadSave(int slotIndex) {\r\n\t\t\tSaveManager.SaveFile save = SaveManager.GetSave(slotIndex);\r\n\t\t\t\r\n\t\t\tGV.MonoGameImplement.saveIndex = slotIndex; // Store save index\r\n\r\n\t\t\tMoveZones(save.currentZone);\r\n\t\t\t\r\n\t\t\tGV.MonoGameImplement.Player.Position = save.playerPosition;\r\n\r\n\t\t\tGV.MonoGameImplement.GameHUD.SetHeartCount(save.heartCount);\r\n\t\t\tGV.MonoGameImplement.GameHUD.SetHealth(save.health);\r\n\r\n\t\t\tGV.MonoGameImplement.Player.ImplementPerks(save.perks);\r\n\r\n\t\t\tforeach (Tuple<String, bool> flagChange in save.flags) {\r\n\t\t\t\tFlagAsset flag = GV.MapZone.GetFlagAsset(flagChange.Item1);\r\n\r\n\t\t\t\tif (!(flag.asset as Flag).ValueChangedFromDefault())\r\n\t\t\t\t\t(flag.asset as Flag).ChangeFlag(flagChange.Item2);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void FullScreenReset(bool isFullScreen) {\r\n\t\t\tif (GV.MonoGameImplement.gameState == GameState.GameRunning) Reset();\r\n\t\t}\r\n\r\n\t\tprivate static void MoveZones(Vector2 newZone) {\r\n\t\t\tGV.MapZone.globalAssets[\"playerStartPosition\"].Delete();\r\n\r\n\t\t\tVector2 zoneDifference = newZone - GV.MonoGameImplement.map.Index;\r\n\r\n\t\t\tGV.MonoGameImplement.map.SetCurrentZone(newZone, false, true); // Could assign new player position\r\n\r\n\t\t\t#region PlayerPositionAssignment\r\n\t\t\tVector2 newPlayerPosition = Vector2.Zero; //GV.MonoGameImplement.Player.Position; // By default push to Vector2\r\n\r\n\t\t\tif (GV.MapZone.globalAssets[\"playerStartPosition\"].asset != null) {\r\n\t\t\t\tnewPlayerPosition = (Vector2)GV.MapZone.globalAssets[\"playerStartPosition\"].GetValue();\r\n\t\t\t} else if (Math.Abs(zoneDifference.X) == 1 ^ Math.Abs(zoneDifference.Y) == 1) {\r\n\t\t\t\tVector2 zoneDimensions = GV.MonoGameImplement.map.CurrentZone.XSize;\r\n\r\n\t\t\t\tif (zoneDifference.X > 1) newPlayerPosition.X = 0; // Default Anyway but leave for lack of better option\r\n\t\t\t\telse if (zoneDifference.X < 1) newPlayerPosition.X = zoneDimensions.X - GV.MonoGameImplement.Player.Width;\r\n\r\n\t\t\t\t/*if (zoneDifference.Y > 1) newPlayerPosition.Y = 0; // Default anyway, but leave for lack of better option\r\n\t\t\t\telse if (zoneDifference.Y < 1) newPlayerPosition.Y = zoneDimensions.Y - GV.MonoGameImplement.Player.Height;*/\r\n\t\t\t}\r\n\r\n\t\t\tGV.MonoGameImplement.Player.SetPosition(newPlayerPosition);\r\n\t\t\t#endregion\r\n\r\n\t\t\tGV.MonoGameImplement.Player.interaction_timeout = 500; // Add Timeout\r\n\t\t}\r\n\r\n\t\t#region EventStuff\r\n\t\tpublic static void InvokePlayerDeceased() { PlayerDeceased(); }\r\n\r\n\t\tpublic static void InvokeCoinAcquired(Coin coin) { CoinAcquired(coin); }\r\n\r\n\t\tpublic static void InvokeBurstPointAcquired(BurstPoint point) { BurstPointAcquired(point); }\r\n\r\n\t\tpublic static void InvokeGotHealthPickup(HealthPickup pickup) { GotHealthPickup(pickup); }\r\n\r\n\t\tpublic static void InvokeGotItem(IItem item) { GotItem(item); }\r\n\r\n\t\tpublic static event Action PlayerDeceased;\r\n\t\tpublic static event Action<Coin> CoinAcquired;\r\n\t\tpublic static event Action<BurstPoint> BurstPointAcquired;\r\n\t\tpublic static event Action<IItem> GotItem;\r\n\t\tpublic static event Action<HealthPickup> GotHealthPickup;\r\n\t\tpublic static event Action<Vector2, Vector2> TransitionZone;\r\n\r\n\t\tpublic static bool invokeTransitionZone = false;\r\n\t\tpublic static Vector2? transitionZoneEventArg_New;\r\n\t\t#endregion\r\n\r\n\t\tstatic int elapsedGameTime;\r\n\r\n\t\tpublic static bool WaitForInputToBeRemoved = false;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7081561088562012, "alphanum_fraction": 0.7107082009315491, "avg_line_length": 37.3472785949707, "blob_id": "ec653055b41531ff272710246c6fdc080ad14e50", "content_id": "b479a9125c350c2f62c40f4f685db38d3700b5ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 18810, "license_type": "no_license", "max_line_length": 129, "num_lines": 478, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/ZoneEditor.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing System.Drawing.Imaging;\r\nusing System.Drawing.Drawing2D;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.GAssets;\r\nusing System.Text.RegularExpressions;\r\nusing V2 = Microsoft.Xna.Framework.Vector2;\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class ZoneEditor : Form {\r\n\t\tpublic enum CustomSelectionRectBuilderTypes { EntityWrapper, TileHighliter, None }\r\n\r\n\t\t/// <summary>Constructs a new zone editor</summary>\r\n\t\tpublic ZoneEditor(Zone zoneInstance) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tSize = sizeBeforeResize = MinimumSize; // Set size to initial size\r\n\r\n\t\t\tentityTypeComboBox.Items.AddRange(GV.EntityGenerators.entityTypes.Keys.ToArray());\r\n\t\t\tentityTypeComboBox.SelectedIndex = 0; // Select First Entity In Entity Combo Box\r\n\r\n\t\t\t#region BuildControls\r\n\t\t\tzoneCanvasPanel.Controls.Add(canvas);\r\n\r\n\t\t\ttileBox.Width = tileBoxContainerPanel.Width;\r\n\t\t\ttileBox.Height = tileBoxContainerPanel.Height;\r\n\r\n\t\t\ttileBox.HaveErrorIndicator = false;\r\n\r\n\t\t\ttileBoxContainerPanel.Controls.Add(tileBox);\r\n\t\t\t#endregion\r\n\r\n\t\t\tAddEventHandlers(); // Set Event Handlers\r\n\t\t\tshowTileMapButton_Click(this, null);\r\n\r\n\t\t\tif (zoneInstance != null) Initialize(zoneInstance); // Init zone\r\n\t\t}\r\n\r\n\t\tprivate void ZoneEditor_Load(object sender, EventArgs e) {\r\n\t\t\t// clickRadioButton.Checked = true;\r\n\t\t}\r\n\r\n\t\t~ZoneEditor() { }\r\n\r\n\t\t/// <summary>Builds event handlers for form variables</summary>\r\n\t\tprivate void AddEventHandlers() {\r\n\t\t\tentityTypeComboBox.MouseWheel += (s, e) => { ((HandledMouseEventArgs)e).Handled = true; };\r\n\r\n\t\t\tGV.LevelEditor.tileMap.FormClosing += (s, e) => { tileBox.DrawTile = false; };\r\n\r\n\t\t\tGV.LevelEditor.tileMap.Shown += (s, e) => { tileBox.DrawTile = true; };\r\n\r\n\t\t\tGV.LevelEditor.tileMap.ReShown += (s) => { tileBox.DrawTile = true; };\r\n\r\n\t\t\tGV.LevelEditor.tileMap.canvas.BuildSelectionRect += (t, e) => {\r\n\t\t\t\tRectangleF r = e.currentRectangle; // Store current rectangle\r\n\r\n\t\t\t\ttileBox.AssignTextureAndRect(\r\n\t\t\t\t\tGV.LevelEditor.tileMap.CurrentImage, // Assign current image\r\n\t\t\t\t\tnew Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height)\r\n\t\t\t\t);\r\n\t\t\t};\r\n\r\n\t\t\tcanvas.DrawToCanvas += DrawBackground_DrawToCanvas;\r\n\t\t\tcanvas.DrawToCanvas += DrawTiles_DrawToCanvas;\r\n\t\t\t\r\n\t\t\tcanvas.BuildSelectionRect += BuildSelectionRect_TileHighliter_RectBuilderEventHandler;\r\n\t\t\tcanvas.ClickBegun\t\t += CanvasClickBegun_TileHighliter_MouseBasedEventHandler;\r\n\t\t\tcanvas.ClickComplete\t += CanvasClickComplete_TileHighligter_MouseBasedEventHandler;\r\n\r\n\t\t\tcanvas.BuildSelectionRect += BuildSelectionRect_EntityWrapper_RectBuilderEventHandler;\r\n\t\t\t//canvas.ClickBegun\t\t += CanvasClickBegun_EntityWrapper_MouseBasedEventHandler;\r\n\t\t\t//canvas.ClickComplete\t += CanvasClickComplete_EntityWrapper_MouseBasedEventHandler;\r\n\r\n\t\t\tcanvas.CanvasRegionExecute += CanvasRegionExecute_MouseBasedEventHandler;\r\n\t\t}\r\n\r\n\t\t/// <summary>Initializes and builds zone assets from a given zone instance</summary>\r\n\t\t/// <param name=\"zoneInstance\">Instance of a zone file with which to build editor</param>\r\n\t\tpublic void Initialize(Zone zoneInstance) {\r\n\t\t\tcanvas.SetWidth(zoneInstance.ZoneWidth);\r\n\t\t\tcanvas.SetHeight(zoneInstance.ZoneHeight);\r\n\r\n\t\t\tzone = zoneInstance; // Store zone to editor instance\r\n\t\t\tSize = sizeBeforeResize = MinimumSize;\r\n\r\n\t\t\ttiles.Clear(); // Delete all current tiles\r\n\r\n\t\t\tforeach (var entity in zone.zoneEntities) {\r\n\t\t\t\tvar tile = new EntityTile(entity.Value);\r\n\t\t\t\ttiles.Add(entity.Key, tile); // store tile\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region EventHandlers\r\n\t\t/// <summary>Default event handler for when the template entity type is changed</summary>\r\n\t\tprivate void entityTypeComboBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tSetTemplateEntity(GV.EntityGenerators.StringToGameEntity(entityTypeComboBox.SelectedItem.ToString()));\r\n\t\t}\r\n\r\n\t\t/// <summary>Disposes of any unnecessary assets and resets tilemap rects</summary>\r\n\t\tprivate void ZoneEditor_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\t// Check if save, then save\r\n\t\t\tif (canvasChanged) {\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\"Editor Canvas Has Changed, Would You Like To Save Before Closing\",\r\n\t\t\t\t\t\"Warning\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result == DialogResult.Yes) saveToolStripMenuItem_Click(sender, e);\r\n\t\t\t\telse if (result == DialogResult.Cancel) e.Cancel = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void layerTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tfloat? newValue = GV.Misc.StringToFloat(layerTextBox.Text); // Convert\r\n\r\n\t\t\tif (newValue.HasValue) newValue = newValue.Value; else newValue = null;\r\n\t\t}\r\n\r\n\t\tprivate void DrawTiles_DrawToCanvas(object sender, PaintEventArgs e) {\r\n\t\t\tEntityTile[] collection = tiles.Values.ToArray(), trimmedCollection; // Get all tiles within current zone and cast to array\r\n\r\n\t\t\tif (DrawOnlyCurrentEntity) collection = (from X in collection where X.EntityType == CurrentEntityType select X).ToArray();\r\n\t\t\t// If draw only current entity, then trim collection to only entities of a type corresponding to the entity type of the editor\r\n\r\n\t\t\tif (SelectedLayer.HasValue) { // Only draw values which approximate to a given value\r\n\t\t\t\tFunc<EntityTile, bool> ApproximatelyEqual = (tile) => Math.Abs(tile.Layer - SelectedLayer.Value) < 0.05;\r\n\t\t\t\ttrimmedCollection = (from X in collection where ApproximatelyEqual(X) select X).ToArray(); // Within range\r\n\t\t\t} else {\r\n\t\t\t\tArray.Sort(collection, (a, b) => a.Layer.CompareTo(b.Layer));\r\n\t\t\t\ttrimmedCollection = collection; // Set trimmed to sorted array\r\n\t\t\t}\r\n\r\n\t\t\tforeach (EntityTile tile in trimmedCollection) { tile.Paint(e); } // Draw all tiles\r\n\t\t}\r\n\r\n\t\tprivate void DrawBackground_DrawToCanvas(object sender, PaintEventArgs e) {\r\n\t\t\t// throw new NotImplementedException();\r\n\t\t}\r\n\r\n\t\t#region CheckBoxChange\r\n\t\t/// <summary>Thrown when user decides to show or disable the grid on the editor</summary>\r\n\t\tprivate void tileGridCheckBox_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.DrawGrid = tileGridCheckBox.Checked;\r\n\t\t}\r\n\r\n\t\t/// <summary>Thrown when user decides to show or disable the background image on the editor</summary>\r\n\t\tprivate void backgroundCheckBox_CheckedChanged(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\t/// <summary>Thrown when the user decides to only show the current entity type on the screen</summary>\r\n\t\tprivate void onlyCurrentEntityCheckBox_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Draw(); // Re invoke\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region ZoomChange\r\n\t\t/// <summary>Sets zoom to 0.5 or 1/2</summary>\r\n\t\tprivate void xHalfToolStripMenuItem_Click(object sender, EventArgs e) { Zoom = 0.5f; }\r\n\r\n\t\t/// <summary>Sets zoom to 1</summary>\r\n\t\tprivate void oneXZoomMenuItem_Click(object sender, EventArgs e) { Zoom = 1f; }\r\n\r\n\t\t/// <summary>Sets zoom to 2</summary>\r\n\t\tprivate void twoXZoomMenuItem_Click(object sender, EventArgs e) { Zoom = 2f; }\r\n\r\n\t\t/// <summary>Sets zoom to 3</summary>\r\n\t\tprivate void threeXZoomMenuItem_Click(object sender, EventArgs e) { Zoom = 3f; }\r\n\r\n\t\t/// <summary>Sets zoom to 4</summary>\r\n\t\tprivate void fourXZoomMenuItem_Click(object sender, EventArgs e) { Zoom = 4f; }\r\n\r\n\t\t/// <summary>Sets zoom to 0.5 or 1/2</summary>\r\n\t\tprivate void zoomSubMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tfloat value = SetZoomDialog.GetZoom(Zoom, MIN_ZOOM, MAX_ZOOM);\r\n\r\n\t\t\tif (value != Zoom) Zoom = value; // Set zoom to new arg value\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region ClickHandlers\r\n\t\t/// <summary>Opens a new script editor form with current zone</summary>\r\n\t\tprivate void editScriptButton_Click(object sender, EventArgs e) {\r\n\t\t\tnew ScriptEditor(zone.FilePath, true, true).Show();\r\n\t\t}\r\n\r\n\t\tprivate void saveToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tInputOutput.InputOutputManager.WriteEncryptedFile(zone.FilePath, CanvasToFile(), GV.Encryption.oneTimePad);\r\n\t\t}\r\n\r\n\t\t/// <summary>Gives focus to existing tile map or creates new tile map form</summary>\r\n\t\tprivate void showTileMapButton_Click(object sender, EventArgs e) {\r\n\t\t\tif (!GV.LevelEditor.tileMap.Visible) {\r\n\t\t\t\tGV.LevelEditor.tileMap.Show(); // Shows tile map\r\n\r\n\t\t\t\tif (GV.LevelEditor.tileMap.canvas.SelectRect == Rectangle.Empty) {\r\n\t\t\t\t\tGV.LevelEditor.tileMap.canvas.ExternalSetSelectionRect(new RectangleF(0, 0, 32, 32));\r\n\t\t\t\t}\r\n\r\n\t\t\t\tRectangleF r = GV.LevelEditor.tileMap.canvas.SelectRect;\r\n\r\n\t\t\t\ttileBox.AssignTextureAndRect(\r\n\t\t\t\t\tGV.LevelEditor.tileMap.CurrentImage, // Assign current image\r\n\t\t\t\t\tnew Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height)\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Zooms canvas in by half times default</summary>\r\n\t\tprivate void zoomInButton_Click(object sender, EventArgs e) { Zoom += 1; }\r\n\r\n\t\t/// <summary>Zooms canvas out by half times default</summary>\r\n\t\tprivate void zoomOutButton_Click(object sender, EventArgs e) { Zoom -= 1; }\r\n\r\n\t\t/// <summary>Opens template tile edit menu</summary>\r\n\t\tprivate void openEditMenu_Click(object sender, EventArgs e) {\r\n\t\t\tvar dialogResult = EditEntityView.RunForTemplateEntity(templateGameEntity, zone);\r\n\r\n\t\t\tif (dialogResult.state == EditEntityView.ReturnState.Changed) {\r\n\t\t\t\tSetTemplateEntity(dialogResult.updatedEntity);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Views all built in assets used by the program</summary>\r\n\t\tprivate void viewAssetsButton_Click(object sender, EventArgs e) {\r\n\t\t\tassetViewToolStripMenuItem_Click(sender, e);\r\n\t\t}\r\n\r\n\t\t/// <summary>Resets default template tile to builtin version</summary>\r\n\t\tprivate void resetEntityButton_Click(object sender, EventArgs e) {\r\n\t\t\tentityTypeComboBox_TextChanged(sender, e);\r\n\t\t}\r\n\r\n\t\tprivate void resizeZoneButton_Click(object sender, EventArgs e) {\r\n\t\t\tsetZoneSizeToolStripMenuItem_Click(sender, e);\r\n\t\t}\r\n\r\n\t\t/// <summary>Executes click for non generic click in zone canvas</summary>\r\n\t\tprivate void ExecuteButton_Click(object sender, EventArgs e) {\r\n\t\t\tcanvas.InvokeCanvasRegionExecuteForHighlitedSelectionRects();\r\n\t\t}\r\n\r\n\t\tprivate void setBackgroundToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\tprivate void assetViewToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tif (!AssetView.Open) { // Then Open New View\r\n\t\t\t\tAssetView view = new AssetView(zone);\r\n\r\n\t\t\t\tview.saveButton.Click += (s, e2) => {\r\n\t\t\t\t\tcanvasChanged = true;\r\n\t\t\t\t};\r\n\r\n\t\t\t\tview.Show();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void setZoneSizeToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tTuple<int, int> results = SetZoneDimensions.Run(zone.FilePath, zone.ZoneWidth, zone.ZoneHeight);\r\n\t\t\tSize newSize = new Size() { Width = results.Item1, Height = results.Item2 }; // To Size Instance\r\n\r\n\t\t\tif (newSize != zone.Size) { // If size has changed\r\n\t\t\t\tif (newSize.Width < zone.ZoneWidth || newSize.Height < zone.ZoneHeight) {\r\n\t\t\t\t\tRectangle newZoneDimensions = new Rectangle() { Location = new Point(0, 0), Size = newSize }; // New Region\r\n\r\n\t\t\t\t\tvar clipped = (from X in tiles where !X.Value.Region.IntersectsWith(newZoneDimensions) select X).ToArray();\r\n\r\n\t\t\t\t\tif (clipped.Length > 0) {\r\n\t\t\t\t\t\tstring num = clipped.Length.ToString().PadLeft(3, '0');\r\n\r\n\t\t\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\t\t$\"{num} Tiles Will Be Clipped To Do This. Are You Sure?\", \"Warning\",\r\n\t\t\t\t\t\t\tMessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation // Triangle!\r\n\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\tif (result != DialogResult.Yes) return; // User has canceled zone resize\r\n\r\n\t\t\t\t\t\tforeach (KeyValuePair<String, EntityTile> entityKVP in clipped) {\r\n\t\t\t\t\t\t\tDeleteTile(entityKVP.Key, false); // Deletes Tile\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (newSize.Width != zone.ZoneWidth) { zone.ZoneWidth = newSize.Width; canvas.SetWidth(newSize.Width); }\r\n\t\t\t\tif (newSize.Height != zone.ZoneHeight) { zone.ZoneHeight = newSize.Height; canvas.SetHeight(newSize.Height); }\r\n\r\n\t\t\t\tcanvasChanged = true; // Check to save before closing\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\t#region NotEventHandlers\r\n\r\n\t\t#region TileMethods\r\n\t\t/// <summary>Adds an entity to the zone and canvas</summary>\r\n\t\t/// <param name=\"key\">Key for new tile to add</param>\r\n\t\t/// <param name=\"entity\">Entity to add to canvas</param>\r\n\t\tprivate void AddEntity(string key, GameEntity entity, bool redraw = true) {\r\n\t\t\tzone.zoneEntities.Add(key, entity);\r\n\t\t\tvar tile = new EntityTile(entity);\r\n\t\t\ttiles.Add(key, tile);\r\n\r\n\t\t\tcanvasChanged = true; // Check to save before closing\r\n\r\n\t\t\tif (redraw) canvas.Draw();\r\n\t\t}\r\n\r\n\t\tprivate void AddEntity(GameEntity entity, int idLength=10, bool redraw=true) {\r\n\t\t\tString key; // Id for newly defined tile\r\n\r\n\t\t\tdo {\r\n\t\t\t\tkey = GV.Misc.GenerateRandomString(idLength);\r\n\t\t\t} while (tiles.ContainsKey(key));\r\n\r\n\t\t\tAddEntity(key, entity, redraw); // Add entity to entity store\r\n\t\t}\r\n\r\n\t\tprivate void DeleteTile(string id, bool reDraw=true) {\r\n\t\t\ttiles.Remove(id); // Delete from displayed tiles\r\n\t\t\tzone.zoneEntities.Remove(id); // Delete from zone\r\n\r\n\t\t\tcanvasChanged = true; // Check to save before closing\r\n\r\n\t\t\tif (reDraw) canvas.Draw(); // Re-invoke canvas to draw updated values\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets all tiles existing at a given position</summary>\r\n\t\t/// <param name=\"pos\">Position to check for</param>\r\n\t\tprivate IEnumerable<KeyValuePair<String, EntityTile>> GetTiles(PointF pos) {\r\n\t\t\tforeach (KeyValuePair<String, EntityTile> tile in tiles) {\r\n\t\t\t\tif (tile.Value.Region.Contains(pos)) yield return tile;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets all tiles intersecting with a given rect</summary>\r\n\t\t/// <param name=\"rect\">Rectangle to check against</param>\r\n\t\tprivate IEnumerable<KeyValuePair<String, EntityTile>> GetTiles(RectangleF rect) {\r\n\t\t\tforeach (KeyValuePair<String, EntityTile> tile in tiles) {\r\n\t\t\t\tif (tile.Value.Region.IntersectsWith(rect)) yield return tile;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Edits an existing tile within the zone/canvas</summary>\r\n\t\t/// <param name=\"id\">Id of selected tile to edit</param>\r\n\t\tprivate void EditEntityView_Execute(String id) {\r\n\t\t\tEntityTile tile = tiles[id]; GameEntity entity = tile.Entity; // Store reference to game-entity & Tile\r\n\t\t\tEditEntityView.EditEntityViewResultsContainer results = EditEntityView.RunForExistingEntity(id, entity, zone);\r\n\r\n\t\t\tif (results.state == EditEntityView.ReturnState.Changed) {\r\n\t\t\t\tforeach (String key in results.updatedEntity.GetEntityAttributes()) {\r\n\t\t\t\t\tentity[key].Value = results.updatedEntity[key].GetValue();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcanvas.Draw(); // Re-invoke canvas to draw updated values\r\n\t\t\t} else if (results.state == EditEntityView.ReturnState.Delete) {\r\n\t\t\t\tDeleteTile(id, true); // Delete and then redraw canvas\r\n\t\t\t} // else if (results.state == EditEntityView.ReturnState.Cancel) { }\r\n\t\t}\r\n\r\n\t\tprivate GameEntity GetDrawEntity(RectangleF newRegion) {\r\n\t\t\tGameEntity clonedTemplate = templateGameEntity.Clone(newRegion) as GameEntity;\r\n\r\n\t\t\tbool supportsDefaultAnimation = clonedTemplate.GetEntityAttributes().Contains(\"DefaultAnimation\");\r\n\r\n\t\t\tif (supportsDefaultAnimation && !clonedTemplate[\"DefaultAnimation\"].IsAssigned) {\r\n\t\t\t\tbool inTileMap = tileBox.DrawTile && tileBox.TextureRegion != Rectangle.Empty;\r\n\t\t\t\tAnimationSequence sequence = new AnimationSequence(0, new Frame(tileBox.TextureRegion));\r\n\t\t\t\tif (inTileMap) clonedTemplate[\"DefaultAnimation\"].SetAttribute(sequence);\r\n\t\t\t}\r\n\r\n\t\t\tif (!clonedTemplate[\"Texture\"].IsAssigned && tileBox.DrawTile) {\r\n\t\t\t\tclonedTemplate[\"Texture\"].Value = GV.LevelEditor.tileMap.CurrentImageTextureKey;\r\n\t\t\t}\r\n\r\n\t\t\treturn clonedTemplate;\r\n\t\t}\r\n\r\n\t\tprivate void SetTemplateEntity(GameEntity entity) {\r\n\t\t\ttemplateGameEntity = entity;\r\n\r\n\t\t\tbool positionAssigned = templateGameEntity[\"Position\"].IsAssigned;\r\n\t\t\tbool widthAssigned = templateGameEntity[\"Width\"].IsAssigned;\r\n\t\t\tbool heightAssigned = templateGameEntity[\"Height\"].IsAssigned;\r\n\r\n\t\t\tif (drawRadioButton.Checked) {\r\n\t\t\t\tif (positionAssigned || widthAssigned || heightAssigned) {\r\n\t\t\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.Custom;\r\n\t\t\t\t\tCustomSelectOption = CustomSelectionRectBuilderTypes.EntityWrapper;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.GridClick;\r\n\t\t\t\t\tCustomSelectOption = CustomSelectionRectBuilderTypes.None;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Event handler to resize canvas alongside form</summary>\r\n\t\tprivate void ZoneEditor_SizeChanged(object sender, EventArgs e) {\r\n\t\t\tSize deltaSize = Size - sizeBeforeResize; // Change in size\r\n\r\n\t\t\tzoneCanvasPanel.Size += deltaSize; // Increment the size of the zone canvas by the change in size\r\n\t\t\tformatGroupBox.Location = new Point(formatGroupBox.Location.X + deltaSize.Width, formatGroupBox.Location.Y);\r\n\r\n\t\t\tsizeBeforeResize = Size; // Set sizeBeforeResize to equal current size\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts zone canvas to a file</summary>\r\n\t\tpublic String CanvasToFile() {\r\n\t\t\tString header = $\"{Zone.ZONE_FILE_HEADER} (X:{zone.ZoneWidth} Y:{zone.ZoneHeight})\";\r\n\r\n\t\t\tStringBuilder builder = new StringBuilder($\"{header}\\n\\n\");\r\n\r\n\t\t\tbuilder.AppendLine(zone.ZoneAssetTrace.ToFileContents());\r\n\r\n\t\t\tbuilder.Append(\"\\n\"); // Leave two line breaks\r\n\r\n\t\t\tforeach (KeyValuePair<String, EntityTile> tileKVP in tiles) {\r\n\t\t\t\tbuilder.AppendLine(tileKVP.Value.Entity.ToFileContents(tileKVP.Key));\r\n\t\t\t}\r\n\r\n\t\t\treturn builder.ToString();\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Canvas zoom</summary>\r\n\t\tpublic float Zoom { get { return canvas.ZoomX; } set {\r\n\t\t\t\tfloat newValue = GV.BasicMath.Clamp(value, MIN_ZOOM, MAX_ZOOM);\r\n\t\t\t\tcanvas.Zoom = new SizeF(newValue, newValue); // Set zoom value\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Canvas region upon which zone is drawn</summary>\r\n\t\tprivate CanvasRegionBox canvas = new CanvasRegionBox() {\r\n\t\t\tDrawGrid = true, DrawBorder = true,\r\n\t\t\tSelectOption = CanvasRegionBox.SelectType.GridClick,\r\n\t\t\tdragableSelectionRectsAreVolatile = true\r\n\t\t};\r\n\r\n\t\t/// <summary>Whether to only draw the currently highlited entity</summary>\r\n\t\tpublic bool DrawOnlyCurrentEntity { get { return onlyCurrentEntityCheckBox.Checked; } }\r\n\r\n\t\t/// <summary>Entity value stored within the entity type combo box</summary>\r\n\t\tpublic string CurrentEntityType { get { return entityTypeComboBox.SelectedItem.ToString(); } }\r\n\r\n\t\tprivate float? SelectedLayer = null;\r\n\r\n\t\t/// <summary>Bottom left tile box, representing value on tile map</summary>\r\n\t\tprivate TileBox tileBox = new TileBox() { HaveErrorIndicator = false };\r\n\r\n\t\tpublic const float MAX_ZOOM = 15f, MIN_ZOOM = 0.5f;\r\n\r\n\t\tprivate Dictionary<String, EntityTile> tiles = new Dictionary<String, EntityTile>();\r\n\r\n\t\tprivate Size sizeBeforeResize;\r\n\r\n\t\tprivate GameEntity templateGameEntity;\r\n\r\n\t\tprivate Zone zone;\r\n\r\n\t\tprivate bool canvasChanged = false;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7150084376335144, "alphanum_fraction": 0.7150084376335144, "avg_line_length": 19.178571701049805, "blob_id": "66a3cc3ea660381deb9b02f514a1e56b6118d679", "content_id": "cf5dcbfa83885376f43ae0656a9d58a71daa3eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 595, "license_type": "no_license", "max_line_length": 97, "num_lines": 28, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/FatalException.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tclass FatalException : HollowAetherException {\r\n\t\tpublic FatalException() : base() {\r\n\r\n\t\t}\r\n\r\n\t\tpublic FatalException(String msg) : base(msg) {\r\n\r\n\t\t}\r\n\r\n\t\tpublic FatalException(String msg, Exception inner) : base(msg, inner) {\r\n\r\n\t\t}\r\n\r\n\t\tpublic FatalException(SerializationInfo info, StreamingContext context) : base(info, context) {\r\n\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7065829634666443, "alphanum_fraction": 0.7073408365249634, "avg_line_length": 42.83495330810547, "blob_id": "21ab6033f0cc9f250900d00510505cbd95391f50", "content_id": "54a68645ba65ce4365d3ed5d05726a7a4c2fd96b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9238, "license_type": "no_license", "max_line_length": 120, "num_lines": 206, "path": "/HollowAether/Lib/InputOutput/InputOutputManager.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Encryption;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.InputOutput {\r\n\t/// <summary>Static class to simplify filestream operations</summary>\r\n\tpublic static class InputOutputManager {\r\n\t\t#region CheckStatemente\r\n\t\t/// <summary>Method to check whether a file exists</summary>\r\n\t\t/// <param name=\"fpath\">Path to a given file</param>\r\n\t\t/// <returns>Boolean indicating existance of given file</returns>\r\n\t\tpublic static bool FileExists(String fpath) { return File.Exists(fpath); }\r\n\r\n\t\t/// <summary>Method to check whether a directory exists</summary>\r\n\t\t/// <param name=\"dpath\">Path to a given directory</param>\r\n\t\t/// <returns>Boolean indicating existence of given dir</returns>\r\n\t\tpublic static bool DirectoryExists(String dpath) { return Directory.Exists(dpath); }\r\n\t\t#endregion\r\n\r\n\t\t#region ReadStatements\r\n\t\t/// <summary>Method to read a file</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"encoding\">Encoding to read file with</param>\r\n\t\t/// <returns>String contents of a given file</returns>\r\n\t\tpublic static String ReadFile(String fpath, Encoding encoding = null) {\r\n\t\t\treturn File.ReadAllText(fpath, (encoding == null) ? defaultEncoding : encoding);\r\n\t\t}\r\n\r\n\t\t/// <summary>Reads a file which was encrypted via OneTimePad</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"OTP\">Instance of OneTimePad to decrypt with</param>\r\n\t\t/// <param name=\"encoding\">Encoding to read a file with</param>\r\n\t\t/// <returns>Decrypted contents of a given file</returns>\r\n\t\tpublic static String ReadEncryptedFile(String fpath, OneTimePad OTP, Encoding encoding = null) {\r\n\t\t\treturn OTP.Decrypt(ReadFile(fpath, encoding)); // no need to pass key\r\n\t\t}\r\n\r\n\t\t/// <summary>Reads a file which was encrypted via OneTimePad</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"key\">Key to encrypt/decrypt with</param>\r\n\t\t/// <param name=\"encoding\">Encoding to read a file with</param>\r\n\t\t/// <returns>Decrypted contents of a given file</returns>\r\n\t\tpublic static String ReadEncryptedFile(String fpath, String key, Encoding encoding = null) {\r\n\t\t\treturn ReadEncryptedFile(fpath, new OneTimePad(key), encoding);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region WriteStatements\r\n\t\t/// <summary>Writes a given string to the path of a file</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"contents\">Text to write to file</param>\r\n\t\t/// <param name=\"encoding\">Encoding to interpret file with</param>\r\n\t\t/// <returns>Boolean indicating whether file was sucessfully written to</returns>\r\n\t\tpublic static bool WriteFile(String fpath, String contents, Encoding encoding = null) {\r\n\t\t\ttry {\r\n\t\t\t\tFile.WriteAllText(fpath, contents, (encoding == null) ? defaultEncoding : encoding);\r\n\t\t\t\treturn true; // File was written to sucesfully, return True\r\n\t\t\t} catch { return false; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts & then writes a given string to the path of a file</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"contents\">Text to write to file</param>\r\n\t\t/// <param name=\"OTP\">Instance of OneTimePad to encrypt/decrypt with</param>\r\n\t\t/// <param name=\"encoding\">Encoding to interpret file with</param>\r\n\t\t/// <returns>Boolean indicating whether file was sucessfully written to</returns>\r\n\t\tpublic static bool WriteEncryptedFile(String fpath, String contents, OneTimePad OTP, Encoding encoding = null) {\r\n\t\t\treturn WriteFile(fpath, OTP.Encrypt(contents), encoding);\r\n\t\t}\r\n\r\n\r\n\t\t/// <summary>Encrypts & then writes a given string to the path of a file</summary>\r\n\t\t/// <param name=\"fpath\">Path to file</param>\r\n\t\t/// <param name=\"contents\">Text to write to file</param>\r\n\t\t/// <param name=\"key\">Key to encrypt text with</param>\r\n\t\t/// <param name=\"encoding\">Encoding to interpret file with</param>\r\n\t\t/// <returns>Boolean indicating whether file was sucessfully written to</returns>\r\n\t\tpublic static bool WriteEncryptedFile(String fpath, String contents, String key, Encoding encoding = null) {\r\n\t\t\treturn WriteEncryptedFile(fpath, contents, new OneTimePad(key), encoding);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Miscellaneous\r\n\t\t/// <summary>Combines various paths into a single path</summary>\r\n\t\t/// <param name=\"fpath\">paths which u wish to join</param>\r\n\t\t/// <returns>Joined directory string</returns>\r\n\t\tpublic static String Join(params String[] fpath) {\r\n\t\t\tif (fpath.Length >= 1)\r\n\t\t\t\treturn fpath.Aggregate((A, B) => $\"{A}{OSFileSystemSeperator}{B}\");\r\n\t\t\telse\r\n\t\t\t\treturn String.Empty;\r\n\t\t}\r\n\r\n\t\t/// <summary>Strips and returns each sequential directory in a path</summary>\r\n\t\t/// <param name=\"str\">File system path</param>\r\n\t\t/// <param name=\"_stripChar\">Character to strip with</param>\r\n\t\t/// <param name=\"skipFirst\">Whether or not to skip first value</param>\r\n\t\t/// <returns>Enumerable sequenced directory</returns>\r\n\t\tpublic static IEnumerable<String> SequentialStrip(String str, char? _stripChar = null, bool skipFirst = true) {\r\n\t\t\tchar stripChar = (_stripChar.HasValue) ? _stripChar.Value : OSFileSystemSeperator;\r\n\t\t\tString[] splitString = str.Split(stripChar); // Split string by given delimeter\r\n\r\n\t\t\tforeach (int X in Enumerable.Range((skipFirst) ? 2 : 1, splitString.Count() - (skipFirst ? 1 : 0))) {\r\n\t\t\t\tyield return (from N in Enumerable.Range(0, X) select splitString[N]).Aggregate((a, b) => $\"{a}{stripChar}{b}\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Tries to create a given directory</summary>\r\n\t\t/// <param name=\"dPath\">Path to directory</param>\r\n\t\t/// <returns>Boolean indicating whether path was constructed or not</returns>\r\n\t\tpublic static bool CheckConstruct(String dPath) {\r\n\t\t\ttry { Directory.CreateDirectory(dPath); return true; } catch { return false; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Constructs every directory in a path</summary>\r\n\t\t/// <param name=\"dpath\">Path to directory</param>\r\n\t\t/// <returns>Boolean indicating whether all directories were constructed or not</returns>\r\n\t\tpublic static bool SequenceConstruct(String dpath) {\r\n\t\t\tforeach (String path in SequentialStrip(dpath))\r\n\t\t\t\tif (!CheckConstruct(path)) return false;\r\n\r\n\t\t\treturn true; // If not returned yet then give true\r\n\t\t}\r\n\r\n\t\tpublic static String[] GetFiles(String path) {\r\n\t\t\treturn Directory.GetFiles(path);\r\n\t\t}\r\n\r\n\t\tpublic static String[] GetDirectories(String path) {\r\n\t\t\treturn Directory.GetDirectories(path);\r\n\t\t}\r\n\r\n\t\tpublic static String ChangeExtension(String input, String desiredExtension) {\r\n\t\t\treturn Path.ChangeExtension(input, desiredExtension);\r\n\t\t}\r\n\r\n\t\tpublic static String GetExtension(String input) {\r\n\t\t\treturn Path.GetExtension(input);\r\n\t\t}\r\n\r\n\t\tpublic static String GetDirectoryName(String input) {\r\n\t\t\treturn Path.GetDirectoryName(input);\r\n\t\t}\r\n\r\n\t\tpublic static String GetFileNameFromPath(String input) {\r\n\t\t\treturn Path.GetFileName(input);\r\n\t\t}\r\n\r\n\t\tpublic static String GetFileTitleFromPath(String input) {\r\n\t\t\treturn Path.GetFileNameWithoutExtension(input);\r\n\t\t}\r\n\r\n\t\tpublic static String RemoveExtension(String input) {\r\n\t\t\tstring directoryName = GetDirectoryName(input), fileTitle = GetFileTitleFromPath(input);\r\n\t\t\treturn String.IsNullOrWhiteSpace(directoryName) ? fileTitle : Join(directoryName, fileTitle);\r\n\t\t}\r\n\r\n\t\t/// <summary>Returns path from a reference to a given absolute path</summary>\r\n\t\t/// <param name=\"absolute\">Path one wishes to reach</param>\r\n\t\t/// <param name=\"reference\">Path from which one is travelling</param>\r\n\t\t/// <returns>Path relation from given reference path to absolute</returns>\r\n\t\tpublic static String GetRelativePath(String absolute, String reference) {\r\n\t\t\tabsolute = absolute.ToLower().TrimEnd(OSFileSystemSeperator);\r\n\t\t\treference = reference.ToLower().TrimEnd(OSFileSystemSeperator);\r\n\r\n\t\t\tif (absolute.Contains(reference)) // If absolute is within reference\r\n\t\t\t\treturn absolute.Replace(reference, \"\").TrimStart(OSFileSystemSeperator);\r\n\r\n\t\t\tforeach (String directory in SequentialStrip(reference, '\\\\', false).Reverse()) {\r\n\t\t\t\tif (!absolute.Contains(directory)) continue; // No related path found yet, there shoud be one at the drive root\r\n\r\n\t\t\t\tvar dotEnumerate = Enumerable.Range(0, reference.Replace(directory, \"\").Count(X => X == '\\\\')); // Desired dot count\r\n\r\n\t\t\t\treturn (from X in dotEnumerate select \"..\").Aggregate((X, Y) => $\"{X}\\\\{Y}\") + absolute.Replace(directory, \"\");\r\n\t\t\t}\r\n\r\n\t\t\treturn absolute; // Couldn't be done, best one can hope for is this\r\n\t\t}\r\n\r\n\t\tpublic static String GetRelativeFilePath(String filePath, String reference) {\r\n\t\t\tString containingFileDirectory = GetDirectoryName(filePath), fileName = GetFileNameFromPath(filePath);\r\n\t\t\treturn Join(GetRelativePath(containingFileDirectory, reference), fileName);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#if !LINUX\r\n\t\t/// <summary>Character to seperate paths in fsystem</summary>\r\n\t\tpublic static char OSFileSystemSeperator = '\\\\';\r\n\t\t#else\r\n\t\t/// <summary>Character to seperate paths in fsystem</summary>\r\n\t\tpublic static char OSFileSystemSeperator = '/';\r\n\t\t#endif\r\n\r\n\t\t/// <summary>Encoding to read files with by default</summary>\r\n\t\tpublic static Encoding defaultEncoding = Encoding.Unicode;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7035501599311829, "alphanum_fraction": 0.7093169689178467, "avg_line_length": 45.02542495727539, "blob_id": "adf8e13cc3b2c1d76ef34a540f8667179b5c66d6", "content_id": "b2835db0e82dd91d8aa77f126181fc50ee819a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5551, "license_type": "no_license", "max_line_length": 129, "num_lines": 118, "path": "/HollowAether/Lib/GAssets/HUD/HeartSprite.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\t/// <summary>Base class for Hearts displayed on HUD.</summary>\r\n\tclass HeartSprite : Sprite, IPushable {\r\n\t\t/// <param name=\"offset\">Value with which to offset sprite from top left corner of screen</param>\r\n\t\t/// <param name=\"start_health\">Beginning health assigned to sprite. It's full by default</param>\r\n\t\tpublic HeartSprite(Vector2 offset, int startHealth=HEART_SPAN) : base(offset, DEFAULT_WIDTH, DEFAULT_HEIGHT, true) {\r\n\t\t\thealth = startHealth; // Set beginning health for heart from constructor, by default is max\r\n\t\t\tInitialize(@\"sprites\\heart\"); // Initialize from construction with spritesheet & animations\r\n\t\t\tResetAnimationSequence(); // ResetAnimationSequence to match corresponding heart health\r\n\t\t\theartCount += 1; // Increment the amount of hearts known\r\n\t\t\tLayer = 0.9f;\r\n\t\t}\r\n\r\n\t\tpublic HeartSprite(int xOffset, int yOffset, int startHealth=HEART_SPAN) : this(new Vector2(xOffset, yOffset), startHealth) { }\r\n\r\n\t\tpublic void PushTo(Vector2 position, float over = 0.8f) {\r\n\t\t\tif (PushArgs.PushValid(position, Position))\r\n\t\t\t\tPush(new PushArgs(position, Position, over));\r\n\t\t}\r\n\r\n\t\tpublic void Push(PushArgs args) { if (!BeingPushed) PushPack = args; }\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed time as well\r\n\r\n\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) {\r\n\t\t\t\tPushPack = null; // Delete push pack\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds all animations used by sprite</summary>\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tfor (int X = HEART_SPAN; X >= 0; X--) { // Iterative animation generator -> Relies on texture following format\r\n\t\t\t\tAnimation[$\"{X}/{HEART_SPAN}\"] = new AnimationSequence(0, new Frame(HEART_SPAN - X, 1, 18, 15, 18, 15));\r\n\t\t\t}\r\n\r\n\t\t\tResetAnimationSequence(); // Reset sequence to \r\n\t\t}\r\n\r\n\t\t/// <summary>Set's animation to match health of heart sprite</summary>\r\n\t\tprivate void ResetAnimationSequence() {\r\n\t\t\tAnimation.SetAnimationSequence($\"{health}/{HEART_SPAN}\", true);\r\n\t\t}\r\n\r\n\t\t/// <summary>Adds health to sprite heart and then updates animation sequence to match</summary>\r\n\t\t/// <param name=\"value\">Value to add to health already contained in heart</param>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.HollowAetherException\">New value out of range</exception>\r\n\t\tpublic void AddHealth(int value=1) {\r\n\t\t\tif (health + value > HEART_SPAN) throw new HollowAetherException($\"Heart health cannot be '{health + value}'\");\r\n\t\t\thealth += value; ResetAnimationSequence(); // Subtract from health then re-decide animation-sequence\r\n\t\t}\r\n\r\n\t\t/// <summary>Subtracts health from heart sprite and then updates animation sequence to match</summary>\r\n\t\t/// <param name=\"value\">Value to subtract from health already contained in heart</param>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.HollowAetherException\">New value out of range</exception>\r\n\t\tpublic void SubtractHealth(int value=1) {\r\n\t\t\tif (health - value < 0) throw new HollowAetherException($\"Heart health cannot be '{health - value}'\");\r\n\t\t\thealth -= value; ResetAnimationSequence(); // Subtract from health then re-decide animation-sequence\r\n\t\t}\r\n\r\n\t\tpublic void RefillHealth() { health = HEART_SPAN; ResetAnimationSequence(); }\r\n\r\n\t\tpublic void EmptyHealth() { health = 0; ResetAnimationSequence(); }\r\n\r\n\t\t/// <summary>Sets the health of the heart and then updates animation sequence to match</summary>\r\n\t\t/// <param name=\"newHealth\">New heart health</param>\r\n\t\t/// <exception cref=\"HollowAether.Lib.Exceptions.HollowAetherException\">New value out of range</exception>\r\n\t\tpublic void SetHealth(int newHealth) {\r\n\t\t\tif (newHealth < 0 || newHealth > HEART_SPAN) throw new HollowAetherException($\"Heart health cannot be '{newHealth}'\");\r\n\t\t\thealth = newHealth; ResetAnimationSequence(); // Change stored health to new value, then re-decide animation sequence\r\n\t\t}\r\n\t\t\r\n\t\t/// <param name=\"heart\">Heart to add to</param>\r\n\t\t/// <param name=\"value\">Value to add to heart</param>\r\n\t\t/// <returns>New heart with incremented health</returns>\r\n\t\tpublic static HeartSprite operator +(HeartSprite heart, int value) {\r\n\t\t\theart.health += value; return heart;\r\n\t\t}\r\n\r\n\t\t/// <param name=\"heart\">Heart to subtract from heart</param>\r\n\t\t/// <param name=\"value\">Value to subtract from heart</param>\r\n\t\t/// <returns>New heart with decremented health</returns>\r\n\t\tpublic static HeartSprite operator -(HeartSprite heart, int value) {\r\n\t\t\theart.health -= value; return heart;\r\n\t\t}\r\n\r\n\t\t/// <summary>Supports implicit casting to integer</summary>\r\n\t\t/// <param name=\"heart\">Heart to cast to integer</param>\r\n\t\tpublic static implicit operator int(HeartSprite heart) {\r\n\t\t\treturn heart.health;\r\n\t\t}\r\n\r\n\t\t/// <summary>Health of heart</summary>\r\n\t\tpublic int Health { get { return health; } set { SetHealth(value); } }\r\n\r\n\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\r\n\t\tprivate int health; // Health allocated to sprite/heart\r\n\r\n\t\tpublic const int DEFAULT_WIDTH = 18 * 2, DEFAULT_HEIGHT = 15 * 2;\r\n\t\tpublic const int HEART_SPAN = 4; // Max amount of heart features\r\n\t\tpublic static int heartCount = 0;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6945782899856567, "alphanum_fraction": 0.7006024122238159, "avg_line_length": 28.740739822387695, "blob_id": "8e5b84960d6ce3439479909d001d34d7985472b2", "content_id": "c7479a4a8ce78b25cc9fdf095e488a0de38229ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1662, "license_type": "no_license", "max_line_length": 112, "num_lines": 54, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Assist/EnemyHealthBar.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic class EnemyHealthBar {\r\n\t\tstatic EnemyHealthBar() { healthTexture = GV.TextureCreation.GenerateBlankTexture(Color.Red, 1, 1); }\r\n\r\n\t\tpublic EnemyHealthBar(Vector2 position, int width, int height=DEFAULT_HEIGHT, uint healthSpan=1) {\r\n\t\t\tPosition = position;\r\n\t\t\tWidth = width;\r\n\t\t\tHeight = height;\r\n\t\t\tHealth = (int)healthSpan;\r\n\t\t\tMaxHealth = healthSpan;\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\thealthTexture, new Rectangle(Position.ToPoint(), new Point(AdjustedWidth, Height)), Color.White\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic void TakeDamage(int amount) { Health = GV.BasicMath.Clamp<int>(Health-amount, 0, (int)MaxHealth); }\r\n\r\n\t\tpublic void RegainHealth(int amount) { Health = GV.BasicMath.Clamp<int>(Health + amount, 0, (int)MaxHealth); }\r\n\r\n\t\tprivate int GetWidthFromHealthSpan() { return (int)(Width * Health / MaxHealth); }\r\n\r\n\t\tpublic void Offset(Vector2 offset) { Position += offset; }\r\n\r\n\t\tpublic Vector2 Position { get; set; }\r\n\r\n\t\tpublic int Width { get; protected set; }\r\n\r\n\t\tpublic int Height { get; protected set; }\r\n\t\r\n\t\tpublic int Health { get; protected set; }\r\n\r\n\t\tpublic int AdjustedWidth { get { return GetWidthFromHealthSpan(); } }\r\n\r\n\t\tpublic uint MaxHealth { get; private set; }\r\n\r\n\t\tprivate static Texture2D healthTexture;\r\n\r\n\t\tpublic const int DEFAULT_HEIGHT = 5;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6736912131309509, "alphanum_fraction": 0.6852262616157532, "avg_line_length": 31.392593383789062, "blob_id": "575e01fdbe5f309870158346ed602518ad1e1121", "content_id": "f56eb97b5ed0d2b5ee85d7846f4f1bda58bf3d70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4510, "license_type": "no_license", "max_line_length": 116, "num_lines": 135, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Fortress.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Fortress : Enemy, IPushable {\r\n\t\tpublic Fortress() : this(Vector2.Zero, 1) { }\r\n\r\n\t\tpublic Fortress(Vector2 position, int level) : base(position, FRAME_WIDTH, FRAME_HEIGHT, level, true) {\r\n\t\t\tInitialize(@\"enemies\\badeye\");\r\n\t\t\tdefaultPosition = position;\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey);\r\n\r\n\t\t\tKilled += (self) => { Animation.SetAnimationSequence(\"Stationary\"); };\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(Position.X, Position.Y, Width, Height));\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Stationary\"] = GV.MonoGameImplement.importedAnimations[@\"fortress\\stationary\"];\r\n\t\t\tAnimation[\"Flapping\"] = GV.MonoGameImplement.importedAnimations[@\"fortress\\flapping\"];\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"Flapping\"); // Default animation is stationary\r\n\t\t}\r\n\r\n\r\n\t\tpublic void PushTo(Vector2 position, float over = 0.8f) {\r\n\t\t\tPush(new PushArgs(position, Position, over));\r\n\t\t}\r\n\r\n\t\tpublic void Push(PushArgs args) { if (!BeingPushed) PushPack = args; }\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed time as well\r\n\r\n\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) {\r\n\t\t\t\tPushPack = null; // Delete push pack\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override void DoEnemyStuff() {\r\n\t\t\tVector2 playerCenter = GV.MonoGameImplement.Player.SpriteRect.Center.ToVector2();\r\n\t\t\tfloat differenceLength = (playerCenter - (defaultPosition + (Size.ToVector2() / 2))).Length(); \r\n\r\n\t\t\tif (attacking) {\r\n\t\t\t\tif (attackTimeout > 0) { attackTimeout -= elapsedMilitime; } else {\r\n\t\t\t\t\tFireball fire = new Fireball(Position, GV.MonoGameImplement.Player.Position, 45);\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(fire); // Add fire to object store\r\n\t\t\t\t\tattackTimeout = 2500; // Don't attack\\throw-fireball again for 2.5 seconds\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!BeingPushed) {\r\n\t\t\t\t\tif (differenceLength >= DetectionRadius) { attacking = false; Angle = 0f; PushTo(defaultPosition, 2f); } else {\r\n\t\t\t\t\t\tAngle += AngularSpeed * elapsedTime; // Increment current angle of enemy from center\r\n\r\n\t\t\t\t\t\tVector2 sinCosRatio = new Vector2((float)Math.Cos(Angle), (float)Math.Sin(Angle));\r\n\t\t\t\t\t\tOffsetSpritePosition(sinCosRatio * Radius * elapsedTime); // Make circle around center\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (!BeingPushed && differenceLength <= DetectionRadius) {\r\n\t\t\t\t\tPushTo(defaultPosition - new Vector2(0, Radius), 2f);\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (BeingPushed) { // In case new position not valid\r\n\t\t\t\t\t\tPushPack.PushCompleted += (self, args) => {\r\n\t\t\t\t\t\t\tattacking = true; // Start attacking after pushed\r\n\t\t\t\t\t\t};\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override uint GetHealth() {\r\n\t\t\treturn 100;\r\n\t\t\treturn GV.BasicMath.Clamp<uint>((uint)(3 * GV.Variables.random.Next(Level-5, Level+5)), 1, 100);\r\n\t\t}\r\n\r\n\t\tprivate float GetLengthToPlayerFrom(Vector2 position) {\r\n\t\t\treturn (GV.MonoGameImplement.Player.SpriteRect.Center.ToVector2() - position).Length();\r\n\t\t}\r\n\r\n\t\tprivate bool attacking = false;\r\n\r\n\t\tprivate float attackTimeout = 0f;\r\n\r\n\t\tpublic float DetectionRadius { get; set; } = 150;\r\n\r\n\t\tprivate const float AngularSpeed = (float)(2 * Math.PI / 3);\r\n\r\n\t\tprivate float angle;\r\n\r\n\t\tprivate float Angle { get { return angle; } set {\r\n\t\t\tangle = value; // Set angle to new value\\argument\r\n\r\n\t\t\tif (angle > 2 * Math.PI) angle -= (float)(2 * Math.PI);\r\n\t\t} }\r\n\r\n\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\r\n\t\tpublic float Radius { get { return Height * 5f; } }\r\n\r\n\t\tprotected override bool CanGenerateHealth { get; set; } = false;\r\n\r\n\t\tprotected override bool CausesContactDamage { get; set; } = true;\r\n\r\n\t\tprivate Vector2 defaultPosition;\r\n\r\n\t\tpublic const int FRAME_WIDTH = 31, FRAME_HEIGHT = 24;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = FRAME_WIDTH, SPRITE_HEIGHT = FRAME_HEIGHT;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7281286120414734, "alphanum_fraction": 0.7377727031707764, "avg_line_length": 33.991737365722656, "blob_id": "7c995a7d5de01be3e91d70d3a612b298f8093792", "content_id": "b6550bea4d1374b01577aec5dfa66add8a0520f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4357, "license_type": "no_license", "max_line_length": 138, "num_lines": 121, "path": "/HollowAether/Lib/GAssets/Weapons/Shuriken.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets.Weapons {\r\n\tpublic sealed class Shuriken : Weapon {\r\n\t\tprivate sealed class Projectile : VolatileCollideableSprite, IDamagingToEnemies {\r\n\t\t\tpublic Projectile(Vector2 initPosition) : base(initPosition, FRAME_WIDTH, FRAME_HEIGHT, true) {\r\n\t\t\t\tInitialize(\"weapons\\\\shuriken\"); // Initialise from construction with default texture\r\n\r\n\t\t\t\tInitializeVolatility(VolatilityType.Timeout, EXISTANCE_TIME);\r\n\r\n\t\t\t\tfloat theta = GV.MonoGameImplement.Player.GetAnglePointedToByInput();\r\n\r\n\t\t\t\tVector2 sinCosRatio = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));\r\n\r\n\t\t\t\tvelocity = sinCosRatio * DefaultVelocity; acceleration = sinCosRatio * DefaultAcceleration;\r\n\t\t\t}\r\n\r\n\t\t\tpublic int GetDamage() {\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\t\tbase.Update(updateAnimation);\r\n\r\n\t\t\t\tOffsetSpritePosition(velocity * elapsedTime);\r\n\t\t\t\tvelocity += acceleration * elapsedTime;\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void BuildBoundary() {\r\n\t\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, GetBoundaryRect(Position));\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = GetAnimationSequence();\r\n\t\t\t}\r\n\r\n\t\t\tprivate const int EXISTANCE_TIME = 5000;\r\n\r\n\t\t\tprivate Vector2 velocity, acceleration;\r\n\r\n\t\t\tpublic static readonly int DefaultAcceleration = 50;\r\n\r\n\t\t\tpublic static readonly int DefaultVelocity = 25;\r\n\t\t}\r\n\r\n\t\tpublic Shuriken(Vector2 position) : base(position, FRAME_WIDTH, FRAME_HEIGHT, true) { Initialize($\"weapons\\\\shuriken\"); }\r\n\r\n\t\tprotected override void BuildBoundary() { boundary = new SequentialBoundaryContainer(SpriteRect, GetBoundaryRect(Position)); }\r\n\r\n\t\tprotected override void BuildSequenceLibrary() { Animation[GV.MonoGameImplement.defaultAnimationSequenceKey] = GetAnimationSequence(); }\r\n\r\n\t\tprivate static IBRectangle GetBoundaryRect(Vector2 position) {\r\n\t\t\tVector2 boundaryPosition = position + new Vector2(BOUNDARY_X_OFFSET, BOUNDARY_Y_OFFSET); // Position with offset\r\n\t\t\treturn new IBRectangle(boundaryPosition.X, boundaryPosition.Y, ACTUAL_WEAPON_WIDTH, ACTUAL_WEAPON_HEIGHT);\r\n\t\t}\r\n\r\n\t\tprivate static AnimationSequence GetAnimationSequence() {\r\n\t\t\treturn AnimationSequence.FromRange(FRAME_WIDTH, FRAME_HEIGHT, 0, 0, 4, FRAME_WIDTH, FRAME_HEIGHT, 1, true, 0);\r\n\t\t}\r\n\r\n\t\tpublic override void Attack(Player player) {\r\n\t\t\tbase.Attack(player); // Update base attack features\r\n\r\n\t\t\tGV.MonoGameImplement.monogameObjects.AddNameless(new Projectile(Position));\r\n\t\t}\r\n\t\r\n\t\tprotected override void UpdateAttack() {\r\n\t\t\tif (Attacking) {\r\n\t\t\t\telapsedTimeBetweenThrows += elapsedMilitime;\r\n\r\n\t\t\t\tif (elapsedTimeBetweenThrows >= DELAY_BETWEEN_THROWS)\r\n\t\t\t\t\tFinishAttacking(); // Allow attack again\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override void FinishAttacking() {\r\n\t\t\tbase.FinishAttacking();\r\n\t\t\telapsedTimeBetweenThrows = 0;\r\n\t\t}\r\n\r\n\t\tpublic override void Throw(float direction) {\r\n\t\t\tbase.Throw(direction); // No real point\r\n\t\t\tAttack(GV.MonoGameImplement.Player);\r\n\t\t\tStopThrowing(); // Can't throw and attack\r\n\t\t}\r\n\r\n\t\tpublic override void SetWeaponPositionRelativeToPlayer(Player player) {\r\n\t\t\tVector2 positionBeforeSizeOffset = player.Position + (player.FacingRight ? Vector2.Zero : new Vector2(player.SpriteRect.Width, 0));\r\n\t\t\tPosition = positionBeforeSizeOffset - (SpriteRect.Size.ToVector2() / 2); // Subtract half dimensions from either desired size\r\n\t\t}\r\n\r\n\t\tpublic override void AttachToPlayer(Player player) { SetWeaponPositionRelativeToPlayer(player); }\r\n\r\n\t\tpublic override bool CanBeThrown { get; protected set; } = true;\r\n\r\n\t\tprivate Point ActualWeaponSize { get { return new Point(ACTUAL_WEAPON_WIDTH, ACTUAL_WEAPON_HEIGHT); } }\r\n\r\n\t\tprivate const int BOUNDARY_X_OFFSET=8, BOUNDARY_Y_OFFSET=8;\r\n\r\n\t\tprivate const int FRAME_WIDTH = 28, FRAME_HEIGHT = 28;\r\n\r\n\t\tprivate const int ACTUAL_WEAPON_WIDTH = 12, ACTUAL_WEAPON_HEIGHT = 12;\r\n\r\n\t\tprivate const int DELAY_BETWEEN_THROWS = 750;\r\n\r\n\t\tprivate int elapsedTimeBetweenThrows;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6635454893112183, "alphanum_fraction": 0.6703880429267883, "avg_line_length": 41.04263687133789, "blob_id": "7bc4ccf154ca843ddd3ece50b2c9bdfbb71e1154", "content_id": "b58ae5088cbb8e26ae80b5617bce3a64a2c18a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11109, "license_type": "no_license", "max_line_length": 131, "num_lines": 258, "path": "/HollowAether/Lib/InputOutput/Parsers/Parser.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.InputOutput;\r\n#endregion\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.MapZone;\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tstatic class Converters {\r\n\t\t#region StringToValues\r\n\r\n\t\t#endregion\r\n\r\n\t\tpublic static Object StringToAssetValue(Type assetType, String value) {\r\n\t\t\treturn StringToAssetValue(TypeToDesiredString(assetType), value);\r\n\t\t}\r\n\r\n\t\tpublic static Object StringToAssetValue(String assetType, String value) {\r\n\t\t\tswitch (assetType.ToLower()) {\r\n\t\t\t\tcase \"string\":\r\n\t\t\t\tcase \"str\":\r\n\t\t\t\tcase \"texture2d\":\r\n\t\t\t\tcase \"texture\":\r\n\t\t\t\tcase \"sound\":\r\n\t\t\t\t\treturn value;\r\n\t\t\t\tcase \"animation\":\r\n\t\t\t\tcase \"animationsequence\":\r\n\t\t\t\t\treturn Parser.AnimationParser(value);\r\n\t\t\t\tcase \"vector\":\r\n\t\t\t\tcase \"vector2\":\r\n\t\t\t\t\treturn Parser.Vector2Parser(value);\r\n\t\t\t\tcase \"integer\":\r\n\t\t\t\tcase \"int\":\r\n\t\t\t\t\treturn Parser.IntegerParser(value)[0];\r\n\t\t\t\tcase \"float\":\r\n\t\t\t\t\treturn Parser.FloatParser(value)[0];\r\n\t\t\t\tcase \"bool\":\r\n\t\t\t\tcase \"boolean\":\r\n\t\t\t\tcase \"flag\":\r\n\t\t\t\t\treturn Parser.BooleanParser(value);\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException($\"Couldn't Convert '{value}' To Value Of Type '{assetType}'\");\r\n\t\t}\r\n\r\n\t\tpublic static String TypeToDesiredString(Type type) {\r\n\t\t\tswitch (type.Name.ToLower()) {\r\n\t\t\t\tcase \"int64\": case \"int32\": case \"int16\":\treturn \"Integer\";\r\n\t\t\t\tcase \"single\":\t\t\t\t\t\t\t\treturn \"Float\";\r\n\t\t\t\tcase \"string\":\t\t\t\t\t\t\t\treturn \"String\";\r\n\t\t\t\tcase \"vector2\":\t\t\t\t\t\t\t\treturn \"Vector\";\r\n\t\t\t\tcase \"boolean\":\t\t\t\t\t\t\t\treturn \"Bool\";\r\n\t\t\t\tcase \"animation\": case \"animationsequence\": return \"Animation\";\r\n\t\t\t\tcase \"flag\":\t\t\t\t\t\t\t\treturn \"Flag\";\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException($\"Couldn't Interpret '{type}' As Asset Type\");\r\n\t\t}\r\n\r\n\t\tpublic static Asset StringToAsset(String assetType, String assetID, Object value) {\r\n\t\t\tswitch (assetType.ToLower()) {\r\n\t\t\t\tcase \"string\":\r\n\t\t\t\t\treturn new Asset(typeof(String), assetID, value);\r\n\t\t\t\tcase \"texture2d\": case \"texture\":\r\n\t\t\t\t\treturn new TextureAsset(assetID, value);\r\n\t\t\t\tcase \"animation\": case \"animationsequence\":\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tvar sequence = (value is String) ? Parser.AnimationParser(value.ToString()) : (AnimationSequence)value;\r\n\t\t\t\t\t\treturn new AnimationAsset(assetID, sequence) { IsImportedAsset = sequence.IsImported };\r\n\t\t\t\t\t} catch (KeyNotFoundException) { throw new Exception($\"Animation {value.ToString()} Not Found\"); }\r\n\t\t\t\tcase \"vector\": case \"vector2\":\r\n\t\t\t\t\treturn new PositionAsset(assetID, value);\r\n\t\t\t\tcase \"integer\": case \"int\": case \"int16\": case \"int32\": case \"int64\":\r\n\t\t\t\t\treturn new IntegerAsset(assetID, value);\r\n\t\t\t\tcase \"float\": case \"single\":\r\n\t\t\t\t\treturn new FloatAsset(assetID, value);\r\n\t\t\t\tcase \"bool\": case \"boolean\":\r\n\t\t\t\t\treturn new BooleanAsset(assetID, value);\r\n\t\t\t\tcase \"flag\":\r\n\t\t\t\t\treturn new FlagAsset(assetID, value);\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException($\"Couldn't Convert '{value.ToString()}' To Asset of Type '{assetType}'\");\r\n\t\t}\r\n\t\t\r\n\t\tpublic static String ValueToString(Type type, Object value) {\r\n\t\t\tif (value is Asset) return $\"[{(value as Asset).assetID}]\"; // return assets as they should be\r\n\r\n\t\t\tswitch (type.Name.ToLower()) {\r\n\t\t\t\tcase \"int64\": case \"int32\": case \"int16\": case \"single\": case \"string\":\r\n\t\t\t\t\treturn value.ToString();\r\n\t\t\t\tcase \"animationsequence\":\r\n\t\t\t\t\tAnimationSequence sequence = value as AnimationSequence;\r\n\r\n\t\t\t\t\tif (!sequence.IsImported) { return \"{\"+sequence.Frames[0].ToFileContents()+\"}\"; } else {\r\n\t\t\t\t\t\treturn GV.CollectionManipulator.DictionaryGetKeyFromValue(GV.MonoGameImplement.importedAnimations, sequence);\r\n\t\t\t\t\t}\r\n\t\t\t\tcase \"vector2\": case \"vector\":\r\n\t\t\t\t\treturn $\"(X:{((Vector2)value).X.ToString().PadLeft(3, '0')}, Y:{((Vector2)value).Y.ToString().PadLeft(3, '0')})\";\r\n\t\t\t\tcase \"boolean\":\r\n\t\t\t\t\treturn (bool)value ? \"True\" : \"False\";\r\n\t\t\t\tcase \"flag\":\r\n\t\t\t\t\treturn (value as Flag).Value ? \"True\" : \"False\";\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException($\"Couldn't Convert String '{value.ToString()}' into object of type {type}\");\r\n\t\t}\r\n\r\n\t\tpublic static bool IsValidConversion(string type, string value) {\r\n\t\t\ttry { StringToAssetValue(type, value); return true; } catch { return false; }\r\n\t\t}\r\n\t}\r\n\r\n\tstatic class Parser {\r\n\t\t/// <summary>Checks whether the first line of a string matches a desired header</summary>\r\n\t\t/// <param name=\"line\">String representing first line of a given </param>\r\n\t\t/// <param name=\"header\">Header which line should match for correct return</param>\r\n\t\t/// <returns>Boolean indicating whether a line matches a desired header</returns>\r\n\t\tpublic static bool HeaderCheck(String line, String header) {\r\n\t\t\treturn line.Length >= header.Length && line.Substring(0, header.Length) == header;\r\n\t\t}\r\n\r\n\t\tpublic static String SystemPathExtracter(String line) {\r\n\t\t\t//Match pathMatch = Regex.Match(line, @\"[^ \\n\\r]+\\\\.+[^ \\n\\r]+\");\r\n\t\t\tMatch pathMatch = Regex.Match(line, @\"(([\\w]:\\\\)|\\\\)([^\\n\\r]+)\");\r\n\r\n\t\t\tif (pathMatch.Success) return pathMatch.Value.TrimStart('\\\\'); else {\r\n\t\t\t\tthrow new HollowAetherException($\"Couldn't Find A System Path in Line '{line}'\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static AnimationSequence AnimationParser(Object value) {\r\n\t\t\tif (value is AnimationSequence) return (AnimationSequence)value; // when default is sequence\r\n\r\n\t\t\tstring valString = value.ToString();\r\n\t\t\tbool isSingle = valString.Length > 2 && Frame.isFrameDefinitionRegexCheck.IsMatch(valString.Substring(1, valString.Length - 1));\r\n\t\t\t\r\n\t\t\tif (isSingle) {\r\n\t\t\t\ttry { return new AnimationSequence(0, Frame.FromFileContents(value.ToString(), true)); } \r\n\t\t\t\tcatch (Exception e) { throw new HollowAetherException($\"Animation Couldn't Be Extracted\", e); }\r\n\t\t\t} else {\r\n\t\t\t\ttry { return GV.MonoGameImplement.importedAnimations[value.ToString().ToLower()]; } \r\n\t\t\t\tcatch (Exception e) { throw new HollowAetherException($\"Animation Couldn't Be Extracted\", e); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Extracts value in a given string containing brackets</summary>\r\n\t\t/// <param name=\"line\">String containing parentheses/brackets</param>\r\n\t\t/// <returns>The contents of the given parentheses/brackets</returns>\r\n\t\tpublic static String GetValueInParentheses(String line) {\r\n\t\t\tif (Regex.Match(line, @\"(\\(.+\\))\").Success) {\r\n\t\t\t\tString brackets = Regex.Match(line, @\"\\((.*?)\\)\").Value; // Value & ()\r\n\t\t\t\treturn brackets.Substring(1, brackets.Length - 2); // Value Without ()\r\n\t\t\t} else { // Throw exception\r\n\t\t\t\tif (Regex.Match(line, @\"\\(\\)\").Success) {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Line {line} Has Empty Parentheses Values\");\r\n\t\t\t\t} else throw new HollowAetherException($\"Line {line} Doesn't Contains Parentheses\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Extracts value in a given string containing speech marks</summary>\r\n\t\t/// <param name=\"line\">String containing speech marks</param>\r\n\t\t/// <returns>The contents of the given speech marks</returns>\r\n\t\tpublic static String GetValueInSpeechMarks(String line) {\r\n\t\t\tMatch match = Regex.Match(line, \"([\\\"'])(?:(?=(\\\\\\\\?))\\\\2.)*?\\\\1\");\r\n\r\n\t\t\tif (!match.Success) // If no speech marks are in the given string\r\n\t\t\t\tthrow new HollowAetherException($\"Could Not Extract Value in Speech Marks For Line '{line}'\");\r\n\r\n\t\t\tif (match.Value.Length == 2) // When just empty speech marks like \"\"\r\n\t\t\t\tthrow new HollowAetherException($\"No Value Found in Speech Marks For Line '{line}'\");\r\n\r\n\t\t\treturn match.Value.Substring(1, match.Value.Length - 2);\r\n\t\t}\r\n\r\n\t\t/// <summary>Constructs a Vector from an input string</summary>\r\n\t\t/// <param name=\"line\">String containing vector in format (X:00, Y:00)</param>\r\n\t\t/// <returns>Vectorised value of vector in input string</returns>\r\n\t\tpublic static Vector2 Vector2Parser(String line) {\r\n\t\t\tString bracketContents = GetValueInParentheses(line); // Contents of (parenthesese)\r\n\t\t\tMatchCollection xyMatches = Regex.Matches(bracketContents, @\"([Xx||Yy]:-?\\d+)\");\r\n\r\n\t\t\tif (xyMatches.Count != 2) // Lines has more than just X or Y in the axis\r\n\t\t\t\tthrow new HollowAetherException($\"Line {line} doesn't Have Vector Values Formatted Correctly\");\r\n\r\n\t\t\tfloat X=float.NaN, Y=float.NaN;\r\n\r\n\t\t\t//Vector2 returnValue = new Vector2(); // Store vector which will be returned\r\n\r\n\t\t\tforeach (String xyMatch in (from Match N in xyMatches select N.Value)) {\r\n\t\t\t\tString[] splitMatch = xyMatch.Split(':'); // Index 0=Axis, 1=Value\r\n\r\n\t\t\t\tswitch (splitMatch[0]) {\r\n\t\t\t\t\tcase \"x\": case \"X\": X = FloatParser(splitMatch[1])[0]; break;\r\n\t\t\t\t\tcase \"y\": case \"Y\": Y = FloatParser(splitMatch[1])[0]; break;\r\n\t\t\t\t\tdefault: throw new HollowAetherException($\"Vector value has invalid axis '{splitMatch[0]}'\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (X == float.NaN) throw new HollowAetherException($\"X axis unassigned in float definition\");\r\n\t\t\tif (Y == float.NaN) throw new HollowAetherException($\"Y axis unassigned in float definition\");\r\n\r\n\t\t\treturn new Vector2(X, Y); // Return new vector corresponding to desired values\r\n\t\t}\r\n\r\n\t\t/// <summary>Method to convert a string to a boolean value</summary>\r\n\t\t/// <param name=\"line\">Line to extract boolean value from</param>\r\n\t\t/// <remarks>Acceptable boolean values=true, True, false, False</remarks>\r\n\t\tpublic static bool BooleanParser(String line) {\r\n\t\t\tif (Regex.Match(line, @\"[Tt]rue\").Success) return true;\r\n\t\t\tif (Regex.Match(line, @\"[Ff]alse\").Success) return false;\r\n\r\n\t\t\tthrow new HollowAetherException($\"Couldn't Convert Line '{line}' To A Boolean\");\r\n\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts String to intger</summary>\r\n\t\t/// <param name=\"line\">Line containing single integer</param>\r\n\t\t/// <returns>All Integers found in string</returns>\r\n\t\tpublic static Int32[] IntegerParser(String line) {\r\n\t\t\tMatchCollection matches = Regex.Matches(line, @\"-?\\d+\"); // All int matches, +ve || -ve\r\n\r\n\t\t\tif (matches.Count == 0) throw new HollowAetherException($\"No Integer Found In Line '{line}'\"); else {\r\n\t\t\t\ttry { return (from X in Enumerable.Range(0, matches.Count) select Int32.Parse(matches[X].Value)).ToArray(); }\r\n\t\t\t\tcatch { throw new HollowAetherException($\"Couldn't Convert '{line}' To Int\"); /*Because of casting error*/ }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts string to float</summary>\r\n\t\t/// <param name=\"line\">Line to convert to float</param>\r\n\t\t/// <returns>Float version of input string</returns>\r\n\t\tpublic static float[] FloatParser(String line) {\r\n\t\t\tMatchCollection matches = Regex.Matches(line, @\"[-+]?[0-9]*\\.?[0-9]+\"); // All float matches, +ve || -ve\r\n\r\n\t\t\tif (matches.Count == 0) throw new HollowAetherException($\"No Integer Found In Line '{line}'\"); else {\r\n\t\t\t\ttry { return (from X in Enumerable.Range(0, matches.Count) select float.Parse(matches[X].Value)).ToArray(); } \r\n\t\t\t\tcatch { throw new HollowAetherException($\"Couldn't Convert '{line}' To float\"); /*Because of casting error*/ }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.7045351266860962, "alphanum_fraction": 0.7209372520446777, "avg_line_length": 38.582820892333984, "blob_id": "c2ce445cab88be0c983db724bf2f8d3411aba494", "content_id": "a24330aa1ba96d68a24bdf1cc656dbca00df9536", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13232, "license_type": "no_license", "max_line_length": 132, "num_lines": 326, "path": "/HollowAether/Lib/GAssets/Weapons/Weapon.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic abstract class Weapon : CollideableSprite {\r\n\t\tpublic Weapon(Vector2 position, int width, int height, bool animationRunning)\r\n\t\t\t: base(position, width, height, animationRunning) { Layer = 0.65f; }\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates animation\r\n\r\n\t\t\tif (Thrown) UpdateThrown(); else if (Attacking) UpdateAttack(); else {\r\n\t\t\t\tImplementFloatingEffect(); // Make go up and down\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void ImplementFloatingEffect() {\r\n\t\t\ttimeFloating += elapsedMilitime; // \r\n\r\n\t\t\tOffsetSpritePosition(Y: floatingDirection * floatingVelocity * elapsedTime);\r\n\r\n\t\t\tif (timeFloating >= 2000) {\r\n\t\t\t\ttimeFloating -= 2000; // Push time back\r\n\t\t\t\tfloatingDirection = -floatingDirection;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic int GetDamage() {\r\n\t\t\treturn 25;\r\n\t\t}\r\n\r\n\t\tpublic abstract void SetWeaponPositionRelativeToPlayer(Player player);\r\n\r\n\t\tpublic virtual void Throw(float direction) {\r\n\t\t\tif (!CanBeThrown) throw new HollowAetherException($\"Weapon '{this.GetType()}' Can't Be Thrown\");\r\n\t\t}\r\n\r\n\t\tpublic virtual void StopThrowing() { Thrown = false; }\r\n\r\n\t\tpublic virtual void ReturnThrownWeaponToPlayer() {\r\n\t\t\treturningToPlayer = true;\r\n\t\t}\r\n\r\n\t\tprotected virtual void UpdateThrown() { } // Optional\r\n\r\n\t\tprotected abstract void UpdateAttack();\r\n\r\n\t\tpublic virtual void Reset(Player player) {\r\n\t\t\tif (Thrown) StopThrowing();\r\n\r\n\t\t\tAttachToPlayer(player);\r\n\t\t}\r\n\r\n\t\tpublic virtual void Attack(Player player) {\r\n\t\t\tAttacking = true;\r\n\t\t}\r\n\r\n\t\tpublic abstract void AttachToPlayer(Player player);\r\n\r\n\t\tprotected virtual void FinishAttacking() {\r\n\t\t\tAttacking = false;\r\n\t\t}\r\n\r\n\t\tprivate float floatingVelocity = 3f;\r\n\r\n\t\tprivate int timeFloating = 0, floatingDirection = +1;\r\n\r\n\t\tpublic bool returningToPlayer = false;\r\n\r\n\t\tpublic bool Thrown { get; protected set; } = false;\r\n\r\n\t\tpublic abstract bool CanBeThrown { get; protected set; }\r\n\r\n\t\tpublic bool Attacking { get; protected set; } = false;\r\n\r\n\t\tpublic bool CanAttack { get { return !Attacking && !Thrown; } }\r\n\r\n\t\tpublic bool CanThrow { get { return CanBeThrown && CanAttack; } }\r\n\r\n\t\tpublic bool CanCallThrownWeaponBack { get { return CanBeThrown && Thrown && !returningToPlayer; } }\r\n\t}\r\n\r\n\tpublic abstract class SwordLikeWeapon : Weapon {\r\n\t\tpublic SwordLikeWeapon(Vector2 position, int width, int height, bool animationRunning)\r\n\t\t\t: base(position, width, height, animationRunning) { }\r\n\r\n\t\tpublic override void Attack(Player player) {\r\n\t\t\tbase.Attack(player);\r\n\r\n\t\t\tswingDirection = GV.MonoGameImplement.Player.FacingLeft ? -1 : 1;\r\n\t\t\tTrueBoundary.Rotation = (float)(-swingDirection * Math.PI / 4);\r\n\r\n\t\t\tAnimation.SetAnimationSequence(swingDirection > 0 ? \"315\" : \"045\");\r\n\r\n\t\t\tSwingAcceleration = new Vector2(-swingDirection * SWING_ACCELERATION, -SWING_ACCELERATION);\r\n\t\t\tswingVelocity = new Vector2(+swingDirection * SWING_INITIAL_VELOCITY, +SWING_INITIAL_VELOCITY);\r\n\t\t}\r\n\r\n\t\tprotected override void UpdateAttack() {\r\n\t\t\tif (!backSwing) { TrueBoundary.Rotation += SWING_ANGULAR_SPEED * elapsedTime; } else {\r\n\t\t\t\tfloat newRotation = TrueBoundary.Rotation - (SWING_ANGULAR_SPEED * elapsedTime); // Store new rotation\r\n\r\n\t\t\t\tnewRotation = (newRotation < 0) ? newRotation : (float)GV.BasicMath.NormaliseRadianAngle(newRotation);\r\n\t\t\t\tTrueBoundary.Rotation = newRotation; // Set rotation to new normalised rotation. Always positive, kay.\r\n\t\t\t}\r\n\r\n\t\t\tSetAnimationFromRotation(); // Set animation for sword from current sprite rotation.\r\n\t\t\t\r\n\t\t\tif (!backSwing && TrueBoundary.Rotation > MAX_SWING_ANGULAR_ROTATION) {\r\n\t\t\t\tbackSwing = true; // Set back swing to true to reverse swing animation\r\n\t\t\t} else if (backSwing && TrueBoundary.Rotation < 0) FinishAttacking();\r\n\r\n\t\t\tswingVelocity += SwingAcceleration * elapsedTime; // Increment velocity\r\n\t\t\tOffsetSpritePosition(swingVelocity * elapsedTime); // Give displacement\r\n\t\t}\r\n\r\n\t\tprotected override void FinishAttacking() {\r\n\t\t\tbase.FinishAttacking();\r\n\r\n\t\t\tPlayer player = GV.MonoGameImplement.Player;\r\n\r\n\t\t\tbackSwing = false; // Reset backswing for next attack\r\n\t\t\tAttachToPlayer(player); // Sets rotation & position\r\n\t\t}\r\n\r\n\t\tpublic override void Throw(float direction) {\r\n\t\t\tbase.Throw(direction); // Throws exception if trying to throw non throwable\r\n\r\n\t\t\tThrown = true; timeBeingThrown = 0; returningToPlayer = false; // Reset throw vars\r\n\r\n\t\t\tVector2 sinCosRatio = new Vector2(\r\n\t\t\t\t(float)Math.Round(Math.Cos(direction), 5),\r\n\t\t\t\t(float)Math.Round(Math.Sin(direction), 5)\r\n\t\t\t);\r\n\r\n\t\t\tthrownLinearVelocity = sinCosRatio * new Vector2(DefaultLinearThrowVelocity);\r\n\t\t\tthrowDeceleration = sinCosRatio * new Vector2(DefaultThrowDeceleration);\r\n\t\t\t\r\n\t\t\tthrownDirection = new Vector2((thrownLinearVelocity.X > 0) ? +1 : -1, (thrownLinearVelocity.Y > 0) ? +1 : -1);\r\n\t\t\t\r\n\t\t\tinitialHorizontalVelocity0 = thrownLinearVelocity.X == 0;\r\n\t\t\tinitialVerticalVelocity0 = thrownLinearVelocity.Y == 0;\r\n\t\t}\r\n\r\n\t\tprotected override void UpdateThrown() {\r\n\t\t\tTrueBoundary.Rotation += AngularThrowVelocity * elapsedTime; // Further weapon rotation as required\r\n\t\t\tSetAnimationFromRotation(); // Set animation for sword from current sprite rotation. \r\n\r\n\t\t\tif (returningToPlayer) UpdateReturningToPlayer(); else {\r\n\t\t\t\tOffsetSpritePosition(thrownLinearVelocity * elapsedTime); // Offset due to linear velocity\r\n\t\t\t\tthrownLinearVelocity -= throwDeceleration * elapsedTime; // Decelerate linear velocity as required\r\n\r\n\t\t\t\tbool directionChangedHorizontally = !initialHorizontalVelocity0 && DirectionChanged(thrownLinearVelocity.X, thrownDirection.X);\r\n\t\t\t\tbool directionChangedVertically = !initialVerticalVelocity0 && DirectionChanged(thrownLinearVelocity.Y, thrownDirection.Y); \r\n\t\t\t\t\r\n\t\t\t\tif (directionChangedHorizontally || directionChangedVertically) { ReturnThrownWeaponToPlayer(); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static bool DirectionChanged(float velocity, float thrownDirection) {\r\n\t\t\treturn (velocity > 0 && thrownDirection < 0) || (velocity < 0 && thrownDirection > 0);\r\n\t\t}\r\n\r\n\t\tpublic override void ReturnThrownWeaponToPlayer() {\r\n\t\t\tbase.ReturnThrownWeaponToPlayer();\r\n\r\n\t\t\tSetAngleVelocityEtcToPlayer(); // Set initial return velocity to towards player\r\n\t\t}\r\n\r\n\t\tprivate void SetAngleVelocityEtcToPlayer() {\r\n\t\t\tVector2 player = GV.MonoGameImplement.Player.Position; // Store position for theta calc\r\n\t\t\tfloat directionTheta = (float)Math.Atan2(player.Y - Position.Y, player.X - Position.X);\r\n\t\t\tVector2 sinCosRatio = new Vector2((float)Math.Cos(directionTheta), (float)Math.Sin(directionTheta));\r\n\r\n\t\t\tthrownLinearVelocity = sinCosRatio * new Vector2(DefaultReturnThrowVelocity); // Return to player\r\n\t\t}\r\n\r\n\t\tprivate void UpdateReturningToPlayer() {\r\n\t\t\tOffsetSpritePosition(thrownLinearVelocity * elapsedTime); // Offset due to linear velocity\r\n\t\t\tthrownLinearVelocity -= throwDeceleration * elapsedTime; // Change acceleration appropriately\r\n\r\n\t\t\tSetAngleVelocityEtcToPlayer(); // Got tired of deciding when so just always do\r\n\t\t}\r\n\r\n\t\tpublic override void AttachToPlayer(Player player) {\r\n\t\t\tTrueBoundary.Rotation = (player.FacingRight) ? FACING_RIGHT_ROTATION : FACING_LEFT_ROTATION;\r\n\t\t\tSetAnimationFromRotation(); // Set animation for sword from current sprite rotation. \r\n\r\n\t\t\tSetWeaponPositionRelativeToPlayer(player); // Whether to place weapon to left or right of player.\r\n\t\t}\r\n\r\n\t\tpublic override void SetWeaponPositionRelativeToPlayer(Player player) {\r\n\t\t\tVector2 direction = new Vector2((player.FacingLeft) ? +1 : -1, -1); // Direction to push on x axis\r\n\r\n\t\t\tOffsetSpritePosition((player.Position + (direction * new Vector2(Size.X / 2, Size.Y / 4))) - Position);\r\n\t\t}\r\n\r\n\t\tprotected void SetAnimationFromRotation() {\r\n\t\t\tint degrees = (int)Math.Round(GV.BasicMath.RadiansToDegrees(TrueBoundary.Rotation));\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, 8)) {\r\n\t\t\t\tif (45 * X <= degrees && degrees < 45 * (X + 1)) { // Between range 45\r\n\t\t\t\t\tAnimation.SetAnimationSequence((45 * X).ToString().PadLeft(3, '0'));\r\n\t\t\t\t\tbreak; // Once valid animation set, break method & return to caller\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Recursively determines what rotation weapon is on and subsequently set weapon animation</summary>\r\n\t\t/// <param name=\"degrees\">Actual degrees value. Allow parameterised to prevent repeated calculation</param>\r\n\t\t/// <param name=\"acuteCount\">Current Rotation Multiple Of 45 Degrees. Max should be (360 / 45)-1 = 7</param>\r\n\t\tprotected void RecursiveSetAnimationFromRotation(int? degrees=null, int acuteCount=7) {\r\n\t\t\tdegrees = degrees.HasValue ? degrees.Value : (int)Math.Round(GV.BasicMath.RadiansToDegrees(TrueBoundary.Rotation));\r\n\r\n\t\t\tif (acuteCount == -1) return; // initial acute count was too small to effectively reach the appropriate angle\r\n\r\n\t\t\tif (45 * acuteCount <= degrees && degrees < 45 * (acuteCount + 1)) {\r\n\t\t\t\t// When acute is within range of 45 Degrees of the current weapon rotation\r\n\t\t\t\tAnimation.SetAnimationSequence((45 * acuteCount).ToString().PadLeft(3, '0'));\r\n\t\t\t} else RecursiveSetAnimationFromRotation(degrees, acuteCount - 1);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"000\"] = new AnimationSequence(0, new Frame(00, 00, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"045\"] = new AnimationSequence(0, new Frame(01, 00, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"090\"] = new AnimationSequence(0, new Frame(02, 00, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"135\"] = new AnimationSequence(0, new Frame(03, 00, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"180\"] = new AnimationSequence(0, new Frame(00, 01, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"225\"] = new AnimationSequence(0, new Frame(01, 01, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"270\"] = new AnimationSequence(0, new Frame(02, 01, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\t\t\tAnimation[\"315\"] = new AnimationSequence(0, new Frame(03, 01, FrameWidth, FrameHeight, FrameWidth, FrameHeight));\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"000\"); // Default animation points directly up\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tfloat rotation = (boundary != null) ? TrueBoundary.Rotation : 0; // Boundary being rebuilt, so maintain rotation\r\n\r\n\t\t\tVector2 boundaryPosition = Position + (ActualSize.ToVector2() / 2) + new Vector2(HorizontalBoundaryOffset, 0);\r\n\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect,\r\n\t\t\t\tnew IBRotatedRectangle(new Rectangle(boundaryPosition.ToPoint(), ActualSize), rotation)\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\t#region Properties\r\n\t\t#region Boundaries\r\n\t\tprivate IBRotatedRectangle TrueBoundary { get { return (IBRotatedRectangle)Boundary.Boundaries[0]; } }\r\n\r\n\t\tpublic abstract int HorizontalBoundaryOffset { get; protected set; }\r\n\r\n\t\t#region Dimensions\r\n\t\tpublic abstract int ActualWeaponWidth { get; protected set; }\r\n\r\n\t\tpublic abstract int ActualWeaponHeight { get; protected set; }\r\n\r\n\t\tpublic abstract int FrameWidth { get; protected set; }\r\n\r\n\t\tpublic abstract int FrameHeight { get; protected set; }\r\n\r\n\t\tprivate Point ActualSize { get { return new Point(ActualWeaponWidth, ActualWeaponHeight); } }\r\n\t\t#endregion\r\n\t\t#endregion\r\n\r\n\t\t#region ThrowVars\r\n\t\t#region Kinematics\r\n\t\tpublic virtual float DefaultLinearThrowVelocity { get; protected set; } = 200f;\r\n\r\n\t\tpublic virtual float DefaultReturnThrowVelocity { get; protected set; } = 200f;\r\n\r\n\t\tprotected virtual float DefaultThrowDeceleration { get; set; } = 65f;\r\n\t\t#endregion\r\n\r\n\t\tpublic override bool CanBeThrown { get; protected set; } = true;\r\n\r\n\t\tpublic abstract float AngularThrowVelocity { get; protected set; }\r\n\t\t#endregion\r\n\r\n\t\t#region SwingVars\r\n\t\tprivate const float SWING_ANGULAR_SPEED = (float)(Math.PI * 4.5); // 1 Swing every 250 ms\r\n\t\t\r\n\t\tprivate const float MAX_SWING_ANGULAR_ROTATION = (float)(Math.PI * 1.45f);\r\n\r\n\t\tprivate Vector2 SwingAcceleration { get; set; }\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\tprivate bool backSwing;\r\n\r\n\t\tprivate Vector2 swingVelocity;\r\n\r\n\t\tprotected int timeBeingThrown;\r\n\r\n\t\tprivate int swingDirection = 0; // Direction sword is swung\r\n\r\n\t\tprivate const int SWING_DISPLACEMENT = 24; // On either axis\r\n\r\n\t\tprivate bool initialVerticalVelocity0, initialHorizontalVelocity0;\r\n\r\n\t\tprivate Vector2 thrownDirection, thrownLinearVelocity, throwDeceleration;\r\n\r\n\t\tprivate const float FACING_RIGHT_ROTATION = (float)(335 * (Math.PI / 180));\r\n\r\n\t\tprivate const float FACING_LEFT_ROTATION = (float)(045 * (Math.PI / 180));\r\n\r\n\t\tprivate const float MILITIME_PER_SWING = (float)((MAX_SWING_ANGULAR_ROTATION + (Math.PI / 4)) / SWING_ANGULAR_SPEED);\r\n\r\n\t\tprivate static readonly float SWING_ACCELERATION = GV.Physics.CalculateGravity(SWING_DISPLACEMENT, MILITIME_PER_SWING);\r\n\r\n\t\tprivate static readonly float SWING_INITIAL_VELOCITY = GV.Physics.GetJumpVelocity(SWING_ACCELERATION, SWING_DISPLACEMENT);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7220279574394226, "alphanum_fraction": 0.724125862121582, "avg_line_length": 38.28168869018555, "blob_id": "37002aa7bf5774b7421b353e3b4e7c815610a6f4", "content_id": "d1f47eaa1801ebbb9b4980e54650b49c1d600fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5722, "license_type": "no_license", "max_line_length": 126, "num_lines": 142, "path": "/HollowAether/Lib/Entity/GameEntity.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing HollowAether.Lib.GAssets;\r\nusing System.Windows.Forms;\r\nusing System.Drawing;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib;\r\nusing T = System.Threading.Thread;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether {\r\n\tpublic class GameEntity : Object, ICloneable {\r\n\t\tprivate class EntityAttributeCollection : Dictionary<String, EntityAttribute>, ICloneable {\r\n\t\t\tpublic EntityAttributeCollection() : base() { }\r\n\r\n\t\t\tpublic object Clone() {\r\n\t\t\t\tEntityAttributeCollection clone = new EntityAttributeCollection();\r\n\r\n\t\t\t\tforeach (KeyValuePair<String, EntityAttribute> keyValuePair in this) {\r\n\t\t\t\t\tclone.Add(keyValuePair.Key, (EntityAttribute)keyValuePair.Value.Clone());\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn clone; // Return cloned entity attribute collection\r\n\t\t\t}\r\n\r\n\t\t\tpublic EntityAttributeCollection CastClone() {\r\n\t\t\t\treturn Clone() as EntityAttributeCollection;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic GameEntity(string entityId) {\r\n\t\t\tforeach (KeyValuePair<String, EntityAttribute> defaultParams in GetDefaultEntityParameters()) {\r\n\t\t\t\tentityAttributes[defaultParams.Key] = defaultParams.Value; // Assign default Params\r\n\t\t\t}\r\n\r\n\t\t\tEntityType = entityId;\r\n\t\t}\r\n\r\n\t\tpublic GameEntity(string entityId, KeyValuePair<String, EntityAttribute>[] args) : this(entityId) {\r\n\t\t\tforeach (var defaultParams in args) { // Any argument attributes\r\n\t\t\t\tif (!entityAttributes.ContainsKey(defaultParams.Key)) entityAttributes.Add(defaultParams.Key, defaultParams.Value); else {\r\n\t\t\t\t\tentityAttributes[defaultParams.Key] = defaultParams.Value; // If has existing texture\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Clones current entity instance</summary>\r\n\t\t/// <returns>Shallow clone of current Game Entity</returns>\r\n\t\tpublic Object Clone() {\r\n\t\t\tGameEntity self = MemberwiseClone() as GameEntity;\r\n\r\n\t\t\tself.entityAttributes = this.entityAttributes.CastClone();\r\n\r\n\t\t\treturn self; // Return cloned game entity instance\r\n\t\t}\r\n\r\n\t\tpublic Object Clone(RectangleF newRegion) {\r\n\t\t\tGameEntity self = this.Clone() as GameEntity;\r\n\r\n\t\t\tself[\"Position\"].Value = new Vector2(newRegion.X, newRegion.Y);\r\n\t\t\tself[\"Width\"].Value = (int)newRegion.Width;\r\n\t\t\tself[\"Height\"].Value = (int)newRegion.Height;\r\n\r\n\t\t\treturn self; // Return new self adjusted to region\r\n\t\t}\r\n\r\n\t\tprivate static ICollection<KeyValuePair<String, EntityAttribute>> GetDefaultEntityParameters(\r\n\t\t\t\tVector2? position = null, int width = 0, int height = 0, \r\n\t\t\t\tstring texture = \"\", bool animRunning=true, float layer=0.1f) {\r\n\t\t\tVector2 positionVal = position.HasValue ? position.Value : Vector2.Zero; // Value From Argument\r\n\r\n\t\t\treturn new KeyValuePair<String, EntityAttribute>[] {\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"Position\",\t\t GetEntityAttribute(positionVal, Vector2.Zero)),\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"Width\",\t\t\t GetEntityAttribute(width, 0)),\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"Height\",\t\t\t GetEntityAttribute(height, 0)),\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"Texture\",\t\t GetEntityAttribute(texture, String.Empty)),\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"AnimationRunning\", new EntityAttribute(animRunning, typeof(bool), false)),\r\n\t\t\t\tnew KeyValuePair<string, EntityAttribute>(\"Layer\",\t\t\t new EntityAttribute(layer, typeof(float), false)),\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate static EntityAttribute GetEntityAttribute<T>(T defaultValue, T nullValue, bool readOnly=false) {\r\n\t\t\tif (defaultValue.Equals(nullValue)) { return new EntityAttribute(typeof(T), readOnly); } else {\r\n\t\t\t\treturn new EntityAttribute(defaultValue, typeof(T), readOnly); // With default value\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void AddEntityAttribute(string key, EntityAttribute value) {\r\n\t\t\tif (entityAttributes.ContainsKey(key)) throw new HollowAetherException($\"Entity Key '{key}' Already Exists\");\r\n\t\t\tentityAttributes.Add(key, value); // Store new entity attribute to existing attribute store/collection\r\n\t\t}\r\n\r\n\t\tpublic void AssignAttribute(String key, object value) {\r\n\t\t\tGetAttribute(key).Value = value;\r\n\t\t}\r\n\t\r\n\t\tpublic String[] GetEntityAttributes() {\r\n\t\t\treturn entityAttributes.Keys.ToArray();\r\n\t\t}\r\n\r\n\t\tpublic EntityAttribute GetAttribute(string key) {\r\n\t\t\tif (entityAttributes.ContainsKey(key)) return entityAttributes[key]; else {\r\n\t\t\t\tthrow new HollowAetherException($\"Entity '{EntityType}' Doesn't Possess Attribute '{key}'\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool AttributeExists(string key) { return entityAttributes.ContainsKey(key); }\r\n\r\n\t\tpublic String ToFileContents(string assetID) {\r\n\t\t\tstring entityName = T.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(EntityType);\r\n\r\n\t\t\tvar attributeEnumerable = from X in entityAttributes where X.Value.IsAssigned select $\"{X.Key}={X.Value.ToFileContents()}\";\r\n\t\t\t\r\n\t\t\tvar attributes = (attributeEnumerable).Aggregate((a, b) => $\"{a}<{b}\"); // Convert to attribute string\r\n\r\n\t\t\treturn ($\"GameEntity: \\\"{entityName}\\\" as [{assetID}] \" + (attributes.Length > 0 ? \"<\" : \"\") + attributes).Trim();\r\n\t\t}\r\n\r\n\t\tpublic IMonoGameObject ToIMGO() {\r\n\t\t\tIMonoGameObject _object = GlobalVars.EntityGenerators.StringToMonoGameObject(EntityType);\r\n\t\t\t_object.AttatchEntity(this);\r\n\t\t\treturn _object;\r\n \t\t}\r\n\r\n\t\tpublic string EntityType { get; private set; }\r\n\r\n\t\tpublic EntityAttribute this[string key] { get { return GetAttribute(key); } }\r\n\r\n\t\t/// <summary>Key/Value store holding relevent entity attributes for game entity instance</summary>\r\n\t\tprivate EntityAttributeCollection entityAttributes = new EntityAttributeCollection();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6921274662017822, "alphanum_fraction": 0.6954076886177063, "avg_line_length": 34.7931022644043, "blob_id": "90ba216c145d85642bcfbee020b40d6fdd1467a8", "content_id": "b3183710613120bced3776ae3fe1c6f78834f27c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2136, "license_type": "no_license", "max_line_length": 131, "num_lines": 58, "path": "/HollowAether/Lib/Debug/DebugPrinter.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n\r\nnamespace HollowAether.Lib.Debug {\r\n\tpublic static class DebugPrinter {\r\n\t\tpublic static void Draw() {\r\n\t\t\tif (!DebugPrinter.enabled) return; // Not enabled, return without draw\r\n\r\n\t\t\tfloat maxX = (from X in debugArgs.Keys select font.MeasureString(KeyToString(X))).Aggregate((a,b) => (a.X >= b.X) ? a : b).X;\r\n\t\t\t// Run through all debug args and measure their string representations as Vectors. Then select the one with the greatest X value\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Begin();\r\n\t\t\tVector2 init = new Vector2(5, 5);\r\n\r\n\t\t\tforeach (String key in debugArgs.Keys) {\r\n\t\t\t\tString value = (debugArgs[key] == null) ? \"None\" : debugArgs[key].ToString();\r\n\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(font, $\"{key}: {value}\", init, color);\r\n\r\n\t\t\t\tinit += new Vector2(0, font.MeasureString($\"{key}: {value}\").Y + 5);\r\n\t\t\t}\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tprivate static String KeyToString(String key) {\r\n\t\t\treturn $\"{key}: {debugArgs[key]}\";\r\n\t\t}\r\n\r\n\t\tpublic static void Add(String parameter, Object value = null) {\r\n\t\t\tdebugArgs.Add(parameter, value);\r\n\t\t}\r\n\r\n\t\t/// <summary>Sets the value for a debug printer target</summary>\r\n\t\t/// <param name=\"parameter\">Parameter key for variable</param>\r\n\t\t/// <param name=\"value\">New value for target variable</param>\r\n\t\t/// <exception cref=\"System.FormatException\">Parameter doesn't exist</exception>\r\n\t\tpublic static void Set(String parameter, Object value) {\r\n\t\t\tif (!debugArgs.ContainsKey(parameter))\r\n\t\t\t\tthrow new FormatException($\"Paramter '{parameter}' Doesn't Exist\");\r\n\r\n\t\t\tdebugArgs[parameter] = value;\r\n\t\t}\r\n\r\n\t\tpublic static Color color = Color.White;\r\n\t\tpublic static Boolean enabled = true;\r\n\r\n\t\tstatic Dictionary<String, Object> debugArgs = new Dictionary<String, Object>();\r\n\t\tstatic SpriteFont font { get { return GV.MonoGameImplement.fonts[\"debugfont\"]; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7085828185081482, "alphanum_fraction": 0.7092481851577759, "avg_line_length": 25.83333396911621, "blob_id": "1478942461e0ada72d39d0c27dd009760dc25578", "content_id": "019deb8bd25d49a8d32e18f478c4fa7504175cc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1505, "license_type": "no_license", "max_line_length": 84, "num_lines": 54, "path": "/HollowAether/Lib/Global/GlobalVars/CollectionManipulator.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class CollectionManipulator {\r\n\t\t\tpublic static T[] GetSubArray<T>(T[] array, int index, int length) {\r\n\t\t\t\tT[] result = new T[length];\r\n\t\t\t\tArray.Copy(array, index, result, 0, length);\r\n\t\t\t\treturn result;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static K DictionaryGetKeyFromValue<K, V>(Dictionary<K, V> dict, V value) {\r\n\t\t\t\tforeach (K key in dict.Keys) {\r\n\t\t\t\t\tif (dict[key].Equals(value)) // If value found\r\n\t\t\t\t\t\treturn key; // Then return found key\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthrow new Exception($\"Value {value.ToString()} Not Found In Dictionary\");\r\n\t\t\t}\r\n\r\n\t\t\tpublic static void SwapListValues<T>(IList<T> list, int indexA, int indexB) {\r\n\t\t\t\tT tmp\t\t = list[indexA];\r\n\t\t\t\tlist[indexA] = list[indexB];\r\n\t\t\t\tlist[indexB] = tmp;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7016241550445557, "alphanum_fraction": 0.7039443254470825, "avg_line_length": 32.75806427001953, "blob_id": "be5ba1149f62d7fc9e0b51baa891ed03ac755222", "content_id": "7cd86e282746ca8eed4b5af5aa163ea5c90ffff4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2157, "license_type": "no_license", "max_line_length": 101, "num_lines": 62, "path": "/HollowAether/Lib/GAssets/Animation/AnimationChain.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic class AnimationChain {\r\n\t\tpublic AnimationChain(params AnimationSequence[] sequences) {\r\n\t\t\tchain = sequences.ToList<AnimationSequence>();\r\n\t\t\tframeCounter = CurrentSequence.Length;\r\n\t\t}\r\n\r\n\t\tpublic bool Update() {\r\n\t\t\tif (frameCounter != 0) frameCounter -= 1; else {\r\n\t\t\t\tchain.RemoveAt(0); // Pop current sequence Entry\r\n\t\t\t\tif (ChainAlive) frameCounter = CurrentSequenceLength;\r\n\t\t\t}\r\n\r\n\t\t\tif (ChainAlive) currentSequenceFrame = CurrentSequence.GetFrame(); // Set Current Sequence\r\n\t\t\telse ChainFinished(); // Call event handler if animation chain has been completed\r\n\r\n\t\t\treturn ChainAlive; // Return Value To Ensure Program Knows Whether Chain Has Ended Or Not\r\n\t\t}\r\n\r\n\t\tpublic Frame GetFrame() { return currentSequenceFrame; }\r\n\r\n\t\tpublic int GetLongLength() { return (from X in chain select X.Length).Aggregate((a, b) => a + b); }\r\n\r\n\t\t/// <summary>Current animation sequence length</summary>\r\n\t\tprivate int CurrentSequenceLength { get { return CurrentSequence.Length; } }\r\n\r\n\t\t/// <summary>Current animation sequence in chain</summary>\r\n\t\tAnimationSequence CurrentSequence {\r\n\t\t\tget {\r\n\t\t\t\ttry { return chain[0]; } // Top of chain is always the current animation sequence for chain\r\n\t\t\t\tcatch { throw new HollowAetherException($\"Cannot retrieve sequence when chain empty\"); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Number of animation sequences in chain</summary>\r\n\t\tpublic int Length { get { return chain.Count; } }\r\n\r\n\t\t/// <summary>Whether chain is still running</summary>\r\n\t\tpublic bool ChainAlive { get { return Length > 0; } }\r\n\r\n\t\t/// <summary>Number of frames in chain</summary>\r\n\t\tpublic int LongLength { get { return GetLongLength(); } }\r\n\r\n\t\tprivate int frameCounter;\r\n\t\t\r\n\t\tprivate Frame currentSequenceFrame;\r\n\r\n\t\t/// <summary>Sequences in chain</summary>\r\n\t\tprivate List<AnimationSequence> chain;\r\n\r\n\t\tpublic event Action ChainFinished = () => { };\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6939443349838257, "alphanum_fraction": 0.6993657946586609, "avg_line_length": 40.324676513671875, "blob_id": "4241f2e2af76a7864e5e2ca9d9eb5e35146b67b8", "content_id": "383c37e59df5ba99536b706825edaa951379ab89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 19554, "license_type": "no_license", "max_line_length": 130, "num_lines": 462, "path": "/HollowAether/Lib/GAssets/HUD/ContextMenu.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\t/// <summary>Menu class to display text to user</summary>\r\n\t/// <remarks>\r\n\t///\t\tCOMMANDS-LIST:\r\n\t///\t\t\t#COLOR : MGColorValue;\r\n\t///\t\t\t#ROTATE : Value;\r\n\t///\t\t\t#FX : (None || FlipX || FlipY);\r\n\t///\t\t\t#SYS : (CLS || PauseForInput);\r\n\t///\t\t\t#WAIT : Value;\r\n\t/// </remarks>\r\n\tpublic static partial class ContextMenu {\r\n\t\tenum ContextType { OK_Cancel, None };\r\n\r\n\t\tpublic static event Action WhenDone;\r\n\t\tpublic static event Action<bool> OkContextMenuComplete;\r\n\t\tprivate static event Action MoveToNextLine;\r\n\t\tprivate static event Action MoveToNextWord;\r\n\t\tprivate static event Action<ContextSpriteCharacter> AddNewCharacter;\r\n\t\tprivate static event Action RemoveTopLine;\r\n\t\tprivate static event Action ClearScreen;\r\n\r\n\t\tstatic ContextMenu() {\r\n\t\t\tGV.MonoGameImplement.textures[\"white\"] = GV.TextureCreation.GenerateBlankTexture(Color.White);\r\n\t\t\tInitialiseEventHandlers(); // Event handlers for events which remain consistent throughout\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds events and event handlers</summary>\r\n\t\tprivate static void InitialiseEventHandlers() {\r\n\t\t\tMoveToNextWord = () => { contextStringWordIndex++; contextStringCharIndex = 0; };\r\n\t\t\tMoveToNextWord += ContextMenu_MoveToNextWord_SetNewCharaSpritePosition; // handler\r\n\r\n\t\t\tRemoveTopLine = ContextMenu_RemoveTopLine_EventHandler; // Default handler\r\n\r\n\t\t\tMoveToNextLine = ContextMenu_MoveToNextLine_SetPreviousCharaPositions; // -> Method\r\n\r\n\t\t\tClearScreen = () => { position = defaultPosition; charactersToDraw.Clear(); };\r\n\t\t\tClearScreen += () => { invokeClearScreen = false; }; // Prevent handler being called\r\n\r\n\t\t\tAddNewCharacter = (sprite) => charactersToDraw.Add(sprite); // First add new sprite \r\n\t\t\tAddNewCharacter += (sprite) => contextStringCharIndex++; // Move to next char in word \r\n\t\t\tAddNewCharacter += (sprite) => position.X += sprite.Size().X; // Move to next position\r\n\t\t\tAddNewCharacter += (sprite) => charAppensionTimer = 0; // Reset timer till next chara\r\n\t\t}\r\n\r\n\t\tprivate static void ContextMenu_RemoveTopLine_EventHandler() {\r\n\t\t\tint currentIndex = lineBreakIndexes[0]; // Store before removal from list\r\n\t\t\tcharactersToDraw.RemoveRange(0, currentIndex+1); // +1 = Ranges Are Weird\r\n\t\t\tlineBreakIndexes.RemoveAt(0); // No longer line break index for sure, so del\r\n\r\n\t\t\tif (lineBreakIndexes.Count > 0) {\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, lineBreakIndexes.Count))\r\n\t\t\t\t\tlineBreakIndexes[X] -= currentIndex + 1; // Push backwards\r\n\t\t\t}\r\n\r\n\t\t\tif (charactersToDraw.Count > 0) InitiateCharaPushToTop();\r\n\r\n\t\t\tinvokeRemoveTopLine = false; // Prevent handler being called again\r\n\t\t}\r\n\r\n\t\tprivate static void ContextMenu_MoveToNextLine_SetPreviousCharaPositions() {\r\n\t\t\tif (charactersToDraw.Count == 0 || charactersToDraw[0].BeingPushed) return;\r\n\r\n\t\t\tif (charactersToDraw[0].Position == defaultPosition)\r\n\t\t\t\tInitiateCharaPushToTop();\r\n\r\n\t\t\tif (position.Y + FontSize >= textContainerBoundary.Bottom)\r\n\t\t\t\tinvokeRemoveTopLine = true;\r\n\r\n\t\t\tposition = new Vector2(defaultPosition.X, position.Y + FontSize);\r\n\t\t\tlineBreakIndexes.Add(charactersToDraw.Count - 1); // Store index\r\n\t\t}\r\n\r\n\t\tprivate static void InitiateCharaPushToTop() {\r\n\t\t\tif (charactersToDraw.Count == 0) {\r\n\t\t\t\tposition = new Vector2(defaultPosition.X, textContainerBoundary.Location.Y);\r\n\t\t\t} else {\r\n\t\t\t\tVector2 newPosition = new Vector2(charactersToDraw[0].Position.X, textContainerBoundary.Location.Y);\r\n\t\t\t\tcharactersToDraw[0].PushTo(newPosition, 0.85f); // Push character upwards, while maintaining X-position\r\n\r\n\t\t\t\tcharactersToDraw[0].PushPack.SpriteOffset += (sprite, offset) => {\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(1, charactersToDraw.Count - 1))\r\n\t\t\t\t\t\tcharactersToDraw[X].Position += offset;\r\n\r\n\t\t\t\t\tposition += offset;\r\n\t\t\t\t};\r\n\r\n\t\t\t\tcharactersToDraw[0].PushPack.SpriteSet += (sprite, newPos, oldPos) => {\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(1, charactersToDraw.Count - 1))\r\n\t\t\t\t\t\tcharactersToDraw[X].Position += newPos - oldPos;\r\n\r\n\t\t\t\t\tposition += newPos - oldPos;\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static List<int> lineBreakIndexes = new List<int>();\r\n\r\n\t\tprivate static void ContextMenu_MoveToNextWord_SetNewCharaSpritePosition() {\r\n\t\t\tif (Completed) return; // Checking next word dimensions pointless if menu finished\r\n\r\n\t\t\tString newWord = new string(contextString[contextStringWordIndex]).Split('\\n')[0]; // Get new word\r\n\r\n\t\t\tfloat wordWidth = GV.MonoGameImplement.fonts[currentContextMenuFont].MeasureString(newWord).X;\r\n\r\n\t\t\tif (position.X + wordWidth > textContainerBoundary.Right) MoveToNextLine(); else position.X += 11;\r\n\t\t}\r\n\r\n\t\tprivate static void Create(ContextType contextType, String something) {\r\n\t\t\tif (Active) throw new HollowAetherException($\"Cannot create context menu when it already exists\");\r\n\t\t\tWhenDone = () => { }; // Clear all event handlers stored within completion event. No method, just reset.\r\n\r\n\t\t\tActive = true; // Set to active to prevent update calls to non context menu IMonoGameObject instances\r\n\r\n\t\t\tcontextString = (from X in something.Split(' ') select X.ToCharArray()).ToArray();\r\n\r\n\t\t\tcharactersToDraw = new List<ContextSpriteCharacter>((int)contextString.LongLength);\r\n\r\n\t\t\tRectangle sR = spriteRect = GetDrawRect(); // Rectangle holding context menu sprite on the game display\r\n\r\n\t\t\tdefaultCharaAttributes = new ContextSpriteCharacter.CharaAttributes(); // reset chara attributes\r\n\t\t\tcontextStringWordIndex = 0; contextStringCharIndex = 0; // Reset index counters to initial value\r\n\t\t\tcurrentContextMenuFont = DEFAULT_FONT; // Assign initial font value to be used with characters\r\n\t\t\tdefaultPosition = position = new Vector2(sR.X + xOffset, sR.Center.Y - (int)(0.5 * FontSize));\r\n\t\t\tcharAppensionTimer = outputTimeout = 0; // Remove any leftover timing variables from previous run\r\n\t\t\tShowOKCancelWindow = false; // Prevent window from automatically being drawn to the screen or updated\r\n\t\t\ttype = contextType; // Store type of context menu to be displayed to user/player locally\r\n\t\t\ttextContainerBoundary = new Rectangle(sR.X + xOffset, sR.Y + yOffset, sR.Width - (2 * xOffset), sR.Height - (2 * yOffset));\r\n\t\t}\r\n\r\n\t\tpublic static void CreateText(String something) { ContextMenu.Create(ContextType.None, something); }\r\n\r\n\t\tpublic static void CreateOKCancel(String something, params Action<bool>[] eventHandlers) {\r\n\t\t\tContextMenu.Create(ContextType.OK_Cancel, something); // Call shared functionality\r\n\r\n\t\t\tOkContextMenuComplete = (ok) => { WhenDone(); Active = false; }; // Erase existing handlers\r\n\r\n\t\t\tforeach (Action<bool> handler in eventHandlers) OkContextMenuComplete += handler;\r\n\r\n\t\t\tMenuSprite = new OKMenuSprite(); // Redefined in case scale changed\r\n\t\t}\r\n\r\n\t\t/// <summary>Updates output procedure on context menu</summary>\r\n\t\tpublic static void Update() {\r\n\t\t\tif (!Active) throw new HollowAetherException($\"Cannot update context menu when it doesn't exists\");\r\n\r\n\t\t\tforeach (ContextSpriteCharacter chara in charactersToDraw)\r\n\t\t\t\tchara.Update(); // Update chara sprites. Used to implement push features\r\n\r\n\t\t\tif (invokeRemoveTopLine) RemoveTopLine(); // Invoke event handler, while by passing collection modification error\r\n\r\n\t\t\tif (invokeClearScreen) ClearScreen(); // Clears all items in context menu & re-alligns to default chara position\r\n\r\n\t\t\tif (WaitingForInput) { // If command waiting for input has been activated, wait\r\n\t\t\t\tif (!GV.PeripheralIO.currentControlState.Jump) // Jump button is used to continue moving context menu\r\n\t\t\t\t\treturn; // No input detected from either input device, thus return & containue to wait\r\n\r\n\t\t\t\tWaitingForInput = false; // Get rid of input waiting command and continue outputting remaining context\r\n\t\t\t}\r\n\r\n\t\t\tint elapsedTime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\r\n\t\t\tif (type == ContextType.OK_Cancel && ShowOKCancelWindow && !WaitForKeyReleaseBeforeAcceptingSkipInput) {\r\n\t\t\t\tMenuSprite.Update(true); // If menu exists, draw it\r\n\t\t\t}\r\n\r\n\t\t\tif (outputTimeout > 0) outputTimeout -= elapsedTime; else {\r\n\t\t\t\tif (Completed) {\r\n\t\t\t\t\tif (type != ContextType.OK_Cancel) { WhenDone(); Active = false; }\r\n\t\t\t\t} else if (charAppensionTimer >= CHAR_APPENSION_RATE) AppendNewChar(); else {\r\n\t\t\t\t\tcharAppensionTimer += elapsedTime;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbool jumpKeyPressed = GV.PeripheralIO.currentControlState.Jump;\r\n\t\t\t\tbool AButtonPressed = GV.PeripheralIO.currentKBState.IsKeyDown(Keys.Enter);\r\n\t\t\t\tbool enterKeyPressed = GV.PeripheralIO.currentGPState.Buttons.A == ButtonState.Pressed;\r\n\r\n\t\t\t\tif (jumpKeyPressed || AButtonPressed || enterKeyPressed) {\r\n\t\t\t\t\tif (!WaitForKeyReleaseBeforeAcceptingSkipInput)\r\n\t\t\t\t\t\tOutputUntilEndOfCurrentSentence();\r\n\t\t\t\t} else if (WaitForKeyReleaseBeforeAcceptingSkipInput) {\r\n\t\t\t\t\tWaitForKeyReleaseBeforeAcceptingSkipInput = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void AppendNewChar() {\r\n\t\t\tif (Completed) return; // Nothing to do, just skip any increments or word addition\r\n\r\n\t\t\tchar newChar = contextString[contextStringWordIndex][contextStringCharIndex];\r\n\r\n\t\t\tbool moveToNextWord = WordCompleted; // Store before new sprite addition to prevent index error\r\n\r\n\t\t\tswitch (newChar) { // Allows handling of unconventional characters\r\n\t\t\t\tcase '\\n': MoveToNextLine(); contextStringCharIndex++; break;\r\n\t\t\t\tcase '#': InterpretCommand(ReadCommand()); break;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tvar sprite = new ContextSpriteCharacter(newChar, currentContextMenuFont, position, defaultCharaAttributes);\r\n\t\t\t\t\tAddNewCharacter(sprite); // Call event handler for creating and storing a new context menu sprite\r\n\t\t\t\t\tbreak; // By default, any non system characters are outputted to ContextMenu as sprite.\r\n\t\t\t}\r\n\r\n\t\t\tif (moveToNextWord) MoveToNextWord(); // If ready to move to next word then call event handler\r\n\r\n\t\t\tif (type == ContextType.OK_Cancel && Completed && !ShowOKCancelWindow) ShowOKCancelWindow = true;\r\n\t\t}\r\n\r\n\t\tprivate static void OutputUntilEndOfCurrentSentence() {\r\n\t\t\tdo { AppendNewChar(); } while (\r\n\t\t\t\t !Completed && !WaitingForInput // In order of most tasking bool check\r\n\t\t\t\t&& contextString[contextStringWordIndex][contextStringCharIndex] != '\\n'\r\n\t\t\t\t&& !(type == ContextType.OK_Cancel && ShowOKCancelWindow)\r\n\t\t\t);\r\n\r\n\t\t\toutputTimeout = 500; // Skipped to end, take breif pause to let user removee keypress\r\n\t\t\tWaitForKeyReleaseBeforeAcceptingSkipInput = true;\r\n\t\t}\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\tif (!Active) throw new HollowAetherException($\"Cannot draw context menu when it doesn't exists\");\r\n\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false); // Draw without camera\r\n\r\n\t\t\tDrawMenu(); // Draw base sprite for menu to hold text\r\n\r\n\t\t\tif (type == ContextType.OK_Cancel && ShowOKCancelWindow)\r\n\t\t\t\tMenuSprite.Draw(); // Draw sprite if valid\r\n\r\n\t\t\tif (WaitingForInput) DrawCursor(); // Indicator drawn\r\n\t\t\tDrawText(); // Actually tries to draw text to screen\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tprivate static void DrawMenu() {\r\n\t\t\tRectangle baseFrame = new Rectangle(6, 6, ContextMenuWidth, ContextMenuHeight); // Frame\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(BaseTexture, spriteRect, baseFrame, Color.White);\r\n\t\t}\r\n\r\n\t\tprivate static void DrawCursor() {\r\n\t\t\tif (cursorTimer > cursorDrawInterval) { cursorBeingDrawn = !cursorBeingDrawn; cursorTimer = 0; } else {\r\n\t\t\t\tcursorTimer += GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t}\r\n\r\n\t\t\tif (cursorBeingDrawn) // If cursor is supposed to be drawn to screen draw it, else wait till then\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(GV.MonoGameImplement.textures[\"white\"], GetCursorRect(), Color.White);\r\n\t\t}\r\n\r\n\t\tprivate static Rectangle GetCursorRect() {\r\n\t\t\treturn new Rectangle((int)position.X, (int)position.Y, CursorRectWidth, CursorRectHeight);\r\n\t\t}\r\n\r\n\t\tprivate static void DrawText() {\r\n\t\t\tforeach (ContextSpriteCharacter chara in charactersToDraw) chara.Draw();\r\n\t\t}\r\n\r\n\t\tprivate static Rectangle GetDrawRect() {\r\n\t\t\tfloat xOffset = 0.10f * ContextMenuWidth;\r\n\t\t\tfloat yOffset = 0.35f * ContextMenuHeight;\r\n\r\n\t\t\tContextScale = Math.Min(\r\n\t\t\t\tGV.Variables.windowWidth / (ContextMenuWidth + (2 * xOffset)),\r\n\t\t\t\tGV.Variables.windowHeight / (ContextMenuHeight + yOffset)\r\n\t\t\t);\r\n\r\n\t\t\tint scaledWidth = (int)(ContextMenuWidth * ContextScale), scaledHeight = (int)(ContextMenuHeight * ContextScale);\r\n\t\t\tint scaledOffsetHeight = (int)(ContextScale * (ContextMenuHeight + yOffset)); // Accounts for offset as well\r\n\r\n\t\t\treturn new Rectangle(\r\n\t\t\t\t(GV.Variables.windowWidth - scaledWidth) / 2,\r\n\t\t\t\tGV.Variables.windowHeight - scaledOffsetHeight,\r\n\t\t\t\tscaledWidth, scaledHeight // \r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\t/// <summary>Reads command string from context string, with format #NAME:ARG;</summary>\r\n\t\tprivate static String ReadCommand() {\r\n\t\t\tStringBuilder builder = new StringBuilder();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tchar commandCurrent; // Store current char\r\n\r\n\t\t\t\tdo {\r\n\t\t\t\t\tcommandCurrent = contextString[contextStringWordIndex][++contextStringCharIndex];\r\n\r\n\t\t\t\t\tif (commandCurrent == '#') // If system attempts to create a new command regardless of previous one\r\n\t\t\t\t\t\tthrow new HollowAetherException($\"Cannot begin new command whilst previous unfinished\");\r\n\r\n\t\t\t\t\tif (WordCompleted) { contextStringWordIndex++; contextStringCharIndex = 0; }\r\n\r\n\t\t\t\t\tbuilder.Append(commandCurrent);\r\n\t\t\t\t} while (commandCurrent != ';');\r\n\t\t\t} catch (Exception e) { throw new HollowAetherException($\"Command begun, not finished\", e); }\r\n\r\n\t\t\tcontextStringCharIndex++; // Add final increment to skip command terminating character ';'.\r\n\r\n\t\t\treturn builder.ToString(); // Cast builder to string and return to caller method\r\n\t\t}\r\n\r\n\t\tprivate static void InterpretCommand(String command) {\r\n\t\t\tcommand = command.TrimEnd(';'); // Remove command syntax\r\n\r\n\t\t\tString[] split = command.Split(':'); // Split args from command string\r\n\r\n\t\t\t//if (command.Length == 0) throw new HollowAetherException($\"Command with no body given\"); else \r\n\t\t\tif (split.Length != 2) throw new HollowAetherException($\"Invalid command string format '{command}'\");\r\n\r\n\t\t\tswitch (split[0].Trim().ToLower()) { // Switch with command arg\r\n\t\t\t\tcase \"color\":\r\n\t\t\t\tcase \"colour\":\r\n\t\t\t\t\tvar property = typeof(Color).GetProperty(split[1]); // Get nullable potential color value\r\n\t\t\t\t\tif (property == null) throw new HollowAetherException($\"Could not determine color '{split[1]}'\");\r\n\t\t\t\t\tdefaultCharaAttributes.color = (Color)property.GetValue(null, null); // Cast to appropriate color\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"rotation\":\r\n\t\t\t\tcase \"rotate\":\r\n\t\t\t\t\tfloat? potentialValue = GV.Misc.StringToFloat(split[1]); // Try cast to floating point value\r\n\r\n\t\t\t\t\tif (potentialValue.HasValue) defaultCharaAttributes.rotation = potentialValue.Value;\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tthrow new HollowAetherException($\"Couldn't convert '{split[1]}' to a float\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"fx\":\r\n\t\t\t\tcase \"effect\":\r\n\t\t\t\t\tswitch (split[1].Trim().ToLower()) {\r\n\t\t\t\t\t\tcase \"none\":\r\n\t\t\t\t\t\t\tdefaultCharaAttributes.effect = SpriteEffects.None;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"fliphorizontally\":\r\n\t\t\t\t\t\tcase \"flipx\":\r\n\t\t\t\t\t\t\tdefaultCharaAttributes.effect = SpriteEffects.FlipHorizontally;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"flipvertically\":\r\n\t\t\t\t\t\tcase \"flipy\":\r\n\t\t\t\t\t\t\tdefaultCharaAttributes.effect = SpriteEffects.FlipVertically;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tthrow new HollowAetherException($\"Unknown effect command '{split[1]}'\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"system\":\r\n\t\t\t\tcase \"sys\":\r\n\t\t\t\t\tswitch (split[1].Trim().ToLower()) {\r\n\t\t\t\t\t\tcase \"clear\":\r\n\t\t\t\t\t\tcase \"cls\":\r\n\t\t\t\t\t\t\tinvokeClearScreen = true;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"pauseforinput\":\r\n\t\t\t\t\t\tcase \"waitforinput\":\r\n\t\t\t\t\t\tcase \"waittillkeypress\":\r\n\t\t\t\t\t\t\tWaitingForInput = true;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tthrow new HollowAetherException($\"Unknown system command '{split[1]}'\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"wait\":\r\n\t\t\t\tcase \"timeout\":\r\n\t\t\t\t\tint? span = GV.Misc.StringToInt(split[1]); // Try cast to milisecond integer value\r\n\r\n\t\t\t\t\tif (span.HasValue) outputTimeout = span.Value; else {\r\n\t\t\t\t\t\tthrow new HollowAetherException($\"Couldn't cast '{span}' to int\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"font\":\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tthrow new HollowAetherException($\"Unknow Command '{split[0]}'\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Whether context menu exists</summary>\r\n\t\tpublic static bool Active { get; private set; } = false;\r\n\r\n\t\t/// <summary>Whether all words to be outputted have been outputter</summary>\r\n\t\tprivate static bool Completed { get { return contextStringWordIndex >= contextString.Length; } }\r\n\r\n\t\t/// <summary>Whether the current word has been completed</summary>\r\n\t\tprivate static bool WordCompleted { get { return contextStringCharIndex + 1 >= contextString[contextStringWordIndex].Length; } }\r\n\r\n\t\tprivate static Texture2D BaseTexture { get { return GV.MonoGameImplement.textures[@\"cs\\textbox\"]; } }\r\n\r\n\t\tprivate static ContextType type;\r\n\r\n\t\tprivate static float ContextScale;\r\n\r\n\t\t/// <summary>Structure to hold characters, seperated by words</summary>\r\n\t\tprivate static char[][] contextString;\r\n\r\n\t\t/// <summary>Indexes for values in string</summary>\r\n\t\tprivate static int contextStringWordIndex, contextStringCharIndex;\r\n\r\n\t\t#region TimingVars\r\n\t\t/// <summary>Add character to menu once every 0.05 seconds</summary>\r\n\t\tprivate const int CHAR_APPENSION_RATE = 50;\r\n\r\n\t\t/// <summary>Counts intervals between chara appension</summary>\r\n\t\tprivate static int charAppensionTimer = 0;\r\n\r\n\t\t/// <summary>Whether to draw cursor or not</summary>\r\n\t\tprivate static bool cursorBeingDrawn = false;\r\n\r\n\t\t/// <summary>Time for which cursor is both not drawn & drawn</summary>\r\n\t\tprivate static int cursorDrawInterval = 150;\r\n\r\n\t\t/// <summary>Counts interval between alternations is bool cursorBeingDrawn</summary>\r\n\t\tprivate static int cursorTimer = 0;\r\n\r\n\t\t/// <summary>If greater than 0, is paused until 0</summary>\r\n\t\tprivate static int outputTimeout = 0;\r\n\r\n\t\t/// <summary>Whether waiting for input before continuing menu output</summary>\r\n\t\tprivate static bool WaitingForInput { get; set; } = false;\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Font at a given point in time</summary>\r\n\t\tprivate static String currentContextMenuFont;\r\n\r\n\t\t/// <summary>Default font used by context menu</summary>\r\n\t\tprivate static readonly String DEFAULT_FONT = \"base\";\r\n\r\n\t\tprivate static bool WaitForKeyReleaseBeforeAcceptingSkipInput { get; set; } = false;\r\n\r\n\t\tprivate static bool ShowOKCancelWindow;\r\n\r\n\t\tprivate static bool invokeRemoveTopLine;\r\n\r\n\t\tprivate static bool invokeClearScreen;\r\n\r\n\t\tprivate static List<ContextSpriteCharacter> charactersToDraw;\r\n\r\n\t\tprivate static ContextSpriteCharacter.CharaAttributes defaultCharaAttributes;\r\n\r\n\t\tprivate static Rectangle spriteRect, textContainerBoundary;\r\n\r\n\t\tprivate static Vector2 position, defaultPosition;\r\n\r\n\t\tprivate static OKMenuSprite MenuSprite;\r\n\r\n\t\tprivate const int FontSize = 48;\r\n\r\n\t\tprivate const int CursorRectWidth = (int)(0.66 * FontSize), CursorRectHeight = (int)(0.84 * FontSize);\r\n\r\n\t\tprivate const int xOffset = 35, yOffset = 25;\r\n\r\n\t\tprivate const int ContextMenuWidth = 260, ContextMenuHeight = 36;\r\n\r\n\t\tprivate const int StretchedContextMenuWidth = ContextMenuWidth, StretchedContextMenuHeight = 60;\r\n\t}\r\n}" }, { "alpha_fraction": 0.756440281867981, "alphanum_fraction": 0.7572209239006042, "avg_line_length": 25.84782600402832, "blob_id": "cfce4892170b8065a1fef0cd7da537afce00aed6", "content_id": "16772b03ea8f8ade12c765a1f45ed3d946c2d6dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 67, "num_lines": 46, "path": "/HollowAether/Lib/Global/GlobalVars/LevelEditor.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.IO;\r\nusing System.Drawing;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Content;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing SUM = HollowAether.StartUpMethods;\r\nusing HollowAether.Lib.GAssets;\r\nusing LE = HollowAether.Lib.Forms.LevelEditor;\r\n\r\nusing System;\r\nusing System.Windows.Forms;\r\nusing System.Threading;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class LevelEditor {\r\n\t\t\tpublic static string GetTextureKeyFromInstance(Image image) {\r\n\t\t\t\tforeach (var keyVal in textures) {\r\n\t\t\t\t\tif (keyVal.Value.Item1 == image)\r\n\t\t\t\t\t\treturn keyVal.Key;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthrow new HollowAetherException(\"TextyreKeyNotFound\");\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Dictionary<String, Tuple<Image, String>> textures;\r\n\t\t\tpublic static LE.TileMap tileMap;\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.735876739025116, "alphanum_fraction": 0.735876739025116, "avg_line_length": 28.288888931274414, "blob_id": "f3c34fcde5b5196431b7142f648d43243d8bdb86", "content_id": "40324ad05fda41cbbec14a1cc597db7487c0fa4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 95, "num_lines": 45, "path": "/HollowAether/Lib/Global/GlobalVars/FileIO.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class FileIO {\r\n\t\t\tpublic static SettingsManager settingsManager;\r\n\r\n\t\t\tpublic static Dictionary<String, String> assetPaths = new Dictionary<String, String>() {\r\n\t\t\t\t{ \"Root\", \"Assets\" }, { \"Save\", @\"Assets\\Saves\" },\r\n\t\t\t\t{ \"Animations\", @\"Assets\\Animations\" },\r\n\t\t\t\t{ \"Map\", @\"Assets\\Map\" },\r\n\t\t\t\t{ \"EditorRoot\", Forms.Editor.levelEditorBasePath },\r\n\t\t\t\t{ \"EditorTextures\", Forms.Editor.textureBasePath },\r\n\t\t\t\t{ \"EditorMaps\", Forms.Editor.mapZoneStorePath },\r\n\t\t\t};\r\n\r\n\t\t\tpublic static String DefaultMapPath = InputOutputManager.Join(assetPaths[\"Map\"], \"Map.map\");\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7247557044029236, "alphanum_fraction": 0.7296416759490967, "avg_line_length": 34.156864166259766, "blob_id": "73305441c2a278cc90af071845793625e01ac4f9", "content_id": "c9ea110c3c57beea0f6e5661afb52415eb920473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1844, "license_type": "no_license", "max_line_length": 125, "num_lines": 51, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/SetInitialZone.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\n\r\nnamespace HollowAether.Lib.Forms {\r\n\tpublic partial class SetInitialZone : Form {\r\n\t\tprivate SetInitialZone(Vector2 currentValue) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\txTextBox.Text = currentValue.X.ToString().PadLeft(3, '0');\r\n\t\t\tyTextBox.Text = currentValue.Y.ToString().PadLeft(3, '0');\r\n\t\t}\r\n\r\n\t\tprivate void SetInitialZone_Load(object sender, EventArgs e) { }\r\n\r\n\t\tpublic static Vector2? Get(Vector2? currentValue=null) {\r\n\t\t\tSetInitialZone zone = new SetInitialZone(currentValue.HasValue ? currentValue.Value : Vector2.Zero);\r\n\t\t\tDialogResult result = zone.ShowDialog(); // Display newly made instance of self as a dialog \r\n\t\t\t\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tint? xPos = GV.Misc.StringToInt(zone.xTextBox.Text), yPos = GV.Misc.StringToInt(zone.yTextBox.Text);\r\n\r\n\t\t\t\tif (xPos.HasValue && yPos.HasValue) return new Vector2(xPos.Value, yPos.Value); else {\r\n\t\t\t\t\tif (!xPos.HasValue) MessageBox.Show($\"Couldn't cast X-Input to integer\", \"Num Error\");\r\n\t\t\t\t\tif (!yPos.HasValue) MessageBox.Show($\"Couldn't cast Y-Input to integer\", \"Num Error\");\r\n\t\t\t\t}\r\n\t\t\t} else if (result != DialogResult.Cancel) Console.WriteLine($\"Warning: Unknown Dialog Result In SetInitialZone {result}\");\r\n\r\n\t\t\treturn null; // If couldn't determine user choice from input values, return null\r\n\t\t}\r\n\t}\r\n}" }, { "alpha_fraction": 0.7015604972839355, "alphanum_fraction": 0.7022106647491455, "avg_line_length": 31.07526969909668, "blob_id": "e4098b74a46ba94e03920621e2bf9617e2bcbb76", "content_id": "8d7b2896a35b44848f7fc46680cf7e73578b9934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3078, "license_type": "no_license", "max_line_length": 86, "num_lines": 93, "path": "/HollowAether/Lib/Misc/Colored.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Text {\r\n\tclass ColoredString {\r\n\t\tpublic ColoredString(String value) {\r\n\t\t\t_string = value;\r\n\t\t}\r\n\r\n\t\tpublic ColoredString(String value, params Object[] args) {\r\n\t\t\t_string = String.Format(value, args);\r\n\t\t}\r\n\r\n\t\tpublic static ColoredString Red(String value) {\r\n\t\t\treturn new ColoredString(value) { foreground = ConsoleColor.Red };\r\n\t\t}\r\n\r\n\t\tpublic static ColoredString Blue(String value) {\r\n\t\t\treturn new ColoredString(value) { foreground = ConsoleColor.Blue };\r\n\t\t}\r\n\r\n\t\tpublic static ColoredString Yellow(String value) {\r\n\t\t\treturn new ColoredString(value) { foreground = ConsoleColor.DarkYellow };\r\n\t\t}\r\n\r\n\t\tpublic static ColoredString Green(String value) {\r\n\t\t\treturn new ColoredString(value) { foreground = ConsoleColor.Green };\r\n\t\t}\r\n\r\n\t\tpublic static String Pack(String str) {\r\n\t\t\tStringBuilder builder = new StringBuilder(); // Container to hold string\r\n\r\n\t\t\tint count = (int)Math.Floor(str.Length / (double)Console.WindowWidth); // Occurence\r\n\r\n\t\t\tforeach (int index in Enumerable.Range(0, count)) {\r\n\t\t\t\tbuilder.Append(str.Substring(Console.WindowWidth * index, Console.WindowWidth));\r\n\t\t\t}\r\n\r\n\t\t\tString remainder = str.Substring(builder.Length, str.Length - builder.Length);\r\n\t\t\tbuilder.Append(remainder.PadLeft((remainder.Length + Console.WindowWidth) / 2));\r\n\t\t\r\n\t\t\treturn builder.ToString(); // Convert given builder to a string\r\n\t\t}\r\n\r\n\t\tpublic static String Pack(String str, params Object[] args) {\r\n\t\t\treturn Pack(String.Format(str, args));\r\n\t\t}\r\n\r\n\t\tpublic void Write() {\r\n\t\t\tSet(); Console.Write(_string); Reset();\r\n\t\t}\r\n\r\n\t\tpublic void WriteLine() {\r\n\t\t\tSet(); Console.WriteLine(_string); Reset();\r\n\t\t}\r\n\r\n\t\tpublic void ResetForeground(ConsoleColor? _color = null) {\r\n\t\t\tConsole.ForegroundColor = _color.HasValue ? _color.Value : defForeground;\r\n\t\t}\r\n\r\n\t\tpublic void ResetBackground(ConsoleColor? _color = null) {\r\n\t\t\tConsole.BackgroundColor = _color.HasValue ? _color.Value : defBackground;\r\n\t\t}\r\n\r\n\t\tpublic void Reset(ConsoleColor? fore = null, ConsoleColor? back = null) {\r\n\t\t\tif (!fore.HasValue) ResetForeground(); else ResetForeground(fore.Value);\r\n\t\t\tif (!back.HasValue) ResetForeground(); else ResetForeground(back.Value);\r\n\t\t}\r\n\r\n\t\tpublic void SetForeground(ConsoleColor? _color = null) {\r\n\t\t\tConsole.ForegroundColor = _color.HasValue ? _color.Value : foreground;\r\n\t\t}\r\n\r\n\t\tpublic void SetBackground(ConsoleColor? _color = null) {\r\n\t\t\tConsole.BackgroundColor = _color.HasValue ? _color.Value : background;\r\n\t\t}\r\n\r\n\t\tpublic void Set(ConsoleColor? fore = null, ConsoleColor? back = null) {\r\n\t\t\tif (!fore.HasValue) SetForeground(); else SetForeground(fore.Value);\r\n\t\t\tif (!back.HasValue) SetForeground(); else SetForeground(back.Value);\r\n\t\t}\r\n\r\n\t\tpublic String _string;\r\n\r\n\t\tpublic ConsoleColor foreground = defForeground, background = defBackground;\r\n\r\n\t\tpublic static ConsoleColor defForeground = Console.ForegroundColor;\r\n\t\tpublic static ConsoleColor defBackground = Console.BackgroundColor;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7028387188911438, "alphanum_fraction": 0.7104892134666443, "avg_line_length": 45.75961685180664, "blob_id": "ac63dd7d1136d968f037bbf38bffc3a389ed80cd", "content_id": "5f38d96fdbb1679cbb110b91acf0dd6491245c69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4969, "license_type": "no_license", "max_line_length": 147, "num_lines": 104, "path": "/HollowAether/Lib/GAssets/Camera/CameraBUP.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System.Linq;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\n/*namespace HollowAether.Lib {\r\n\t/// <summary> Camera class allowing game to instantiate and use a camera instance\r\n\t/// to view game instances. Customised Derivative Camera Class Inspired by source on\r\n\t/// : http://www.dylanwilson.net/implementing-a-2d-camera-in-monogame : </summary>\r\n\t/// <Note> Note any sprite batches begun with a Camera2D Matrix must have a default\r\n\t/// scale value of 0.1 or greater, anything lower will not be visible at all </Note>\r\n\tpublic class Camera2D {\r\n\t\tpublic enum CameraType {\r\n\t\t\tFixed, // Camera stays in a given position\r\n\t\t\tCentered, // Attatches to player and follows him\r\n\t\t\tForward, // Looks slightly forward in the players facing direction\r\n\t\t\tSmart // Specific following algorithm\r\n\t\t}\r\n\r\n\t\t/// <summary> Base constructor to create a 2Dimensional camera </summary>\r\n\t\t/// <param name=\"vp\">Viewport base to construct camera onto, and define camera base values</param>\r\n\t\t/// <param name=\"zoom\">Signifies maximum sprite scale zoom, value must be float above 0.1</param>\r\n\t\t/// <param name=\"rotation\">Value representing the degrees of rotation to set the camera to</param>\r\n\t\tpublic Camera2D(CameraType type = CameraType.Centered, float zoom = 1.0f, float rotation = 0.0f) {\r\n\t\t\tthis.rotationFactor = rotation;\r\n\t\t\tthis.scale = zoom;\r\n\t\t}\r\n\r\n\t\t/// <summary> Function to create and return a ViewMatrix Instance </summary>\r\n\t\t/// <returns> Single Matrix value, showing dimensions of camera </returns>\r\n\t\tpublic Matrix GetViewMatrix() {\r\n\t\t\tMatrix[] container = new Matrix[5]; int counter = 0;\r\n\t\t\t// Constructs a Matrix Container and incrementor, to construct a ViewMatrix\r\n\t\t\tforeach (Vector2 X in new Vector2[] { -this.position, -this.origin, this.origin })\r\n\t\t\t\t// Loops for three different potential vectors required to influence ViewMatrix\r\n\t\t\t\tcontainer[counter++] = Matrix.CreateTranslation(new Vector3(X, 0f));\r\n\t\t\t// Translates and stores new vectors to Matrix Container for aggregation\r\n\r\n\t\t\tcontainer[counter++] = Matrix.CreateRotationZ(this.rotationFactor); // adds rotation\r\n\t\t\tcontainer[counter++] = Matrix.CreateScale(this.scale, this.scale, 1.0f);\r\n\t\t\t// and scale Matrices to simplify implementation of ViewMatrix through aggregation\r\n\r\n\t\t\treturn container.Aggregate((Matrix a, Matrix b) => { return a * b; });\r\n\t\t\t// Agrregates and then returns ViewMatrix using local Lambda Function\r\n\t\t}\r\n\r\n\t\tpublic void Update() {\r\n\t\t\tint displacement = 5;\r\n\r\n\t\t\tif (GlobalVars.PeripheralIO.currentKBState.IsKeyDown(Keys.D)) {\r\n\t\t\t\tOffset(displacement);\r\n\t\t\t} if (GlobalVars.PeripheralIO.currentKBState.IsKeyDown(Keys.W)) {\r\n\t\t\t\tOffset(Y: -displacement);\r\n\t\t\t} if (GlobalVars.PeripheralIO.currentKBState.IsKeyDown(Keys.A)) {\r\n\t\t\t\tOffset(-displacement);\r\n\t\t\t} if (GlobalVars.PeripheralIO.currentKBState.IsKeyDown(Keys.S)) {\r\n\t\t\t\tOffset(Y: displacement);\r\n\t\t\t}\r\n\t\t} // Lerp to player position here\r\n\r\n\t\t/// <summary> Recommended way to alter camera position\r\n\t\t/// a positive X value moves camera to the right, a negative X value moves to the left\r\n\t\t/// a positive Y value moves camera upwards, a negative Y value camera downwards </summary>\r\n\t\t/// <param name=\"argVect\">Vector representing what value to offset camera by</param>\r\n\t\tpublic void Offset(Vector2 argVect) {\r\n\t\t\tthis.position += new Vector2(argVect.X, argVect.Y);\r\n\t\t\t//this.origin += new Vector2(-argVect.X, -argVect.Y);\r\n\t\t\t// <Note>X Axis flipped to help resemble math graphs</Note>\r\n\t\t}\r\n\r\n\t\t/// <summary> Recommended way to alter camera position </summary>\r\n\t\t/// <param name=\"X\">a positive X value moves camera to the right, a negative X value moves to the left</param>\r\n\t\t/// <param name=\"Y\">a positive Y value moves camera upwards, a negative Y value camera downwards</param>\r\n\t\tpublic void Offset(int X = 0, int Y = 0) {\r\n\t\t\tthis.Offset(new Vector2(X, Y));\r\n\t\t\t// Calls Vector based Offset Overload\r\n\t\t}\r\n\r\n\t\t#region Attributes\r\n\t\tprivate Vector2 _position = new Vector2();\r\n\t\t#endregion\r\n\r\n\t\t#region PublicAttributes\r\n\t\tpublic float rotationFactor, scale;\r\n\t\t#endregion\r\n\r\n\t\t#region Properties\r\n\t\tpublic Matrix Transform { get { return GetViewMatrix(); } }\r\n\t\tpublic Vector2 origin { get { return screenCenter / scale; } }\r\n\t\tprivate float viewportWidth { get { return viewport.Width; } }\r\n\t\tprivate float viewportHeight { get { return viewport.Height; } }\r\n\t\tpublic Vector2 position { get { return _position; } set { _position = value; } }\r\n\t\tprivate Viewport viewport { get { return GlobalVars.hollowAether.GraphicsDevice.Viewport; } }\r\n\t\tpublic Vector2 screenCenter { get { return new Vector2((position.X + viewport.Width) / 2, (position.Y + viewport.Height) / 2); } }\r\n\t\tpublic Vector2 target { get { return GlobalVars.MonoGameImplement.player.boundary.Container.Center.ToVector2(); } } // attatch to player position\r\n\t\t#endregion\r\n\t}\r\n}\r\n*/\r\n" }, { "alpha_fraction": 0.7438375949859619, "alphanum_fraction": 0.7443209290504456, "avg_line_length": 34.29824447631836, "blob_id": "16c768e28cc4e0bfa693aa87ef1a7ad6a275fa10", "content_id": "5c3143142ef2715597113ef373a0e4d4edb4db07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 137, "num_lines": 57, "path": "/HollowAether/Lib/Global/GlobalVars/Main/GlobalVars.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Content;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tstatic GlobalVars() {\r\n\t\t\tforeach (String path in (from X in FileIO.assetPaths.Keys select Path.Combine(Directory.GetCurrentDirectory(), FileIO.assetPaths[X])))\r\n\t\t\t\tif (!Directory.Exists(path)) Directory.CreateDirectory(path); // Make if not found: pretty much for saves\r\n\r\n\t\t\tMapZone.globalAssets = new AssetContainer {\r\n\t\t\t\t{ \"defaultAnimationRunning\", new BooleanAsset(\"defaultAnimationRunning\", true) },\r\n\t\t\t\t{ \"background\", new StringAsset(\"background\", \"default_value\") },\r\n\t\t\t\t{ \"playerStartPosition\", new PositionAsset(\"playerStartPosition\", Vector2.Zero) }\r\n\t\t\t};\r\n\r\n\t\t\tLoadAnimations(FileIO.assetPaths[\"Animations\"]); // Load animations\r\n\t\t}\r\n\r\n\t\tpublic static void LoadAnimations(String path) {\r\n\t\t\tforeach (String animFile in StartUpMethods.SystemParserScriptInterpreter(path)) {\r\n\t\t\t\tDictionary<String, AnimationSequence> fileSequences = Animation.FromFile(animFile);\r\n\r\n\t\t\t\tforeach (String key in fileSequences.Keys) {\r\n\t\t\t\t\tString nKey = $\"{InputOutputManager.GetFileTitleFromPath(animFile)}\\\\{key}\".ToLower();\r\n\t\t\t\t\tMonoGameImplement.importedAnimations[nKey] = fileSequences[key]; // add animation to importable\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static HollowAetherGame hollowAether = new HollowAetherGame();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7495429515838623, "alphanum_fraction": 0.7605118751525879, "avg_line_length": 29.257143020629883, "blob_id": "28179e756f677d4902a4d6367fb703771b4d0520", "content_id": "c621f02558536930fd422c0ab99a95cd850fcf5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1096, "license_type": "no_license", "max_line_length": 127, "num_lines": 35, "path": "/HollowAether/Lib/GAssets/Blocks/Block.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Block : CollideableSprite, IBlock, IInitializableEntity {\r\n\t\tpublic Block() : base() { }\r\n\r\n\t\tpublic Block(Vector2 position, int width, int height, bool aRunning=true) \r\n\t\t\t: base(position, width, height, aRunning) { }\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tif (!Animation.SequenceExists(GlobalVars.MonoGameImplement.defaultAnimationSequenceKey))\r\n\t\t\t\tAnimation[GlobalVars.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(32, 32, 0, 0, 1, 32, 32);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 22.11111068725586, "blob_id": "ab430aac33e9e3841290c768f9b88a9afeac8613", "content_id": "de82848886b6033cbb52059286f3262834745b00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 219, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/HollowAether/Lib/GAssets/Items/Gates/LockedGate.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items.Gates {\r\n\t// public class LockedGate : Gate { }\r\n}\r\n" }, { "alpha_fraction": 0.673190712928772, "alphanum_fraction": 0.6802458167076111, "avg_line_length": 27.293333053588867, "blob_id": "573c5ba00093646beda63fed0e069295fc003865", "content_id": "1708be41ca6595bc59e8e9cbb9d459b27d868fa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4396, "license_type": "no_license", "max_line_length": 104, "num_lines": 150, "path": "/HollowAether/Lib/Global/MonoGameObjectStore.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Collections;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary></summary>\r\n\t/// <remarks>Uses two lists instead of dictionary, because faster at expense of memory</remarks>\r\n\tpublic class MonoGameObjectStore : IEnumerable<IMonoGameObject>, IEnumerable {\r\n\t\tpublic MonoGameObjectStore() {\r\n\t\t\tobjects = new Dictionary<string, IMonoGameObject>();\r\n\t\t\tunnamedObjects = new List<IMonoGameObject>();\r\n\t\t}\r\n\r\n\t\tpublic int Count() {\r\n\t\t\treturn unnamedObjects.Count + objects.Count;\r\n\t\t}\r\n\r\n\t\tpublic MonoGameObjectStore(int capacity) {\r\n\t\t\tobjects = new Dictionary<string, IMonoGameObject>(capacity / 2);\r\n\t\t\tunnamedObjects = new List<IMonoGameObject>(capacity / 2);\r\n\t\t}\r\n\r\n\t\tpublic void Add(String key, IMonoGameObject _object) {\r\n\t\t\tif (Exists(key)) throw new HollowAetherException($\"Cannot Add IMGO '{key}', When It Already Exists\");\r\n\r\n\t\t\t_object.SpriteID = key; // in case isn't stored already\r\n\t\t\tobjects.Add(key, _object); // Store to local object store\r\n\t\t}\r\n\r\n\t\tpublic void AddNameless(IMonoGameObject _object) {\r\n\t\t\tunnamedObjects.Add(_object);\r\n\t\t}\r\n\r\n\t\tpublic void AddRangeNameless(params IMonoGameObject[] args) {\r\n\t\t\tunnamedObjects.AddRange(args);\r\n\t\t}\r\n\r\n\t\tpublic void Add(IMonoGameObject _object) {\r\n\t\t\tif (String.IsNullOrWhiteSpace(_object.SpriteID)) // If invalid sprite ID detected\r\n\t\t\t\tthrow new HollowAetherException($\"New Object Of Type {_object} Lacks a Sprite ID\");\r\n\r\n\t\t\tobjects.Add(_object.SpriteID, _object); // Store to local object store\r\n\t\t}\r\n\r\n\t\tpublic bool Exists(String spriteID) {\r\n\t\t\treturn objects.ContainsKey(spriteID);\r\n\t\t}\r\n\r\n\t\tpublic bool Exists(IMonoGameObject _object) {\r\n\t\t\treturn objects.ContainsValue(_object) || unnamedObjects.Contains(_object);\r\n\t\t}\r\n\r\n\t\tpublic IEnumerator<IMonoGameObject> Generate() {\r\n\t\t\treturn GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate(Type type) {\r\n\t\t\tforeach (IMonoGameObject X in this) {\r\n\t\t\t\tif (GV.Misc.DoesExtend(X.GetType(), type))\r\n\t\t\t\t\tyield return X; // Yield of child or same\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate(params Type[] types) {\r\n\t\t\tforeach (IMonoGameObject _object in this) {\r\n\t\t\t\tif (GV.Misc.TypesContainsGivenType(_object.GetType(), types))\r\n\t\t\t\t\tyield return _object; \r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region GenericLimitedImplimentation\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate<T>() {\r\n\t\t\treturn Generate(typeof(T));\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate<T1, T2>() {\r\n\t\t\treturn Generate(typeof(T1), typeof(T2));\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate<T1, T2, T3>() {\r\n\t\t\treturn Generate(typeof(T1), typeof(T2), typeof(T3));\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate<T1, T2, T3, T4>() {\r\n\t\t\treturn Generate(typeof(T1), typeof(T2), typeof(T3), typeof(T4));\r\n\t\t}\r\n\r\n\t\tpublic IEnumerable<IMonoGameObject> Generate<T1, T2, T3, T4, T5>() {\r\n\t\t\treturn Generate(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5));\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tIEnumerator IEnumerable.GetEnumerator() {\r\n\t\t\treturn GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IEnumerator<IMonoGameObject> GetEnumerator() {\r\n\t\t\tforeach (IMonoGameObject named in objects.Values) {\r\n\t\t\t\tyield return named;\r\n\t\t\t}\r\n\r\n\t\t\tforeach (IMonoGameObject unnamed in unnamedObjects) {\r\n\t\t\t\tyield return unnamed;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate int GetIndexFromSpriteID(String ID) {\r\n\t\t\tString[] keys = objects.Keys.ToArray(); // Get keys\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, keys.Length)) {\r\n\t\t\t\tif (keys[X] == ID) return X; // Return index\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException($\"Object with ID '{ID}' Not Found\");\r\n\t\t}\r\n\r\n\t\tpublic IMonoGameObject Get(String ID) {\r\n\t\t\treturn objects[ID];\r\n\t\t}\r\n\r\n\t\tpublic void Remove(String ID) {\r\n\t\t\tobjects.Remove(ID); // Delete key\r\n\t\t}\r\n\r\n\t\tpublic void ClearAll() {\r\n\t\t\tobjects.Clear();\r\n\t\t\tunnamedObjects.Clear();\r\n\t\t}\r\n\r\n\t\tpublic void Remove(IMonoGameObject _object) {\r\n\t\t\ttry { Remove(_object.SpriteID); } \r\n\t\t\tcatch { unnamedObjects.Remove(_object); }\r\n\t\t}\r\n\r\n\t\tpublic IMonoGameObject this[String spriteID] {\r\n\t\t\tget { return Get(spriteID); }\r\n\t\t}\r\n\r\n\t\tpublic int Length { get { return Count(); } }\r\n\r\n\t\tprivate Dictionary<String, IMonoGameObject> objects;\r\n\t\tprivate List<IMonoGameObject>\t\t\t\tunnamedObjects;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7024463415145874, "alphanum_fraction": 0.7199200987815857, "avg_line_length": 31.94915199279785, "blob_id": "09a7f95d94189c6b478773f18df3f6088ba48099", "content_id": "8aed04a493fd610090a452deb1431ec21290cc2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2005, "license_type": "no_license", "max_line_length": 117, "num_lines": 59, "path": "/HollowAether/Lib/GAssets/Items/HealthPickup.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic class HealthPickup : VolatileCollideableSprite, ITimeoutSupportedAutoInteractable {\r\n\t\tpublic HealthPickup(Vector2 position, bool singleHeart=false) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT, true) {\r\n\t\t\theartSingle = singleHeart; // Store to determine frame deets\r\n\t\t\tInitializeVolatility(VolatilityType.Timeout, 5000); \r\n\t\t\tInitialize(\"cs\\\\npcsym\");\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\r\n\t\t\tif (InteractionTimeout > 0)\r\n\t\t\t\tInteractionTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\telse if (InteractCondition()) Interact();\r\n\t\t}\r\n\r\n\t\tprivate bool heartSingle;\r\n\r\n\t\tpublic bool InteractCondition() {\r\n\t\t\treturn CanInteract && !Interacted && GV.MonoGameImplement.Player.Intersects(boundary);\r\n\t\t}\r\n\r\n\t\tpublic void Interact() {\r\n\t\t\tVolatilityManager.Delete(this); // Allocate for deletion\r\n\t\t\tGameWindow.GameRunning.InvokeGotHealthPickup(this);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tFrame f1 = new Frame(2 + (heartSingle ? 0 : 2), 5, 32, 32, runCount: 5);\r\n\t\t\tFrame f2 = new Frame(3 + (heartSingle ? 0 : 2), 5, 32, 32, runCount: 3);\r\n\t\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = new AnimationSequence(0, f1, f2);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tpublic bool Interacted { get; } = false;\r\n\r\n\t\tpublic bool CanInteract { get; } = true;\r\n\r\n\t\tpublic int InteractionTimeout { get; set; }\r\n\r\n\t\tpublic int Value { get { return heartSingle ? 1 : 3; } }\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7202942967414856, "alphanum_fraction": 0.7214047908782959, "avg_line_length": 38.700565338134766, "blob_id": "6ff8e1484082615392228e0f8ab4124ee52f4d64", "content_id": "9da1cb37d8148578fb42246d44bc8d976f9bb67c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7206, "license_type": "no_license", "max_line_length": 190, "num_lines": 177, "path": "/HollowAether/Lib/GAssets/CollideableSprite.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#define DRAW_BOUNDARY\r\n\r\n#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Sprite which any other collideable sprite can collide with</summary>\r\n\tpublic abstract partial class CollideableSprite : Sprite, ICollideable {\r\n\t\tpublic CollideableSprite() : base() { }\r\n\r\n\t\tpublic CollideableSprite(Vector2 position, int width, int height, bool aRunning = true) \r\n\t\t\t: base(position, width, height, aRunning) { }\r\n\r\n\t\t/// <summary>Also builds boundary</summary>\r\n\t\t/// <param name=\"textureKey\">Texture of given sprite</param>\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey);\r\n\t\t\tBuildBoundary();\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw();\r\n\r\n\t\t\t#if DRAW_BOUNDARY && DEBUG\r\n\t\t\tColor boundaryColor; // What to colour boundary\r\n\r\n\t\t\tif (this is Player)\t\t\t\tboundaryColor = Color.Yellow;\r\n\t\t\telse if (this is IDamaging)\t\tboundaryColor = Color.Red;\r\n\t\t\telse if (this is Enemy)\t\t\tboundaryColor = Color.Red;\r\n\t\t\telse if (this is IInteractable) boundaryColor = Color.Green;\r\n\t\t\telse\t\t\t\t\t\t\tboundaryColor = Color.White;\r\n\t\t\t\r\n\t\t\tGV.DrawMethods.DrawBoundary(boundary, boundaryColor);\r\n\t\t\t#endif\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for collision between two IMonoGameObjects</summary>\r\n\t\t/// <param name=\"A\">Fist MonoGameObject</param><param name=\"B\">Second MonoGameObject</param>\r\n\t\t/// <returns>Boolean indicating succesful collision between the two given monogame objects</returns>\r\n\t\tprotected static bool Intersects(IMonoGameObject A, IMonoGameObject B) {\r\n\t\t\tif (A is ICollideable && B is ICollideable) return Intersects((ICollideable)A, (ICollideable)B); else return false;\r\n\t\t}\r\n\r\n\t\tprotected static bool Intersects(ICollideable A, ICollideable B) {\r\n\t\t\treturn Intersects(A.Boundary, B.Boundary);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for collision between two boundaries</summary>\r\n\t\t/// <param name=\"A\">First boundary</param><param name=\"B\">Second boundary</param>\r\n\t\t/// <returns>Boolean indicating succesful collision between the two given boundaries</returns>\r\n\t\tpublic static bool Intersects(IBoundaryContainer A, IBoundaryContainer B) {\r\n\t\t\treturn A.Intersects(B);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for collision with another IMonoGameObject</summary>\r\n\t\t/// <param name=\"target\">Target monogame object to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating succesful collision with this</returns>\r\n\t\tpublic bool Intersects(IMonoGameObject target) {\r\n\t\t\treturn Intersects(this, target);\r\n\t\t}\r\n\r\n\t\t/// <summary>Check for collision between this and another boundary</summary>\r\n\t\t/// <param name=\"target\">Given target boundary to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating succesful collision with this</returns>\r\n\t\tpublic bool Intersects(IBoundaryContainer target) {\r\n\t\t\treturn Intersects(this.boundary, target);\r\n\t\t}\r\n\r\n\t\tprotected static IMonoGameObject[] CompoundIntersects<T>(ICollideable self, IMonoGameObject[] objects) {\r\n\t\t\treturn (from X in objects where X != self && X is ICollideable && X is T && Intersects(self, (ICollideable)X) select X).ToArray();\r\n\t\t}\r\n\r\n\t\tprotected static IMonoGameObject[] CompoundIntersects<T>(ICollideable self) {\r\n\t\t\treturn CompoundIntersects<T>(self, GV.MonoGameImplement.monogameObjects.ToArray());\r\n\t\t}\r\n\r\n\t\tprotected static IEnumerable<IMonoGameObject> YieldCompoundIntersects(ICollideable self, IMonoGameObject[] objects, params Type[] types) {\r\n\t\t\treturn (from X in objects where X != self && X is ICollideable && (types.Length == 0 || GV.Misc.TypesContainsGivenType(X.GetType(), types)) && Intersects(self, (ICollideable)X) select X);\r\n\t\t}\r\n\r\n\t\tprotected static IMonoGameObject[] CompoundIntersects(ICollideable self, IMonoGameObject[] objects, params Type[] types) {\r\n\t\t\treturn YieldCompoundIntersects(self, objects, types).ToArray();\r\n\t\t}\r\n\r\n\t\tprotected static IMonoGameObject[] CompoundIntersects(ICollideable self, params Type[] types) {\r\n\t\t\treturn YieldCompoundIntersects(self, GV.MonoGameImplement.monogameObjects.ToArray(), types).ToArray();\r\n\t\t}\r\n\r\n\t\tpublic IMonoGameObject[] CompoundIntersects(params Type[] types) {\r\n\t\t\treturn CompoundIntersects(this, types);\r\n\t\t}\r\n\r\n\t\tpublic IMonoGameObject[] CompoundIntersects<T>() {\r\n\t\t\treturn CompoundIntersects<T>(this);\r\n\t\t}\r\n\r\n\t\tpublic bool HasIntersectedTypes(params Type[] types) {\r\n\t\t\tif (types.Length == 0) throw new ArgumentException($\"At least one type must be passed\");\r\n\r\n\t\t\tforeach (ICollideable X in GV.MonoGameImplement.monogameObjects.Generate<ICollideable>()) {\r\n\t\t\t\tif (X != this && GV.Misc.TypesContainsGivenType(X.GetType(), types) && Intersects(this, X))\r\n\t\t\t\t\treturn true; // Has intersected a desired type\r\n\t\t\t}\r\n\r\n\t\t\treturn false; // Has not intersected desired type\r\n\t\t}\r\n\r\n\t\tpublic bool HasIntersectedType(Type type) {\r\n\t\t\tforeach (ICollideable X in GV.MonoGameImplement.monogameObjects.Generate<ICollideable>()) {\r\n\t\t\t\tif (X != this && GV.Misc.DoesExtend(X.GetType(), type) && Intersects(this, X))\r\n\t\t\t\t\treturn true; // Has intersected a desired type\r\n\t\t\t}\r\n\r\n\t\t\treturn false; // Has not intersected desired type\r\n\t\t}\r\n\r\n\t\tpublic bool HasIntersectedTypes(Vector2 offset, params Type[] types) {\r\n\t\t\treturn CheckOffsetMethodCaller(offset, () => HasIntersectedTypes(types));\r\n\t\t}\r\n\r\n\t\tpublic bool HasIntersectedType(Type type, Vector2 offset) {\r\n\t\t\treturn CheckOffsetMethodCaller(offset, () => HasIntersectedType(type));\r\n\t\t}\r\n\r\n\t\t/// <summary>Action method which accepts a type and returns a value of said type</summary>\r\n\t\t/// <typeparam name=\"V\">Value type for delegate handler/method to return</typeparam>\r\n\t\tprotected delegate V DelegatedAction<V>();\r\n\r\n\t\tprotected V CheckOffsetMethodCaller<V>(Vector2 offset, DelegatedAction<V> method) {\r\n\t\t\tOffsetSpritePosition(offset); // Push by desired amount\r\n\t\t\tV result = method(); // Store Method Result Pre-Emptively\r\n\t\t\tOffsetSpritePosition(-offset); // Push back to original\r\n\r\n\t\t\treturn result; // Return stored method result\r\n\t\t}\r\n\r\n\t\t/// <summary>Offsets both sprite and boundary positon</summary>\r\n\t\t/// <param name=\"XY\">Vector by which to offset positions</param>\r\n\t\tpublic override void OffsetSpritePosition(Vector2 XY) {\r\n\t\t\tbase.OffsetSpritePosition(XY);\r\n\r\n\t\t\tif (boundary != null) boundary.Offset(XY);\r\n\t\t}\r\n\r\n\t\tpublic override void SetPosition(Vector2 nPos) {\r\n\t\t\tbase.SetPosition(nPos);\r\n\t\t\tBuildBoundary();\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds sprite boundary container for collision detection</summary>\r\n\t\t/// <remarks>Default boundary will be the sprite rect I.E. width and height = position</remarks>\r\n\t\tprotected abstract void BuildBoundary();\r\n\t\t\r\n\t\t\r\n\t\t/// <summary>Sprite collision boundary</summary>\r\n\t\tprotected IBoundaryContainer boundary;\r\n\t\t\r\n\t\t/// <summary>Read only access for boundary outside of class</summary>\r\n\t\tpublic IBoundaryContainer Boundary { get { return boundary; } private set { boundary = value; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7720797657966614, "alphanum_fraction": 0.7720797657966614, "avg_line_length": 25, "blob_id": "8c3f9d3f0608bb520dbc04bfe34a8dc5e653b3eb", "content_id": "a9e89a6d2301e1f0184a23d8edb2896cfef255e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 353, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/HollowAether/Lib/Interfaces/IVolatile.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic interface IVolatile {\r\n\t\tvoid InitializeVolatility(VolatilityType vt, object arg);\r\n\t\tGAssets.Volatile.VolatilityManager VolatilityManager { get; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7242239117622375, "alphanum_fraction": 0.7262632846832275, "avg_line_length": 42.68860626220703, "blob_id": "c9da4cf81c179347b879010f02064a8da9e1bc13", "content_id": "1fa0579d44bf5198c1e0f9f0ed1c2ec12126955b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 17654, "license_type": "no_license", "max_line_length": 143, "num_lines": 395, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Classes/ZoneEditor_SelectionRectImplement.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing System.Drawing.Imaging;\r\nusing System.Drawing.Drawing2D;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.GAssets;\r\nusing System.Text.RegularExpressions;\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\nusing HollowAether.Lib.Exceptions;\r\nusing V2 = Microsoft.Xna.Framework.Vector2;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing SRBEA = HollowAether.Lib.Forms.LevelEditor.CanvasRegionBox.SelectionRectBuildersEventArgs;\r\nusing ST = HollowAether.Lib.Forms.LevelEditor.CanvasRegionBox.SelectType;\r\nusing CSRBT = HollowAether.Lib.Forms.LevelEditor.ZoneEditor.CustomSelectionRectBuilderTypes;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class ZoneEditor {\r\n\t\tprivate void CanvasRegionExecute_MouseBasedEventHandler(ST type, RectangleF finalRect, RectangleF[] highlited) {\r\n\t\t\tif (highlited == null) { // Single Rect Vars\r\n\t\t\t\tif (drawRadioButton.Checked) Draw_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t\t\tif (fillRadioButton.Checked) Fill_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t\t\tif (copyRadioButton.Checked) Copy_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t\t\tif (pasteRadioButton.Checked) Paste_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t\t\tif (deleteRadioButton.Checked) Delete_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t\t} else { // Multi Rect Vars\r\n\t\t\t\tif (drawRadioButton.Checked) Draw_MultipleRectPropertyImplementer(type, highlited);\r\n\t\t\t\tif (fillRadioButton.Checked) Fill_MultipleRectPropertyImplementer(type, highlited);\r\n\t\t\t\tif (copyRadioButton.Checked) Copy_MultipleRectPropertyImplementer(type, highlited);\r\n\t\t\t\tif (pasteRadioButton.Checked) Paste_MultipleRectPropertyImplementer(type, highlited);\r\n\t\t\t\tif (deleteRadioButton.Checked) Delete_MultipleRectPropertyImplementer(type, highlited);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region ClickComplete_PropertyImplementer\r\n\r\n\t\t#region Draw\r\n\t\t/// <summary>Adds a single tile to the canvas ata specified region</summary>\r\n\t\t/// <param name=\"type\"></param>\r\n\t\t/// <param name=\"finalRect\"></param>\r\n\t\tprivate void Draw_SingleRectPropertyImplementer(ST type, RectangleF finalRect) {\r\n\t\t\tRectangle rounded = new Rectangle((int)finalRect.X, (int)finalRect.Y, (int)finalRect.Width, (int)finalRect.Height);\r\n\r\n\t\t\tif (new Rectangle(Point.Empty, zone.Size).Contains(rounded)) \r\n\t\t\t\tAddEntity(GetDrawEntity(rounded), redraw: true);\r\n\t\t} // Complete\r\n\r\n\t\tprivate void Draw_MultipleRectPropertyImplementer(ST type, RectangleF[] rects) {\r\n\t\t\tif (rects.Count() > 15) { // Warn about adding too many\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t$\"You're about to add {rects.Length.ToString().PadLeft(3, '0')}. Are you sure you want to do this?\",\r\n\t\t\t\t\t\"Are you sure?\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation // Could be tasking\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result != DialogResult.Yes) return; // Result = DialogResult.No || DialogResult.Cancel\r\n\t\t\t}\r\n\r\n\t\t\tforeach (RectangleF highlitedRegion in rects) {\r\n\t\t\t\tRectangle rounded = new Rectangle((int)highlitedRegion.X, (int)highlitedRegion.Y, (int)highlitedRegion.Width, (int)highlitedRegion.Height);\r\n\r\n\t\t\t\tif (new Rectangle(Point.Empty, zone.Size).Contains(rounded))\r\n\t\t\t\t\tAddEntity(GetDrawEntity(rounded), redraw: false);\r\n\t\t\t}\r\n\r\n\t\t\tcanvas.Draw(); // Redraw canvas with new tile\r\n\t\t} // Complete\r\n\t\t#endregion\r\n\r\n\t\t#region Fill\r\n\t\tprivate void Fill_SingleRectPropertyImplementer(ST type, RectangleF finalRect) {\r\n\t\t\tint width = templateGameEntity[\"Width\"].IsAssigned ? (int)templateGameEntity[\"Width\"].GetActualValue() : (int)canvas.GridWidth;\r\n\t\t\tint height = templateGameEntity[\"Height\"].IsAssigned ? (int)templateGameEntity[\"Height\"].GetActualValue() : (int)canvas.GridHeight;\r\n\r\n\t\t\tint xSpan = (int)Math.Floor(finalRect.Width / width), ySpan = (int)Math.Floor(finalRect.Height / height);\r\n\r\n\t\t\tRectangleF[] rects = new RectangleF[xSpan * ySpan];\r\n\t\t\tint counter = 0; // Start adding to rects from 0\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, xSpan)) {\r\n\t\t\t\tforeach (int Y in Enumerable.Range(0, ySpan)) {\r\n\t\t\t\t\trects[counter++] = new RectangleF() {\r\n\t\t\t\t\t\tX = finalRect.X + (X * width),\r\n\t\t\t\t\t\tY = finalRect.Y + (Y * width),\r\n\t\t\t\t\t\tWidth = width, Height = height\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tDraw_MultipleRectPropertyImplementer(type, rects);\r\n\t\t} // Complete\r\n\r\n\t\tprivate void Fill_MultipleRectPropertyImplementer(ST type, RectangleF[] rects) {\r\n\t\t\tDraw_MultipleRectPropertyImplementer(type, rects);\r\n\t\t} // Complete\r\n\t\t#endregion\r\n\r\n\t\t#region Delete\r\n\t\tprivate void Delete_SingleRectPropertyImplementer(ST type, RectangleF finalRect) {\r\n\t\t\tif (type == ST.Custom && CustomSelectOption == CSRBT.TileHighliter && tileSelectionArgs != null) {\r\n\t\t\t\tif (tileSelectionArgs.Item4 == MouseButtons.Left && tileSelectionArgs.Item3 == tiles[tileSelectionArgs.Item1].Location) {\r\n\t\t\t\t\t// Basically, if tile highliting is active, user has left clicked tile, and tile hasn't been moved, try to delete\r\n\r\n\t\t\t\t\tDialogResult dialog = MessageBox.Show(\r\n\t\t\t\t\t\t$\"Are You Sure You Want To Delete The Tile '{tileSelectionArgs.Item1}'\", // Query with id\r\n\t\t\t\t\t\t\"Warning\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk // Do if Yes, ignore others\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tif (dialog == DialogResult.Yes) DeleteTile(tileSelectionArgs.Item1); // Delete selected tile\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tKeyValuePair<String, EntityTile>[] intersected = GetTiles(finalRect).ToArray();\r\n\r\n\t\t\t\tif (intersected.Length > 0) {\r\n\t\t\t\t\tDialogResult dialog = MessageBox.Show(\r\n\t\t\t\t\t\t$\"Are You Sure You Want To Delete {intersected.Length.ToString().PadLeft(3, '0')} Tiles\",\r\n\t\t\t\t\t\t\"Warning\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk // Do if Yes, ignore others\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tif (dialog == DialogResult.Yes) {\r\n\t\t\t\t\t\tforeach (KeyValuePair<String, EntityTile> tile in intersected) {\r\n\t\t\t\t\t\t\tDeleteTile(tile.Key, false); // Don't redraw the canvas\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tcanvas.Draw(); // Redraw canvas after deleting\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} // Complete\r\n\r\n\t\tprivate void Delete_MultipleRectPropertyImplementer(ST type, RectangleF[] rects) {\r\n\t\t\t// Not supported by level editor, leave method in case implemented later\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Copy\r\n\t\tprivate void Copy_SingleRectPropertyImplementer(ST type, RectangleF finalRect) {\r\n\t\t\tif (type == ST.Custom && CustomSelectOption == CSRBT.TileHighliter && tileSelectionArgs != null) {\r\n\t\t\t\tif (tileSelectionArgs.Item4 == MouseButtons.Right) return; // Right click menu\r\n\t\t\t\t\r\n\t\t\t\tGameEntity cloned = tiles[tileSelectionArgs.Item1].Entity.Clone() as GameEntity;\r\n\r\n\t\t\t\tif (cloned[\"Position\"].IsAssigned) cloned[\"Position\"].Delete();\r\n\t\t\t\tentityTypeComboBox.Text = cloned.EntityType; // Set copied entity type\r\n\t\t\t\tSetTemplateEntity(cloned); // Assign template entity to copied entity\r\n\r\n\t\t\t\tpasteRadioButton.Checked = clickRadioButton.Checked = true;\r\n\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void Copy_MultipleRectPropertyImplementer(ST type, RectangleF[] rects) {\r\n\t\t\t// Not supported by level editor, leave method in case implemented later\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region Paste\r\n\t\tprivate void Paste_SingleRectPropertyImplementer(ST type, RectangleF finalRect) {\r\n\t\t\tDraw_SingleRectPropertyImplementer(type, finalRect);\r\n\t\t}\r\n\r\n\t\tprivate void Paste_MultipleRectPropertyImplementer(ST type, RectangleF[] rects) {\r\n\t\t\t// Not supported by level editor, leave method in case implemented later\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\r\n\t\t#endregion\r\n\r\n\t\t#region TileHighliter_SelectionRectBuilder\r\n\r\n\t\t#region AssistanceMethods\r\n\t\t/// <summary>Creates Selection Tile Arguments For</summary>\r\n\t\t/// <param name=\"tileId\">Id of selected tile</param>\r\n\t\t/// <param name=\"tile\">Reference to selected tile</param>\r\n\t\t/// <param name=\"point\">Point where tile is clicked</param>\r\n\t\tprivate void CreateNewTileSelectionArgs(String tileId, EntityTile tile, PointF point, MouseButtons button) {\r\n\t\t\tSizeF displacement = new SizeF() { // displacementFromTileOrigin\r\n\t\t\t\tWidth = point.X - tile.Location.X, Height = point.Y - tile.Location.Y\r\n\t\t\t};\r\n\r\n\t\t\ttileSelectionArgs = new Tuple<string, SizeF, PointF, MouseButtons>(tileId, displacement, tile.Location, button);\r\n\t\t}\r\n\r\n\t\t/// <summary>Event called when user has tried to select more then one possible tile.\r\n\t\t/// Basically asks which tile they want to edit and then set's it to selected</summary>\r\n\t\tprivate void MultipleTileSelectionContextMenu_ClickEventHandler(object sender, MouseButtons button) {\r\n\t\t\tint index = multipleTileSelectionContextMenu.MenuItems.IndexOf(sender as MenuItem);\r\n\r\n\t\t\t#region UpdateClick&GridClickPoint\r\n\t\t\tPointF cursorPos = canvas.PointToClient(Cursor.Position); // Get current cursor position\r\n\t\t\tcursorPos = new PointF(cursorPos.X / canvas.ZoomX, cursorPos.Y / canvas.ZoomY); // zoomed\r\n\r\n\t\t\tcursorPos = (!tileGridCheckBox.Checked) ? cursorPos : new PointF() {\r\n\t\t\t\tX = GV.BasicMath.RoundDownToNearestMultiple(cursorPos.X, canvas.GridWidth, false),\r\n\t\t\t\tY = GV.BasicMath.RoundDownToNearestMultiple(cursorPos.Y, canvas.GridHeight, false)\r\n\t\t\t};\r\n\t\t\t#endregion\r\n\r\n\t\t\tKeyValuePair<String, EntityTile> selectedKVP = canvasClickIntersectedTiles[index];\r\n\t\t\tCreateNewTileSelectionArgs(selectedKVP.Key, selectedKVP.Value, cursorPos, button);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>When mouse-down on the canvas and the tile highligting algorithm has been selected</summary>\r\n\t\t/// <param name=\"type\">The current selection type used by the canvas</param>\r\n\t\t/// <param name=\"clickPoint\">The point on the canvas where the mouse was clicked</param>\r\n\t\t/// <param name=\"gridClickPoint\">The closest grid point on the canvas where the mouse was clicked</param>\r\n\t\tprivate void CanvasClickBegun_TileHighliter_MouseBasedEventHandler(ST type, PointF clickPoint, PointF gridClickPoint, MouseButtons button) {\r\n\t\t\tif (type == ST.Custom && CustomSelectOption == CSRBT.TileHighliter) {\r\n\t\t\t\tcanvasClickIntersectedTiles = GetTiles(clickPoint).ToArray(); // Get all intersected tiles\r\n\r\n\t\t\t\tif (canvasClickIntersectedTiles.Length > 1) { // If more then one potential collection\r\n\t\t\t\t\tmultipleTileSelectionContextMenu = new ContextMenu(); // Show tile options\r\n\r\n\t\t\t\t\tforeach (KeyValuePair<String, EntityTile> KVP in canvasClickIntersectedTiles) {\r\n\t\t\t\t\t\tMenuItem item = new MenuItem(KVP.Key); // New item for the context menu\r\n\t\t\t\t\t\titem.Click += (s, e) => MultipleTileSelectionContextMenu_ClickEventHandler(s, button);\r\n\t\t\t\t\t\tmultipleTileSelectionContextMenu.MenuItems.Add(item); // Add new item\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tPoint roundedClickPoint = new Point() { X = (int)clickPoint.X, Y = (int)clickPoint.Y };\r\n\t\t\t\t\tmultipleTileSelectionContextMenu.Show(canvas, roundedClickPoint); // Display menu\r\n\t\t\t\t} else if (canvasClickIntersectedTiles.Length == 1) {\r\n\t\t\t\t\tPointF point = (tileGridCheckBox.Checked) ? gridClickPoint : clickPoint;\r\n\t\t\t\t\tKeyValuePair<String, EntityTile> selectedKVP = canvasClickIntersectedTiles[0];\r\n\t\t\t\t\tCreateNewTileSelectionArgs(selectedKVP.Key, selectedKVP.Value, point, button);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Actually highlits any tiles within the canvas that the cursor is hovering</summary>\r\n\t\t/// <param name=\"type\">The type of selection rect allocated by the canvas-region</param>\r\n\t\tprivate void BuildSelectionRect_TileHighliter_RectBuilderEventHandler(CanvasRegionBox.SelectType type, SRBEA e) {\r\n\t\t\tif (type == ST.Custom && CustomSelectOption == CSRBT.TileHighliter) {\r\n\t\t\t\tif (tileSelectionArgs != null) { // When no tile is being dragged or has been selected\r\n\r\n\t\t\t\t\tif (tileSelectionArgs.Item4 == MouseButtons.Left) { // Tile drag implementation\r\n\t\t\t\t\t\tPointF current = (tileGridCheckBox.Checked) ? e.CurrentGridPoint : e.CurrentPoint;\r\n\t\t\t\t\t\ttiles[tileSelectionArgs.Item1].Location = current - tileSelectionArgs.Item2;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\te.currentRectangle = tiles[tileSelectionArgs.Item1].Region;\r\n\t\t\t\t} else { // Can be assumed that mouse is not down, thus just highlight any tiles\r\n\t\t\t\t\tIEnumerable<KeyValuePair<String, EntityTile>> tiles = GetTiles(e.CurrentPoint); // Tiles within range\r\n\r\n\t\t\t\t\tif (tiles.Count() == 0) { e.currentRectangle = RectangleF.Empty; } else { // Erase when empty\r\n\t\t\t\t\t\te.currentRectangle = (from X in tiles select X.Value.Region).Aggregate(RectangleF.Union);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Event called on click completeion for tile highligter algorithm</summary>\r\n\t\t/// <param name=\"type\">The type of selection being used by the zone canvas</param>\r\n\t\t/// <param name=\"finalRect\">The current selected rectangle region</param>\r\n\t\tprivate void CanvasClickComplete_TileHighligter_MouseBasedEventHandler(ST type, RectangleF finalRect) {\r\n\t\t\tbool execute = CustomSelectOption == CSRBT.TileHighliter && tileSelectionArgs != null;\r\n\r\n\t\t\tif (type == ST.Custom && execute) {\r\n\t\t\t\t#region NotMovedToOpenEditMenu_Implement\r\n\t\t\t\t/*if (tileSelectionArgs.Item3 == tiles[tileSelectionArgs.Item1].Location) {\r\n\t\t\t\t\tEditEntityView_Execute(tileSelectionArgs.Item1);\r\n\t\t\t\t}*/\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\tif (tileSelectionArgs.Item4 == MouseButtons.Right) {\r\n\t\t\t\t\tEditEntityView_Execute(tileSelectionArgs.Item1);\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttileSelectionArgs = null; // Delete variable\r\n\t\t\t\tcanvasClickIntersectedTiles = null; // delete\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region EntityWrapper_SelectionRectBuilder\r\n\t\t\r\n\t\tprivate void BuildSelectionRect_EntityWrapper_RectBuilderEventHandler(ST type, SRBEA e) {\r\n\t\t\tif (CustomSelectOption == CSRBT.EntityWrapper && (type == ST.Custom || type == ST.GridHighlight)) {\r\n\t\t\t\tEntityAttribute positionAttrib = templateGameEntity[\"Position\"];\r\n\t\t\t\tEntityAttribute widthAttrib = templateGameEntity[\"Width\"];\r\n\t\t\t\tEntityAttribute heightAttrib = templateGameEntity[\"Height\"];\r\n\r\n\t\t\t\tPointF location; // Value to hold which location to draw the selection rectangle\r\n\r\n\t\t\t\tif (!positionAttrib.IsAssigned) { location = (tileGridCheckBox.Checked) ? e.CurrentGridPoint : e.CurrentPoint; } else {\r\n\t\t\t\t\tvar position = (Microsoft.Xna.Framework.Vector2)templateGameEntity[\"Position\"].GetActualValue();\r\n\t\t\t\t\tlocation = new PointF(position.X, position.Y); // Cast vector2 position value to Microsoft PointF\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint width = (widthAttrib.IsAssigned) ? (int)widthAttrib.GetActualValue() : (int)canvas.GridWidth;\r\n\t\t\t\tint height = (heightAttrib.IsAssigned) ? (int)heightAttrib.GetActualValue() : (int)canvas.GridHeight;\r\n\r\n\t\t\t\te.currentRectangle = new RectangleF(location, new SizeF(width, height)); // Set current rectangle\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#endregion\r\n\r\n\t\t#region RadioButtonCheckChange\r\n\r\n\t\t#region CanvasSelectTypeRadioButtons\r\n\t\tprivate void SetPropertyRadioButtons(bool draw, bool fill, bool delete, bool copy, bool paste) {\r\n\t\t\tdrawRadioButton.Enabled = draw;\r\n\t\t\tfillRadioButton.Enabled = fill;\r\n\t\t\tdeleteRadioButton.Enabled = delete;\r\n\t\t\tcopyRadioButton.Enabled = copy;\r\n\t\t\tpasteRadioButton.Enabled = paste;\r\n\t\t\texecuteButton.Enabled = highlightRadioButton.Checked;\r\n\t\t}\r\n\r\n\t\tprivate void clickRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tSetPropertyRadioButtons(true, false, false, false, true);\r\n\r\n\t\t\tif (!drawRadioButton.Checked && !pasteRadioButton.Checked)\r\n\t\t\t\tdrawRadioButton.Select(); // first selectable property option\r\n\r\n\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.GridClick;\r\n\t\t\tcanvas.Deselect(); // Deselect any selected regions within canvas\r\n\r\n\t\t\tSetTemplateEntity(templateGameEntity); // Also sets select option\r\n\t\t}\r\n\r\n\t\tprivate void highlightRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tSetPropertyRadioButtons(true, true, false, false, false);\r\n\r\n\t\t\tif (!clickRadioButton.Checked && !fillRadioButton.Checked)\r\n\t\t\t\tdrawRadioButton.Select(); // First selectable property option\r\n\r\n\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.GridHighlight;\r\n\t\t\tcanvas.Deselect(); // Deselect any selected regions within canvas\r\n\t\t}\r\n\r\n\t\tprivate void rectangleRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tSetPropertyRadioButtons(true, true, true, false, false);\r\n\r\n\t\t\tif (copyRadioButton.Checked || pasteRadioButton.Checked)\r\n\t\t\t\tclickRadioButton.Select(); // First selectable property option\r\n\t\t\t\r\n\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.GridDrag;\r\n\t\t\tcanvas.Deselect(); // Deselect any selected regions within canvas\r\n\t\t}\r\n\r\n\t\tprivate void selectRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tSetPropertyRadioButtons(false, false, true, true, false);\r\n\r\n\t\t\tif (!deleteRadioButton.Checked && !copyRadioButton.Checked)\r\n\t\t\t\tdeleteRadioButton.Select(); // First selectable property option\r\n\r\n\t\t\tcanvas.SelectOption = CanvasRegionBox.SelectType.Custom;\r\n\t\t\tCustomSelectOption = CustomSelectionRectBuilderTypes.TileHighliter;\r\n\t\t\tcanvas.Deselect(); // Deselect any selected regions within canvas\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region PropertyRadioButtons\r\n\t\tprivate void drawRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Deselect();\r\n\t\t}\r\n\r\n\t\tprivate void fillRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Deselect();\r\n\t\t}\r\n\r\n\t\tprivate void deleteRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Deselect();\r\n\t\t}\r\n\r\n\t\tprivate void copyRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Deselect();\r\n\t\t}\r\n\r\n\t\tprivate void pasteRadioButton_CheckedChanged(object sender, EventArgs e) {\r\n\t\t\tcanvas.Deselect();\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\tprivate Tuple<String, SizeF, PointF, MouseButtons> tileSelectionArgs = null;\r\n\r\n\t\tprivate CustomSelectionRectBuilderTypes CustomSelectOption;\r\n\r\n\t\tprivate ContextMenu multipleTileSelectionContextMenu;\r\n\r\n\t\tprivate KeyValuePair<String, EntityTile>[] canvasClickIntersectedTiles;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6932241320610046, "alphanum_fraction": 0.7021593451499939, "avg_line_length": 35.30555725097656, "blob_id": "1101a88634833d48c9b4a345a1e6d840ce3ee0a8", "content_id": "ee9edc7b516f2d02bfe42e834ae2c8ddc30f3bb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4031, "license_type": "no_license", "max_line_length": 130, "num_lines": 108, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Bat.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Bat : Enemy {\r\n\t\tpublic Bat() : this(Vector2.Zero, 1, -1) { }\r\n\r\n\t\tpublic Bat(Vector2 position, int level, int direction) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT, level, true) {\r\n\t\t\t/*Initialize(@\"enemies\\bat\");*/ travellingDirection = direction;\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey); // Sets animation and texture for sprite\r\n\r\n\t\t\tKilled += (self) => { self.Animation.SetAnimationSequence(\"Rest\"); };\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed time as well\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Rest\"] = GV.MonoGameImplement.importedAnimations[@\"bat\\rest\"];\r\n\t\t\tAnimation[\"Flapping\"] = GV.MonoGameImplement.importedAnimations[@\"bat\\flapping\"];\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"Flapping\"); // Default animation is at rest\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() { boundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(SpriteRect)); }\r\n\r\n\t\tprotected override void DoEnemyStuff() {\r\n\t\t\tif (!active) {\r\n\t\t\t\tOffsetSpritePosition(LINEAR_VELOCITY * travellingDirection * elapsedTime);\r\n\r\n\t\t\t\tVector2 playerPos = GV.MonoGameImplement.Player.Position;\r\n\t\t\t\tfloat heightDifferential = Math.Abs(Position.Y - playerPos.Y);\r\n\r\n\t\t\t\tif (playerPos != Position && (playerPos - Position).Length() < MAX_CHECK_RADIUS) {\r\n\t\t\t\t\tbool passesMin = heightDifferential > MIN_RADIAL_HEIGHT_DIFFERENTIAL;\r\n\t\t\t\t\tbool passesMax = heightDifferential < MAX_RADIAL_HEIGHT_DIFFERENTIAL;\r\n\r\n\t\t\t\t\tif (passesMin && passesMax) { // Valid enemy position to spin around\r\n\t\t\t\t\t\tactive = true; // Player can now initialise attack motion\r\n\t\t\t\t\t\trotationPivot = Position; // Rotates from current position\r\n\t\t\t\t\t\tangle = 0; // Reset rotational angle to 0. I.E. No rotation\r\n\r\n\t\t\t\t\t\tVector2 playerCenter = GV.MonoGameImplement.Player.SpriteRect.Center.ToVector2();\r\n\r\n\t\t\t\t\t\tangularRadius = (playerCenter - SpriteRect.Center.ToVector2()).Length(); // Radius\r\n\t\t\t\t\t\tangularVelocity = LINEAR_VELOCITY / angularRadius; // Convert linear to angular\r\n\r\n\t\t\t\t\t\trotationalDirection = new Vector2(\r\n\t\t\t\t\t\t\tplayerPos.X > Position.X ? +1 : -1,\r\n\t\t\t\t\t\t\tplayerPos.Y > Position.Y ? +1 : -1\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tangle += angularVelocity * elapsedTime; // Increment angle of rotation of enemy\r\n\r\n\t\t\t\tVector2 sinCosRatio = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));\r\n\r\n\t\t\t\tOffsetSpritePosition(sinCosRatio * angularRadius * elapsedTime * rotationalDirection);\r\n\r\n\t\t\t\tif (angle > 2 * Math.PI) { // Has completed single revolution\r\n\t\t\t\t\tactive = false; // Stop enemy attack after complete revolution\r\n\t\t\t\t\tSetPosition(rotationPivot); // Set to position before rotation\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override bool ReadyToDelete(IMonoGameObject self) {\r\n\t\t\treturn base.ReadyToDelete(self) || !GV.MonoGameImplement.camera.ContainedInCamera(SpriteRect);\r\n\t\t}\r\n\r\n\t\tprivate float angle = 0, angularVelocity = 0, angularRadius = 0;\r\n\t\tprivate Vector2 rotationPivot, rotationalDirection;\r\n\r\n\t\t#region \r\n\t\tprotected override bool CanGenerateHealth { get; set; } = false;\r\n\r\n\t\tprotected override bool CausesContactDamage { get; set; } = true;\r\n\r\n\t\tprivate bool active = false; // Started to attack player\r\n\r\n\t\tprivate int travellingDirection;\r\n\r\n\t\tprivate const int LINEAR_VELOCITY = 95, MAX_CHECK_RADIUS = 80;\r\n\r\n\t\tprivate const int MAX_RADIAL_HEIGHT_DIFFERENTIAL = 250, MIN_RADIAL_HEIGHT_DIFFERENTIAL = 8;\r\n\r\n\t\tpublic const int FRAME_WIDTH = 16, FRAME_HEIGHT = 12;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = FRAME_WIDTH * 2, SPRITE_HEIGHT = FRAME_HEIGHT * 2; \r\n\t\t#endregion\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6709706783294678, "alphanum_fraction": 0.6765912175178528, "avg_line_length": 42.78231430053711, "blob_id": "e7c2f47234682cb53491afc4cc5de03fa9e0feba", "content_id": "9926773dd53645a74e66e0b76a83291858cc23d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6585, "license_type": "no_license", "max_line_length": 128, "num_lines": 147, "path": "/HollowAether/Lib/InputOutput/Parsers/ZoneCommandImplement/Implement.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\n\r\nusing System.Text.RegularExpressions;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.MapZone;\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tstatic partial class ZoneParser {\r\n\t\tprivate static void ImportAsset(String line) {\r\n\t\t\tif (!Regex.IsMatch(line, String.Format(@\"{0}\\w+{0} [\\w\\\\\\\\]+ as \\[\\w+\\]\", String.Format(@\"[\\{0}\\{1}]\", '\"', \"'\"))))\r\n\t\t\t\tthrow new MapSyntaxException(zone.FilePath, $\"Syntax of Import Asset statement is incorrect\", lineIndex);\r\n\r\n\t\t\tString assetType = SpeechMarkParser(line), assetID = GetAssetIDs(line)[0]; // stores values\r\n\t\t\tString assetValue = line.Replace($\"\\\"{assetType}\\\" \", \"\").Replace($\" as [{assetID}]\", \"\");\r\n\r\n\t\t\ttry {\r\n\t\t\t\tAsset asset = Converters.StringToAsset(assetType, assetID, assetValue);\r\n\t\t\t\tAddAsset(assetID, asset); // Add asset to stored local assets\r\n\r\n\t\t\t\tif (Zone.StoreAssetTrace) {\r\n\t\t\t\t\tzone.ZoneAssetTrace.AddImportAsset(assetID, assetType, assetValue);\r\n\t\t\t\t}\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tthrow new ZoneCouldNotFindAssetToImportException(zone.FilePath, typeof(String), assetID, lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void DefineAsset(String line) {\r\n\t\t\tString assetID = GetAssetIDs(line)[0]; // ID given to said asset, found in [square brackets]\r\n\t\t\tString assetType = SpeechMarkParser(line); // Type of asset, extracted from \"\" in line\r\n\t\t\tString value = line.Replace($\"[{assetID}] \", \"\").Replace($\"\\\"{assetType}\\\"\", \"\").Trim();\r\n\r\n\t\t\tAsset asset = Converters.StringToAsset(assetType, assetID, value);\r\n\t\t\tAddAsset(assetID, asset); // stores asset in local store\r\n\r\n\t\t\tif (Zone.StoreAssetTrace) { zone.ZoneAssetTrace.AddDefineAsset(assetID, assetType, value); }\r\n\t\t}\r\n\r\n\t\tprivate static void Set(String line) {\r\n\t\t\tString[] IDs = GetAssetIDs(line);\r\n\r\n\t\t\t#region ThrowEception\r\n\t\t\tif (IDs.Length == 0)\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"No Asset ID Given In Line '{line}'\", lineIndex);\r\n\r\n\t\t\tif (!AssetExists(IDs[0]))\r\n\t\t\t\tthrow new ZoneAssetNotFoundException(zone.FilePath, IDs[0], lineIndex);\r\n\t\t\t#endregion\r\n\r\n\t\t\t/*if (Regex.IsMatch(line, @\"[Bb]ind[Tt]o\")) { // BindTo set type\r\n\t\t\t\t#region ThrowEception\r\n\t\t\t\tif (IDs.Length != 2)\r\n\t\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Only One ID found in line {line}\", lineIndex);\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\tString[] _bindToFlag = GetAssetIDs(BracketParser(line));\r\n\r\n\t\t\t\t#region ThrowEception\r\n\t\t\t\tif (_bindToFlag.Length == 0)\r\n\t\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Could not find target flag to bind to in Line '{line}'\", lineIndex);\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\tString bindToFlag = _bindToFlag[0]; // Stores ID of flag to bind to\r\n\r\n\t\t\t\t#region ThrowEception\r\n\t\t\t\tif (!AssetExists(bindToFlag)) // Checks whether an asset with given ID is in memory\r\n\t\t\t\t\tthrow new ZoneAssetNotFoundException(zone.FilePath, bindToFlag, lineIndex);\r\n\t\t\t\tif (!FlagExists(bindToFlag)) // Already know flag exists, so checks whether asset is flag\r\n\t\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Bind Target Isn't of type Flag\", lineIndex);\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\t((Flag)GV.MapZone.globalAssets[bindToFlag].asset).FlagChanged += (flag, nVal) => {\r\n\t\t\t\t\tGV.MapZone.GetAsset(IDs[0], zone.assets).asset = nVal;\r\n\t\t\t\t}; // Append new event handler\r\n\t\t\t} else*/ if (true) { // General Value Set Type\r\n\t\t\t\tString value = line.Replace($\"[{IDs[0]}] \", \"\").Trim(); // get value from line\r\n\r\n\t\t\t\t#region ThrowException\r\n\t\t\t\tif (value.Length == 0)\r\n\t\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Cannot extract 'Set' value from line {line}\", lineIndex);\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\tType type = GlobalVars.MapZone.GetAsset(IDs[0], zone.assets).assetType;\r\n\r\n\t\t\t\tif (type == typeof(Flag)) // Flag set only changed flag value\r\n\t\t\t\t\t((Flag)GV.MapZone.globalAssets[IDs[0]].asset).Value = BooleanParser(value);\r\n\t\t\t\telse SetAsset(IDs[0], Converters.StringToAssetValue(type, value));\r\n\r\n\t\t\t\tif (Zone.StoreAssetTrace) { zone.ZoneAssetTrace.AddSetAsset(IDs[0], value); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void GameEntity(String line) {\r\n\t\t\tString type = SpeechMarkParser(line), ID = GetAssetIDs(line)[0];\r\n\r\n\t\t\tif (!Regex.IsMatch(line, \"\\\"[^\\n\\t\\\"]+\\\".as.\\\\[[^\\n\\t\\\\]]+\\\\]\")) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, \"Syntax of entity command is incorrect\", lineIndex);\r\n\t\t\t}\r\n\r\n\t\t\t//zone.monogameObjects.Add(ID, GV.EntityGenerators.StringToMonoGameObject(type, ID));\r\n\r\n\t\t\tzone.zoneEntities.Add(ID, GV.EntityGenerators.StringToGameEntity(type));\r\n\r\n\t\t\tforeach (Match m in Regex.Matches(line, @\"<[^\\n\\r\\t<]+\")) {\r\n\t\t\t\tString[] split = m.Value.Trim('<', ' ').Split('=');\r\n\r\n\t\t\t\tif (split.Length < 2)\r\n\t\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, \"Syntax Of Attribute Not Correct\", lineIndex);\r\n\r\n\t\t\t\tString attrName = split[0], value = (split.Length > 2) ? // If spaces in value string\r\n\t\t\t\t\tGV.CollectionManipulator.GetSubArray(split, 1, split.Length - 1).Aggregate((a, b) => $\"{a} {b}\") : split[1];\r\n\r\n\t\t\t\tGameEntityAttribute($\"[{ID}]({attrName}) {value}\"); // Interpret as attribute contained in string\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void GameEntityAttribute(String line) {\r\n\t\t\tString[] _IDs = GetAssetIDs(line); // Get All IDs in a given string\r\n\r\n\t\t\tif (_IDs.Length == 0) throw new ZoneSyntaxException(zone.FilePath, $\"No Asset ID Given In Line '{line}'\", lineIndex);\r\n\t\t\t\r\n\t\t\tbool storedInZone = zone.zoneEntities.ContainsKey(_IDs[0]), storedGlobally = GV.MapZone.GlobalEntities.ContainsKey(_IDs[0]);\r\n\r\n\t\t\tif (!(storedInZone || storedGlobally)) throw new ZoneAssetNotFoundException(zone.FilePath, _IDs[0], lineIndex);\r\n\r\n\t\t\tString attribute = BracketParser(line).Trim();\r\n\r\n\t\t\tif (attribute.Length == 0) throw new ZoneSyntaxException(zone.FilePath, $\"Attribute Not Given In Line '{line}'\", lineIndex);\r\n\t\t\t\r\n\t\t\tType attributeType = (storedInZone ? zone.zoneEntities : GV.MapZone.GlobalEntities)[_IDs[0]][attribute].Type;\r\n\t\t\tObject value; // Value for attribute in a given entity/stored monogame object instance\r\n\r\n\t\t\tif (_IDs.Length == 2) { value = GV.MapZone.GetAsset(_IDs[1], zone.assets); } else if (_IDs.Length == 1) {\r\n\t\t\t\tvalue = Converters.StringToAssetValue(attributeType, line.Replace($\"[{_IDs[0]}]\", \"\").Replace($\"({attribute})\", \"\").Trim());\r\n\t\t\t} else { throw new ZoneSyntaxException(zone.FilePath, $\"Too many Assets Found In Line '{line}'\", lineIndex); }\r\n\r\n\t\t\t(storedInZone ? zone.zoneEntities : GV.MapZone.GlobalEntities)[_IDs[0]].AssignAttribute(attribute, value);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6696005463600159, "alphanum_fraction": 0.6790792346000671, "avg_line_length": 24.375, "blob_id": "7fac5753c9d1935cc40d17025e3087350361bdc1", "content_id": "d222709df5afd12e0d7975a3031fd17fc5784a72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 92, "num_lines": 56, "path": "/HollowAether/Lib/GAssets/Boundary/Shapes/IBCircle.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial struct IBCircle : IBoundary {\r\n\t\tstatic IBCircle() {\r\n\t\t\tcircleFrame = GlobalVars.ImageManipulation.CreateCircleTexture(frameRadius, Color.White);\r\n\t\t}\r\n\r\n\t\tpublic IBCircle(Vector2 vect, float _radius) : this() {\r\n\t\t\torigin = vect; radius = _radius;\r\n\t\t}\r\n\r\n\t\tpublic IBCircle(float _X, float _Y, float _radius) {\r\n\t\t\torigin = new Vector2(_X, _Y); radius = _radius;\r\n\t\t}\r\n\r\n\t\tpublic void Offset(Vector2 vect) {\r\n\t\t\torigin += vect;\r\n\t\t}\r\n\r\n\t\tpublic void Offset(float X, float Y) {\r\n\t\t\tOffset(new Vector2(X, Y));\r\n\t\t}\r\n\r\n\t\tpublic void Draw(Color color) {\r\n\t\t\tGlobalVars.MonoGameImplement.SpriteBatch.Draw(circleFrame, Container, color);\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle GetContainerRect() {\r\n\t\t\tVector2 topLeft = new Vector2(X - radius, Y - radius);\r\n\t\t\tVector2 bottomRight = new Vector2(X + radius, Y + radius) - topLeft;\r\n\t\t\t\r\n\t\t\treturn new IBRectangle(topLeft, bottomRight);\r\n\t\t}\r\n\r\n\t\tpublic float X { get { return origin.X; } }\r\n\r\n\t\tpublic float Y { get { return origin.Y; } }\r\n\r\n\t\tpublic IBRectangle Container { get { return GetContainerRect(); } }\r\n\r\n\t\tprivate const int frameRadius = 128;\r\n\t\tprivate static Texture2D circleFrame;\r\n\r\n\t\tpublic static int counter = 0;\r\n\r\n\t\tpublic Vector2 origin;\r\n\t\tpublic float radius;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7337662577629089, "alphanum_fraction": 0.736201286315918, "avg_line_length": 31.29729652404785, "blob_id": "316631d8972ca595470cba60c8cf1a7c8bd01508", "content_id": "d5e69b641aeee406c49ded6dcbcfd4bc0f01e3f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 99, "num_lines": 37, "path": "/HollowAether/Lib/Interfaces/IBoundary.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.GAssets;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary> Interface for any class which can act as an indicator of collision </summary>\r\n\tpublic interface IBoundary {\r\n\t\t/// <summary>Whether one boundary collides with another</summary>\r\n\t\t/// <param name=\"boundary\">Another boundary to collide with</param>\r\n\t\tbool Intersects(IBoundary boundary);\r\n\r\n\t\t/// <summary>Push boundary a given distance in a known direction</summary>\r\n\t\t/// <param name=\"vect\">Amount by which to push sprite boundary</param>\r\n\t\tvoid Offset(Vector2 vect);\r\n\r\n\t\t/// <summary>Push boundary a given distance in a known direction</summary>\r\n\t\t/// <param name=\"X\">Horizontal displacement</param> <param name=\"Y\">Vertical displacement</param>\r\n\t\tvoid Offset(float X=0, float Y=0);\r\n\r\n\t\t/// <summary>Rectangle which can fully encompass boundary</summary>\r\n\t\tIBRectangle Container { get; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7048028111457825, "alphanum_fraction": 0.7097609639167786, "avg_line_length": 38.824771881103516, "blob_id": "1fb12d0126284aab0750ec2a92a62eba05e35d32", "content_id": "c4c373db3aeeb437a331c8eccbf0ed780125eec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 13515, "license_type": "no_license", "max_line_length": 121, "num_lines": 331, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/AnimationView/AnimationView.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Microsoft.Xna.Framework;\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class AnimationView : Form {\r\n\t\tclass StringComparer : IComparer<String> {\r\n\t\t\tpublic int Compare(String a, String b) {\r\n\t\t\t\treturn String.Compare(a, b, false);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static StringComparer comparer = new StringComparer();\r\n\t\t}\r\n\r\n\t\tpublic AnimationView() {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tanimationTreeView.BeforeExpand += animationTreeView_BeforeExpand;\r\n\t\t\tanimationTreeView.MouseDown\t += animationTreeView_MouseDown;\r\n\r\n\t\t\ttextureDisplayComboBox.MouseWheel += (s, e) => {\r\n\t\t\t\t((HandledMouseEventArgs)e).Handled = true;\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate void AnimationView_Load(object sender, EventArgs e) {\r\n\t\t\tanimationTreeView.Nodes.Add(\"Root\");\r\n\r\n\t\t\ttextureDisplayComboBox.Items.AddRange(GlobalVars.LevelEditor.textures.Keys.ToArray());\r\n\t\t\ttextureDisplayComboBox.SelectedIndex = 0; // Select first item referenced by combobox\r\n\r\n\t\t\tforeach (String key in GlobalVars.MonoGameImplement.importedAnimations.Keys) {\r\n\t\t\t\tString[] splitKey = key.Split('\\\\'); AddNodeToTreeView(splitKey[0], splitKey[1]);\r\n\t\t\t\tAnimationViewDataStore animationStore = new AnimationViewDataStore(key);\r\n\t\t\t\tanimationStore.deleteSequenceButton.Click += DeleteSequenceButton_ClickEventHandler;\r\n\t\t\t\tanimationStore.renameAnimButton.Click += RenameSequenceButton_ClickEventHandler;\r\n\r\n\t\t\t\tdataStore.Add(key, animationStore); \r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void animationTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {\r\n\t\t\tif (e.Node.IsSelected) { // Do Nothing When Not Selected\r\n\t\t\t\tAnimationGroupPanel.Controls.Clear(); // Clear All Existing Controls\r\n\t\t\t\tImage texture = GetImageInComboBox();\r\n\r\n\t\t\t\tif (e.Node.Text == \"Root\") {\r\n\t\t\t\t\tTreeNode root = animationTreeView.Nodes[0]; // Root\r\n\r\n\t\t\t\t\tforeach (TreeNode node in BreadthFirstTraverseRoot(root))\r\n\t\t\t\t\t\tAddGroundNodeToDataViewStore(node, texture);\r\n\t\t\t\t} else if (e.Node.Nodes.Count > 0) {\r\n\t\t\t\t\tforeach (TreeNode node in e.Node.Nodes) \r\n\t\t\t\t\t\tAddGroundNodeToDataViewStore(node, texture);\r\n\t\t\t\t} else AddGroundNodeToDataViewStore(e.Node, texture);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AddGroundNodeToDataViewStore(TreeNode node, Image currentImage = null) {\r\n\t\t\tcurrentImage = currentImage == null ? GetImageInComboBox() : currentImage;\r\n\r\n\t\t\tAnimationViewDataStore store = dataStore[$\"{node.Parent.Text}\\\\{node.Text}\"];\r\n\t\t\tstore.AssignTexture(currentImage); // Assign Current Texture To Data Store\r\n\t\t\tstore.Top = GetDataStoreVerticalPosition(); // Set Upper Offset For Store\r\n\r\n\t\t\tAnimationGroupPanel.Controls.Add(store); // Store Control To Animation Group\r\n\t\t}\r\n\r\n\t\tprivate void textureDisplayComboBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\tImage texture = GetImageInComboBox(); // Image Pointed To\r\n\t\t\t\r\n\t\t\tforeach (AnimationViewDataStore store in AnimationGroupPanel.Controls) {\r\n\t\t\t\tstore.AssignTexture(texture);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate IEnumerable<TreeNode> BreadthFirstTraverseRoot(TreeNode node) {\r\n\t\t\tif (node != null) {\r\n\t\t\t\tQueue<TreeNode> queue = new Queue<TreeNode>();\r\n\t\t\t\tqueue.Enqueue(node); // Add root to queue as 1st\r\n\t\t\t\tTreeNode currentNode = node; // Current Node\r\n\r\n\t\t\t\twhile (queue.Count != 0) {\r\n\t\t\t\t\tcurrentNode = queue.Dequeue(); // Get And Remove 1st Item\r\n\r\n\t\t\t\t\tif (currentNode.Nodes.Count == 0) yield return currentNode; else {\r\n\t\t\t\t\t// If Node Is At Tree Bedrock, I.E. It Has No Child Nodes, Return To Caller, Else\r\n\t\t\t\t\t\tforeach (TreeNode child in currentNode.Nodes) queue.Enqueue(child); // Store\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AddNodeToTreeView(String file, String name) {\r\n\t\t\tTreeNode rootNode = animationTreeView.Nodes[0]; // Get root\r\n\r\n\t\t\tif (!rootNode.IsExpanded) rootNode.Expand(); // Expand children\r\n\r\n\t\t\tint index = BinaryGetIndexOfDesiredNodeWithText(rootNode, file);\r\n\r\n\t\t\tif (index == -1) // Not in node view, Add to node view\r\n\t\t\t\tindex = AddToNodeView(rootNode, file); // Store file\r\n\r\n\t\t\tAddToNodeView(rootNode.Nodes[index], name);\r\n\t\t}\r\n\r\n\t\tprivate int BinaryGetIndexOfDesiredNodeWithText(TreeNode rootNode, string text) {\r\n\t\t\tif (rootNode.Nodes.Count == 0) return -1; else { // No Child\r\n\t\t\t\tint start = 0, end = rootNode.Nodes.Count - 1; // Doesn't Start At 0\r\n\r\n\t\t\t\twhile (start <= end) {\r\n\t\t\t\t\tint index = (int)Math.Ceiling((float)(start + end)/2); // Test Index\r\n\t\t\t\t\tint compare = String.Compare(text, rootNode.Nodes[index].Text, true);\r\n\t\t\r\n\t\t\t\t\tif (compare == 0) return index; else {\r\n\t\t\t\t\t\tif (compare < 0) end = index - 1;\r\n\t\t\t\t\t\telse\t\t\t start = index + 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn -1; // When desired value was not found\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate int AddToNodeView(TreeNode node, string value) {\r\n\t\t\tint nodeCount = node.Nodes.Count; // Store collection count, because accessed often\r\n\r\n\t\t\tif (node.Nodes.Count == 0 || String.Compare(value, node.Nodes[nodeCount - 1].Text) >= 0) {\r\n\t\t\t\t// Either No Items So Add Or New Item Greater Then Final Item\r\n\t\t\t\tnode.Nodes.Add(value); // Add node to end of root node\r\n\t\t\t\treturn nodeCount; // Corresponds to newly added index\r\n\t\t\t} else if (String.Compare(value, node.Nodes[0].Text) <= 0) {\r\n\t\t\t\tnode.Nodes.Insert(0, value); // Insert at the beginning if\r\n\t\t\t\treturn 0; // Inserted at the beginning of the node collection\r\n\t\t\t} else {\r\n\t\t\t\t// Otherwise, search for the place to insert.\r\n\t\t\t\tString[] titles = (from X in YieldChildNodes(node) select X.Text).ToArray();\r\n\t\t\t\tint index\t\t= Array.BinarySearch(titles, value, StringComparer.comparer);\r\n\r\n\t\t\t\tif (index < 0) { index = ~index; } // A -ve Num = Bitwise Complement Of Index > (item || count) \r\n\r\n\t\t\t\tnode.Nodes.Insert(index, value); // Add new node to desired index\r\n\t\t\t\treturn index; // Return calculated index for newly inserted node\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void DeleteSequenceButton_ClickEventHandler(object sender, EventArgs e) {\r\n\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\"Are You Sure You Want To Delete This Animation Sequence\", \"Really?\",\r\n\t\t\t\tMessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation\r\n\t\t\t);\r\n\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tAnimationViewDataStore store = (sender as Button).Parent as AnimationViewDataStore;\r\n\t\t\t\tint index = AnimationGroupPanel.Controls.IndexOf(store); // Index of deleting anim\r\n\r\n\t\t\t\tAnimationGroupPanel.Controls.RemoveAt(index); // Remove desired data store item\r\n\t\t\t\t\r\n\t\t\t\tfor (int X = index; X < AnimationGroupPanel.Controls.Count; X++) {\r\n\t\t\t\t\tAnimationGroupPanel.Controls[X].Top = GetDataStoreVerticalPosition(X);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstring key = GlobalVars.CollectionManipulator.DictionaryGetKeyFromValue(dataStore, store);\r\n\t\t\t\tdataStore.Remove(key); GlobalVars.MonoGameImplement.importedAnimations.Remove(key);\r\n\r\n\t\t\t\t#region RemoveFromTreeNodeView\r\n\t\t\t\tDeleteSequenceFromTreeNodeView(key);\r\n\r\n\t\t\t\t/*int nodeIndex = BinaryGetIndexOfDesiredNodeWithText(animationTreeView.Nodes[0], key.Split('\\\\').First());\r\n\r\n\t\t\t\tTreeNode node = animationTreeView.Nodes[0].Nodes[nodeIndex];\r\n\r\n\t\t\t\tif (node.Nodes.Count == 1) node.Remove(); else {\r\n\t\t\t\t\tnode.Nodes.RemoveAt(BinaryGetIndexOfDesiredNodeWithText(node, key.Split('\\\\').Last()));\r\n\t\t\t\t}*/\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void RenameSequenceButton_ClickEventHandler(object sender, EventArgs e) {\r\n\t\t\tAnimationViewDataStore store = (sender as Button).Parent as AnimationViewDataStore;\r\n\t\t\t\r\n\t\t\tTuple<DialogResult, string, string> result = RenameAnimationSequenceDialog.Run(store.SequenceKey);\r\n\r\n\t\t\tif (result.Item1 == DialogResult.OK) { // Dialog Succeeded\r\n\t\t\t\tif (dataStore.ContainsKey(result.Item3.ToLower())) {\r\n\t\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t\t$\"An Animation With The Name \\\"{result.Item3}\\\" Already Exists\",\r\n\t\t\t\t\t\t\"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error\r\n\t\t\t\t\t);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstring[] splitAnimName = result.Item3.Split('\\\\');\r\n\t\t\t\t\tstore.RenameSequenceKey(result.Item3); // Set key\r\n\r\n\t\t\t\t\tDeleteSequenceFromTreeNodeView(result.Item2);\r\n\t\t\t\t\tAddNodeToTreeView(splitAnimName[0], splitAnimName[1]);\r\n\r\n\t\t\t\t\t#region RenameSequenceReferences\r\n\t\t\t\t\tdataStore.Remove(result.Item2);\r\n\t\t\t\t\tdataStore.Add(result.Item3, store);\r\n\r\n\t\t\t\t\tvar sequence = GV.MonoGameImplement.importedAnimations[result.Item2];\r\n\t\t\t\t\tGV.MonoGameImplement.importedAnimations.Remove(result.Item2); // Del\r\n\t\t\t\t\tGV.MonoGameImplement.importedAnimations.Add(result.Item3, sequence);\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void newAnimationButton_Click(object sender, EventArgs e) {\r\n\t\t\tstring value; int counter = 0;\r\n\r\n\t\t\tdo {\r\n\t\t\t\tvalue = (counter++ == 0) ? $\"NewAnimation\\\\NewAnimation\" : $\"NewAnimation\\\\NewAnimation_{counter}\";\r\n\t\t\t\tvalue = value.ToLower(); // Blanket Make Return Value All Lower Case\r\n\t\t\t} while (GlobalVars.MonoGameImplement.importedAnimations.ContainsKey(value));\r\n\r\n\t\t\tAnimationSequence seq = new AnimationSequence(0, new Frame(0, 0, 32, 32));\r\n\t\t\tGlobalVars.MonoGameImplement.importedAnimations.Add(value, seq);\r\n\r\n\t\t\tString[] splitKey = value.Split('\\\\'); AddNodeToTreeView(splitKey[0], splitKey[1]);\r\n\t\t\tAnimationViewDataStore animationStore = new AnimationViewDataStore(value);\r\n\t\t\tanimationStore.deleteSequenceButton.Click += DeleteSequenceButton_ClickEventHandler;\r\n\t\t\tanimationStore.renameAnimButton.Click += RenameSequenceButton_ClickEventHandler;\r\n\r\n\t\t\tdataStore.Add(value, animationStore); // Store new animation store instance\r\n\r\n\t\t\tImage currentImage = GetImageInComboBox();\r\n\r\n\t\t\tanimationStore.AssignTexture(currentImage); // Assign Current Texture To Data Store\r\n\t\t\tanimationStore.Top = GetDataStoreVerticalPosition(); // Set Upper Offset For Store\r\n\r\n\t\t\tAnimationGroupPanel.Controls.Add(animationStore); // Store Control To Animation Group\r\n\t\t}\r\n\r\n\t\tprivate void DeleteSequenceFromTreeNodeView(string key) {\r\n\t\t\tint nodeIndex = BinaryGetIndexOfDesiredNodeWithText(animationTreeView.Nodes[0], key.Split('\\\\').First());\r\n\r\n\t\t\tTreeNode node = animationTreeView.Nodes[0].Nodes[nodeIndex];\r\n\r\n\t\t\tif (node.Nodes.Count == 1) node.Remove(); else {\r\n\t\t\t\tnode.Nodes.RemoveAt(BinaryGetIndexOfDesiredNodeWithText(node, key.Split('\\\\').Last()));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static IEnumerable<TreeNode> YieldChildNodes(TreeNode root) {\r\n\t\t\tforeach (TreeNode node in root.Nodes) { yield return node; }\r\n\t\t}\r\n\r\n\t\tprivate Image GetImageInComboBox() {\r\n\t\t\tint selectedTextureIndex = textureDisplayComboBox.SelectedIndex;\r\n\t\t\tstring path = textureDisplayComboBox.Items[selectedTextureIndex].ToString();\r\n\t\t\treturn GlobalVars.LevelEditor.textures[path].Item1; // Get Corresponding texture\r\n\t\t}\r\n\r\n\t\tprivate static int GetDataStoreVerticalPosition(int Count) {\r\n\t\t\treturn INITIAL_VERTICAL_OFFSET + (Count * (AnimationViewDataStore.CONTAINER_HEIGHT + SEQUENTIAL_VERTICAL_OFFSET));\r\n\t\t}\r\n\r\n\t\tprivate int GetDataStoreVerticalPosition() { return GetDataStoreVerticalPosition(AnimationGroupPanel.Controls.Count); }\r\n\r\n\t\t#region Expansion Prevention\r\n\t\tprivate void animationTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) {\r\n\t\t\te.Cancel = cancelNodeExpansion;\r\n\t\t\tcancelNodeExpansion = false;\r\n\t\t}\r\n\r\n\t\tprivate void animationTreeView_MouseDown(object sender, MouseEventArgs e) {\r\n\t\t\tint ellapsedMilleSecs = (int)DateTime.Now.Subtract(mouseDownTimePoint).TotalMilliseconds;\r\n\t\t\tcancelNodeExpansion\t = (ellapsedMilleSecs < SystemInformation.DoubleClickTime);\r\n\t\t\tmouseDownTimePoint\t = DateTime.Now; // Reset Time Since Last Time Down Check\r\n\t\t}\r\n\r\n\t\tprivate bool cancelNodeExpansion = false;\r\n\r\n\t\tprivate DateTime mouseDownTimePoint = DateTime.Now;\r\n\t\t#endregion\r\n\r\n\t\tpublic const int INITIAL_VERTICAL_OFFSET = 15, SEQUENTIAL_VERTICAL_OFFSET = 15;\r\n\r\n\t\tprivate void AnimationView_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\tString path = GlobalVars.FileIO.assetPaths[\"Animations\"];\r\n\r\n\t\t\tforeach (string subPath in IOMan.GetFiles(path)) {\r\n\t\t\t\ttry { System.IO.File.Delete(subPath); } \r\n\t\t\t\tcatch { Console.WriteLine($\"Couldn't Delete Anim {subPath}\"); }\r\n\t\t\t}\r\n\r\n\t\t\tString[] keys = GlobalVars.MonoGameImplement.importedAnimations.Keys.ToArray();\r\n\t\t\tArray.Sort(keys); // Sort all enteries within the dictionary appropriately\r\n\r\n\t\t\tstring lastKnownFileName = null; Animation animation = new Animation(Vector2.Zero);\r\n\r\n\t\t\tforeach (string key in keys) {\r\n\t\t\t\tstring currentFileName = key.Split('\\\\').First();\r\n\t\t\t\tstring sequenceKey = key.Split('\\\\').Last();\r\n\r\n\t\t\t\tif (currentFileName != lastKnownFileName) {\r\n\t\t\t\t\tif (!string.IsNullOrEmpty(lastKnownFileName)) {\r\n\t\t\t\t\t\tstring container = IOMan.Join(path, lastKnownFileName + \".ANI\"); // File Path For Animation\r\n\t\t\t\t\t\tIOMan.WriteEncryptedFile(container, animation.ToAnimationFile(), GV.Encryption.oneTimePad);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlastKnownFileName = currentFileName;\r\n\t\t\t\t\tanimation = new Animation(Vector2.Zero);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvar sequence = GlobalVars.MonoGameImplement.importedAnimations[key];\r\n\t\t\t\tanimation.AddAnimationSequence(sequenceKey, sequence); // Add To Anim\r\n\t\t\t}\r\n\r\n\t\t\tif (!string.IsNullOrEmpty(lastKnownFileName)) {\r\n\t\t\t\tstring container = IOMan.Join(path, lastKnownFileName + \".ANI\"); // File Path For Animation\r\n\t\t\t\tIOMan.WriteEncryptedFile(container, animation.ToAnimationFile(), GV.Encryption.oneTimePad);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate Dictionary<String, AnimationViewDataStore> dataStore = new Dictionary<String, AnimationViewDataStore>();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6875730752944946, "alphanum_fraction": 0.6899122595787048, "avg_line_length": 36.64406967163086, "blob_id": "bc96da014922fbc44ad0986a8b6cdee6c59e79bb", "content_id": "58f75df937d0fac6e04ccfca6089223881c60551", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6842, "license_type": "no_license", "max_line_length": 129, "num_lines": 177, "path": "/HollowAether/Lib/InputOutput/Parsers/ZoneParser.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing Microsoft.Xna.Framework;\r\nusing System.Text.RegularExpressions;\r\nusing HollowAether.Lib.MapZone;\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tstatic partial class ZoneParser {\r\n\t\tpublic static void Parse(Zone _zone) {\r\n\t\t\tzone = _zone; // Store reference to zone file\r\n\t\t\tfileContents = ReadZoneFile();\r\n\r\n\t\t\tfor (lineIndex = 0; lineIndex < fileContents.Length; lineIndex++) {\r\n\t\t\t\tString line = fileContents[lineIndex];\r\n\t\t\t\r\n\t\t\t\tif (String.IsNullOrWhiteSpace(line)) continue;\r\n\r\n\t\t\t\tString command = GetCommand(line), args = RemoveCommand(line, command);\r\n\r\n\t\t\t\tswitch (command.ToUpper()) {\r\n\t\t\t\t\tcase \"IMPORTASSET\":\r\n\t\t\t\t\t\tImportAsset(args);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"DEFINEASSET\":\r\n\t\t\t\t\t\tDefineAsset(args);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"SET\":\r\n\t\t\t\t\t\tSet(args);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"GAMEENTITY\":\r\n\t\t\t\t\t\tGameEntity(args);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"GAMEENTITYATTRIBUTE\":\r\n\t\t\t\t\t\tGameEntityAttribute(args);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault: throw new ZoneSyntaxException(zone.FilePath, $\"Command '{command}' Not Found\", lineIndex);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static String[] ReadZoneFile() {\r\n\t\t\tString zoneContents; // Pointer to desired map contents\r\n\r\n\t\t\ttry { zoneContents = IOMan.ReadEncryptedFile(zone.FilePath, GV.Encryption.oneTimePad).Replace(\"\\r\", \"\"); } \r\n\t\t\tcatch { throw new ZoneFileCouldntBeReadException(zone.FilePath); /* Couldn't read map file=>throw exception */ }\r\n\r\n\t\t\tGV.Misc.RemoveComments(ref zoneContents); // remove comment notations from file contents because they serve no revelence\r\n\r\n\t\t\tstring[] splitZoneContents = zoneContents.Split('\\n'); // Get all lines contained within the zone file\r\n\r\n\t\t\tif (!Parser.HeaderCheck(zoneContents, Zone.ZONE_FILE_HEADER)) throw new ZoneHeaderException(zone.FilePath); // Header failed\r\n\r\n\t\t\tstring zoneDimensionsString = splitZoneContents[0].Replace(Zone.ZONE_FILE_HEADER, \"\").Trim();\r\n\r\n\t\t\tif (zoneDimensionsString.Length != 0) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tVector2 size = Vector2Parser(zoneDimensionsString);\r\n\t\t\t\t\tzone.ZoneWidth = (int)size.X; zone.ZoneHeight = (int)size.Y;\r\n\t\t\t\t} catch { /*zone.ZoneWidth = Zone.DEFAULT_ZONE_WIDTH; zone.ZoneHeight = Zone.DEFAULT_ZONE_HEIGHT;*/ }\r\n\t\t\t}\r\n\r\n\t\t\treturn GV.CollectionManipulator.GetSubArray(splitZoneContents, 1, splitZoneContents.Length-1);\r\n\r\n\t\t\t//return zoneContents.Substring(Zone.ZONE_FILE_HEADER.Length, zoneContents.Length - Zone.ZONE_FILE_HEADER.Length).Split('\\n');\r\n\t\t}\r\n\r\n\t\t#region NewParser\r\n\t\t/// <summary>Extracts command from line in zone file</summary>\r\n\t\t/// <param name=\"line\">Line from which command should be extracted</param>\r\n\t\tprivate static String GetCommand(String line) {\r\n\t\t\tMatch lineMatch = Regex.Match(line, @\"\\w+:\"); // Match desired word command from line\r\n\r\n\t\t\tif (lineMatch.Success) return lineMatch.Value.Substring(0, lineMatch.Value.Length - 1);\r\n\r\n\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Extract Command From Line '{line}'\", lineIndex);\r\n\t\t}\r\n\r\n\t\t/// <summary>Removes command from line</summary>\r\n\t\tprivate static String RemoveCommand(String line, String command) {\r\n\t\t\treturn line.Replace($\"{command}:\", \"\").Trim();\r\n\t\t}\r\n\r\n\t\t/// <summary>Get's region contained within a code block</summary>\r\n\t\t/// <param name=\"endStatement\">Statement which defines the end of the code block</param>\r\n\t\t/// <returns>Contents of a given code block</returns>\r\n\t\tprivate static String[] GetCodeBlock(String endStatement) {\r\n\t\t\tList<String> blockContents = new List<String>();\r\n\t\t\r\n\t\t\tfor (int X = lineIndex + 1; X < fileContents.Length; X++) {\r\n\t\t\t\tif (String.IsNullOrWhiteSpace(fileContents[X])) continue;\r\n\r\n\t\t\t\tif (GetCommand(fileContents[X]).ToUpper() == endStatement.ToUpper()) {\r\n\t\t\t\t\tlineIndex = X + 1; // Account for skipped values\r\n\t\t\t\t\treturn blockContents.ToArray(); // Return stored block contents\r\n\t\t\t\t}\r\n\r\n\t\t\t\tblockContents.Add(fileContents[X]);\r\n\t\t\t}\r\n\r\n\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"End Block Statement '{endStatement}' Not Found\", fileContents.Length-1);\r\n\t\t}\r\n\r\n\t\t/// <summary>Extracts all asset IDs ina string</summary>\r\n\t\t/// <param name=\"line\">Line containing [asset IDs]</param>\r\n\t\t/// <returns>Array containing all found asset IDs</returns>\r\n\t\tprivate static String[] GetAssetIDs(String line) {\r\n\t\t\tMatchCollection matches = Regex.Matches(line, @\"\\[[^\\r\\n ]+\\]\");\r\n\r\n\t\t\tif (matches.Count != 0)\r\n\t\t\t\treturn (from Match X in matches select X.Value.Replace(\"[\", \"\").Replace(\"]\", \"\")).ToArray();\r\n\r\n\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Extract Asset ID From String {line}\", lineIndex);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region ParserWrapper\r\n\t\tprivate static Vector2 Vector2Parser(String line) {\r\n\t\t\ttry { return Parser.Vector2Parser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Convert Line '{line}' To Vector\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static Boolean BooleanParser(String line) {\r\n\t\t\ttry { return Parser.BooleanParser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Convert Line '{line}' To Boolean\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static int[] IntegerParser(String line) {\r\n\t\t\ttry { return Parser.IntegerParser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Convert Line '{line}' To Integer\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static float[] FloatParser(String line) {\r\n\t\t\ttry { return Parser.FloatParser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, $\"Couldn't Convert Line '{line}' To Float\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static String BracketParser(String line) {\r\n\t\t\ttry { return Parser.GetValueInParentheses(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, e.Message, lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static String SpeechMarkParser(String line) {\r\n\t\t\ttry { return Parser.GetValueInSpeechMarks(line); } catch (Exception e) {\r\n\t\t\t\tthrow new ZoneSyntaxException(zone.FilePath, e.Message, lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static AnimationSequence AnimationParser(String anim) {\r\n\t\t\ttry { return Parser.AnimationParser(anim); } catch (Exception e) {\r\n\t\t\t\tthrow new HollowAetherException($\"Couldn't Convert Line '{anim}' To Animation\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Reference to zone instance</summary>\r\n\t\tprivate static Zone zone;\r\n\r\n\t\t/// <summary>Contents of zone file</summary>\r\n\t\tprivate static String[] fileContents;\r\n\r\n\t\t/// <summary>Index of line in file contents</summary>\r\n\t\tprivate static int lineIndex;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6916788816452026, "alphanum_fraction": 0.6961503624916077, "avg_line_length": 40.853294372558594, "blob_id": "38b5a591d797fb91f58263e16c012588d059a46a", "content_id": "abb42e4282ff4b3bb4b7de1cd7ba538ad78c2510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14315, "license_type": "no_license", "max_line_length": 115, "num_lines": 334, "path": "/HollowAether/Lib/GAssets/Boundary/CollisionChecking.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tstatic class CollisionChecker { // IBoundary Exclusive\r\n\t\tpublic static bool InterpretCollision(IBoundary A, IBoundary B) {\r\n\t\t\tif (!A.Container.Intersects(B.Container))\r\n\t\t\t\treturn false; // If no container collision then return\r\n\r\n\t\t\t#region CrossStitchingLogic\r\n\t\t\tFunc<IBoundary, String> ToTypeString = (boundary) => {\r\n\t\t\t\tif (boundary is IBRectangle)\t\t\t return \"Rectangle\";\r\n\t\t\t\telse if (boundary is IBTriangle)\t\t return \"Triangle\";\r\n\t\t\t\telse if (boundary is IBCircle)\t\t\t return \"Circle\";\r\n\t\t\t\telse if (boundary is IBRotatedRectangle) return \"RRectangle\";\r\n\t\t\t\telse /* Impossible Return CMD */\t\t return String.Empty;\r\n\t\t\t};\r\n\r\n\t\t\tswitch (ToTypeString(A)) {\r\n\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t#region PrimaryRectangleBody\r\n\t\t\t\t\tswitch (ToTypeString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn RectangleToRectangle((IBRectangle)A, (IBRectangle)B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn RectangleToTriangle((IBRectangle)A, (IBTriangle)B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\t\treturn RectangleToCircle((IBRectangle)A, (IBCircle)B);\r\n\t\t\t\t\t\tcase \"RRectangle\":\r\n\t\t\t\t\t\t\treturn RectangleToRotatedRectangle((IBRectangle)A, (IBRotatedRectangle)B);\r\n\t\t\t\t\t\tdefault: return false; // Pretty much impossible, but just in case\r\n\t\t\t\t\t}\r\n\t\t\t\t\t#endregion\r\n\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t#region PrimaryTriangleBody\r\n\t\t\t\t\tswitch (ToTypeString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn TriangleToRectangle((IBTriangle)A, (IBRectangle)B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn TriangleToTriangle((IBTriangle)A, (IBTriangle)B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\t\treturn TriangleToCircle((IBTriangle)A, (IBCircle)B);\r\n\t\t\t\t\t\tcase \"RRectangle\":\r\n\t\t\t\t\t\t\treturn TriangleToRotatedRectangle((IBTriangle)A, (IBRotatedRectangle)B);\r\n\t\t\t\t\t\tdefault: return false; // Pretty much impossible, but just in case\r\n\t\t\t\t\t}\r\n\t\t\t\t\t#endregion\r\n\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t#region PrimaryCircleBody\r\n\t\t\t\t\tswitch (ToTypeString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn CircleToRectangle((IBCircle)A, (IBRectangle)B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn CircleToTriangle((IBCircle)A, (IBTriangle)B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\t\treturn CircleToCircle((IBCircle)A, (IBCircle)B);\r\n\t\t\t\t\t\tcase \"RRectangle\":\r\n\t\t\t\t\t\t\treturn CircleToRotatedRectangle((IBCircle)A, (IBRotatedRectangle)B);\r\n\t\t\t\t\t\tdefault: return false; // Pretty much impossible, but just in case\r\n\t\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\t\t\t\tcase \"RRectangle\":\r\n\t\t\t\t\t#region PrimaryRotatedRectangleBody\r\n\t\t\t\t\tswitch (ToTypeString(B)) {\r\n\t\t\t\t\t\tcase \"Rectangle\":\r\n\t\t\t\t\t\t\treturn RotatedRectangleToRectangle((IBRotatedRectangle)A, (IBRectangle)B);\r\n\t\t\t\t\t\tcase \"Triangle\":\r\n\t\t\t\t\t\t\treturn RotatedRectangleToTriangle((IBRotatedRectangle)A, (IBTriangle)B);\r\n\t\t\t\t\t\tcase \"Circle\":\r\n\t\t\t\t\t\t\treturn RotatedRectangleToCircle((IBRotatedRectangle)A, (IBCircle)B);\r\n\t\t\t\t\t\tcase \"RRectangle\":\r\n\t\t\t\t\t\t\treturn RotatedRectangleToRotatedRectangle((IBRotatedRectangle)A, (IBRotatedRectangle)B);\r\n\t\t\t\t\t\tdefault: return false; // Pretty much impossible, but just in case\r\n\t\t\t\t\t};\r\n\t\t\t\t\t#endregion\r\n\t\t\t\tdefault: return false; // Pretty much impossible, but just in case\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\t\t}\r\n\r\n\t\tstatic bool RectangleToRectangle(IBRectangle A, IBRectangle B) { return A.Intersects(B); } // Complete\r\n\r\n\t\tstatic bool RectangleToTriangle(IBRectangle A, IBTriangle B) {\r\n\t\t\tfor (int X = 0; X < 3; X++) { // For primary Vector in Ventrices\r\n\t\t\t\tfor (int Y = 0; Y < 3; Y++) { // For secondary Vector in Ventrices\r\n\t\t\t\t\tif (B[X] == B[Y]) { continue; } // If Vects Match Skip Forward\r\n\r\n\t\t\t\t\tforeach (var RectLine in GV.Convert.RectangleTo4Lines(A)) { // For Each Line In Given Rectangle\r\n\t\t\t\t\t\tif (B.backBone.LineIntersects(RectLine.pointA, RectLine.pointB, B[X], B[Y]))\r\n\t\t\t\t\t\t\treturn true; // Rectangle line intersects current triangle instances' line\r\n\t\t\t\t\t} // Return True on first instance of intersection between triangle lines\r\n\t\t\t\t} // -- Intersection Check to See If Rect Intersects With Any of the Triangles Lines\r\n\t\t\t} // ------------- Evaluates to Nothing If Rectangle is Contained Entirely Within Triangle\r\n\r\n\t\t\tforeach (Vector2 vect in GV.Convert.RectangleTo4Vects(A)) { if (B.Contains(vect)) return true; }\r\n\t\t\t// Checks wether rectangle is contained entirely within the current triangle instance\r\n\t\t\treturn false; // If all of the above methods evaluate to false, return false\r\n\t\t} // complete\r\n\t\t\r\n\t\tstatic bool RectangleToCircle(IBRectangle A, IBCircle B) {\r\n\t\t\tfloat closestX = GlobalVars.BasicMath.Clamp(B.X, A.Left, A.Right);\r\n\t\t\tfloat closestY = GlobalVars.BasicMath.Clamp(B.Y, A.Top, A.Bottom);\r\n\r\n\t\t\tfloat distanceX = B.X - closestX, distanceY = B.Y - closestY; // Distances displacement\r\n\t\t\treturn Math.Pow(distanceX, 2) + Math.Pow(distanceY, 2) < Math.Pow(B.radius, 2);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool RectangleToRotatedRectangle(IBRectangle A, IBRotatedRectangle B) {\r\n\t\t\treturn RotatedRectangleToRectangle(B, A);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool TriangleToRectangle(IBTriangle A, IBRectangle B) {\r\n\t\t\treturn RectangleToTriangle(B, A); // Reverse then call\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool TriangleToTriangle(IBTriangle A, IBTriangle B) {\r\n\t\t\tfor (int X = 0; X < 3; X++) { // For primary Vector in Ventrices\r\n\t\t\t\tfor (int Y = 0; Y < 3; Y++) { // For secondary Vector in Ventrices\r\n\t\t\t\t\tif (A[X] == A[Y]) { continue; } // When vects match skip forward\r\n\r\n\t\t\t\t\tforeach (Line line in GV.Convert.TriangleTo3Lines(B)) {\r\n\t\t\t\t\t\tif (A.backBone.LineIntersects(line, new Line(A[X], A[Y])))\r\n\t\t\t\t\t\t\treturn true; // argument tri-line intersects current triangles line\r\n\t\t\t\t\t} // Return True on first instance of intersection between triangle lines\r\n\t\t\t\t} // -- Checks to see matching collision between different triangle lines\r\n\t\t\t} // ---- Evaluates to Nothing If Argument Triangle is Contained Entirely Within This\r\n\r\n\t\t\tforeach (Vector2 vect in B.Ventrices) { if (A.Contains(vect)) return true; }\r\n\t\t\t// Checks wether ArgTri is contained entirely within the current triangle instance\r\n\t\t\treturn false; // If all of the above methods evaluate to false, return false\r\n\t\t} // Complete\r\n\t\t\r\n\t\tstatic bool TriangleToCircle(IBTriangle A, IBCircle B) {\r\n\t\t\tforeach (Vector2 ventrice in A.Ventrices) {\r\n\t\t\t\tif (B.Contains(ventrice)) return true;\r\n\t\t\t}\r\n\r\n\t\t\tforeach (Line line in GV.Convert.TriangleTo3Lines(A)) {\r\n\t\t\t\tif (B.Intersects(line)) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool TriangleToRotatedRectangle(IBTriangle A, IBRotatedRectangle B) {\r\n\t\t\treturn RotatedRectangleToTriangle(B, A);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool CircleToRectangle(IBCircle A, IBRectangle B) {\r\n\t\t\treturn RectangleToCircle(B, A); // Reverse Then Call\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool CircleToTriangle(IBCircle A, IBTriangle B) {\r\n\t\t\treturn TriangleToCircle(B, A);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool CircleToCircle(IBCircle A, IBCircle B) {\r\n\t\t\treturn (B.origin - A.origin).Length() < (B.radius - A.radius);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool CircleToRotatedRectangle(IBCircle A, IBRotatedRectangle B) {\r\n\t\t\treturn RotatedRectangleToCircle(B, A);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool RotatedRectangleToRectangle(IBRotatedRectangle A, IBRectangle B) {\r\n\t\t\treturn A.Intersects((Rectangle)B);\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool RotatedRectangleToTriangle(IBRotatedRectangle A, IBTriangle B) {\r\n\t\t\tforeach (Line line in GV.Convert.TriangleTo3Lines(B))\r\n\t\t\t\tif (A.Intersects(line)) return true;\r\n\r\n\t\t\treturn false; // No collision with any lines\r\n\t\t} // Complete\r\n\r\n\t\tstatic bool RotatedRectangleToCircle(IBRotatedRectangle A, IBCircle B) {\r\n\t\t\tforeach (Line line in GV.Convert.RotatedRectangleTo4Lines(A))\r\n\t\t\t\tif (B.Intersects(line)) return true; // Any lines intersect\r\n\r\n\t\t\t// Try detect if circle within rectangle or otherwise\r\n\r\n\t\t\treturn false; // No intersection detected\r\n\t\t} // Partially Complete\r\n\r\n\t\tstatic bool RotatedRectangleToRotatedRectangle(IBRotatedRectangle A, IBRotatedRectangle B) {\r\n\t\t\treturn A.Intersects(B);\r\n\t\t} // Complete\r\n\t}\r\n\r\n\t#region CollisionDefinitions\r\n\tpublic partial class IBTriangle {\r\n\t\t/// <summary>Checks for intersection between triangle and another boundary type</summary>\r\n\t\t/// <param name=\"boundary\">Other boundary type to check collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesful collision with boundary</returns>\r\n\t\tpublic bool Intersects(IBoundary boundary) {\r\n\t\t\treturn CollisionChecker.InterpretCollision(this, boundary);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for intersection with non boundary type rectangle</summary>\r\n\t\t/// <param name=\"target\">Target rectangle to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision with rectangle</returns>\r\n\t\tpublic bool Intersects(Rectangle target) {\r\n\t\t\treturn Intersects((IBoundary)(new IBRectangle(target)));\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for triangle intersection with target</summary>\r\n\t\t/// <param name=\"target\">Target line to check for collision</param>\r\n\t\t/// <returns>Boolean indicating triangular collision</returns>\r\n\t\tpublic bool Intersects(Line target) {\r\n\t\t\tforeach (Line line in GV.Convert.TriangleTo3Lines(this)) {\r\n\t\t\t\t//if (backBone.LineIntersects(line.pointA, line.pointB, target.pointA, target.pointB, false))\r\n\t\t\t\tif (line.Intersects(target)) return true; // Upon first sucesfull line collision return true\r\n\t\t\t}\r\n\r\n\t\t\treturn false; // No collision found\r\n\t\t}\r\n\r\n\t\t/// <summary> Checks whether triangle contains a given point </summary>\r\n\t\t/// <param name=\"point\">Point which can be within triangle</param>\r\n\t\t/// <returns>Boolean Representing whether Point Lies Within Triangle</returns>\r\n\t\tpublic bool Contains(Vector2 point) { return Container.Contains(point.ToPoint()) && backBone.Intersects(point); }\r\n\t}\r\n\r\n\tpublic partial struct IBRectangle {\r\n\t\t/// <summary>Checks for intersection between rectangle and another boundary type</summary>\r\n\t\t/// <param name=\"boundary\">Other boundary type to check collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesful collision with boundary</returns>\r\n\t\tpublic bool Intersects(IBoundary boundary) {\r\n\t\t\treturn CollisionChecker.InterpretCollision(this, boundary);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for intersection with non boundary type rectangle</summary>\r\n\t\t/// <param name=\"target\">Target rectangle to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision with rectangle</returns>\r\n\t\tpublic bool Intersects(Rectangle target) {\r\n\t\t\treturn Intersects((IBoundary)(new IBRectangle(target)));\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for rectangular intersection with a given line</summary>\r\n\t\t/// <param name=\"target\">Target line to check for intersecction with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision</returns>\r\n\t\tpublic bool Intersects(Line target) {\r\n\t\t\tforeach (Line line in GV.Convert.RectangleTo4Lines(this)) {\r\n\t\t\t\tif (target.Intersects(line)) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false; // If not yet returned then return false\r\n\t\t}\r\n\t}\r\n\r\n\tpublic partial struct IBCircle {\r\n\t\t/// <summary>Checks for intersection between circle and another boundary type</summary>\r\n\t\t/// <param name=\"boundary\">Other boundary type to check collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesful collision with boundary</returns>\r\n\t\tpublic bool Intersects(IBoundary target) {\r\n\t\t\treturn CollisionChecker.InterpretCollision(this, target);\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for intersection with non boundary type rectangle</summary>\r\n\t\t/// <param name=\"target\">Target rectangle to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision with rectangle</returns>\r\n\t\tpublic bool Intersects(Rectangle target) {\r\n\t\t\treturn Intersects((IBoundary)(new IBRectangle(target)));\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks for intersection between circle and a given line using quadratic approach</summary>\r\n\t\t/// <param name=\"line\">Line to check for collision with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision with circle</returns>\r\n\t\t/// <remarks>Method gotten from Stackoverflow Question ID 1073336</remarks>\r\n\t\tpublic bool Intersects(Line line) {\r\n\t\t\tVector2 d = line.pointB - line.pointA, f = line.pointA - origin; // Vectorial Displacement Definition\r\n\t\t\tfloat a = Vector2.Dot(d, d), b = 2*Vector2.Dot(f, d), c = Vector2.Dot(f, f) - (float)Math.Pow(radius, 2);\r\n\t\t\tfloat discriminant = (float)Math.Pow(b, 2) - (4 * a * c); // B^2 - 4xAxC => Quadratic Discriminant\r\n\r\n\t\t\tif (discriminant < 0) { return false; /* -Ve discriminant has no root */ } else {\r\n\r\n\t\t\t\tdiscriminant = (float)Math.Sqrt(discriminant); // Root of discriminant\r\n\r\n\t\t\t\tfloat root1 = (-b - discriminant) / (2 * a), root2 = (-b + discriminant) / (2 * a);\r\n\r\n\t\t\t\treturn (root1 >= 0 && root1 <= 1) || (root2 >= 0 && root2 <= 1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary> Checks whether Circle contains a given point </summary>\r\n\t\t/// <param name=\"point\">Point which can be within circle</param>\r\n\t\t/// <returns>Boolean Representing whether Point Lies Within Circle</returns>\r\n\t\tpublic bool Contains(Vector2 vect) {\r\n\t\t\treturn (vect - origin).Length() <= radius;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic partial class IBRotatedRectangle {\r\n\t\tpublic bool Intersects(IBoundary other) {\r\n\t\t\treturn CollisionChecker.InterpretCollision(this, other);\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(Rectangle rect) { return Intersects(new IBRotatedRectangle(rect, 0.0f)); }\r\n\r\n\t\tpublic bool Intersects(Point point) { return Intersects(point.X, point.Y); }\r\n\r\n\t\tpublic bool Intersects(int X, int Y) { return Intersects(new IBRotatedRectangle(X, Y, 1, 1, 0.0f)); }\r\n\r\n\t\tpublic bool Intersects(IBRotatedRectangle rect) {\r\n\t\t\tVector2[] rectAxes = new Vector2[] {\r\n\t\t\t\tthis.RotatedTopRightPoint - this.RotatedTopLeftPoint,\r\n\t\t\t\tthis.RotatedTopRightPoint - this.RotatedBottomRightPoint,\r\n\t\t\t\trect.RotatedTopLeftPoint - rect.RotatedTopRightPoint,\r\n\t\t\t\trect.RotatedTopLeftPoint - rect.RotatedBottomLeftPoint\r\n\t\t\t};\r\n\r\n\t\t\tforeach (Vector2 axis in rectAxes) {\r\n\t\t\t\tif (!IsAxisCollision(rect, axis))\r\n\t\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\treturn true; // Collision has occured\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(Line line) {\r\n\t\t\tforeach (Line rectLine in GV.Convert.RotatedRectangleTo4Lines(this))\r\n\t\t\t\tif (line.Intersects(rectLine)) return true;\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.7441099286079407, "alphanum_fraction": 0.7447643876075745, "avg_line_length": 46.66242218017578, "blob_id": "53ff486921959677869880a1b9928c1381833a4a", "content_id": "06f5baf45e5944bf4239b761441506946a800f83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7642, "license_type": "no_license", "max_line_length": 141, "num_lines": 157, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/MZExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\t#region MapExceptions\r\n\tclass MapException : HollowAetherException {\r\n\t\tpublic MapException(String fPath) { filePath = fPath; }\r\n\t\tpublic MapException(String fpath, String message) : base(message) { filePath = fpath; }\r\n\t\tpublic MapException(String fpath, String message, Exception inner) : base(message, inner) { filePath = fpath; }\r\n\r\n\t\tprivate String filePath;\r\n\t}\r\n\r\n\tclass MapNotFoundException : MapException {\r\n\t\tpublic MapNotFoundException(String fpath) : base(fpath, $\"Map At Given Path Not Found\") { }\r\n\t\tpublic MapNotFoundException(String fpath, Exception inner) : base(fpath, $\"Map At Given Path Not Found\", inner) { }\r\n\t}\r\n\r\n\tclass MapFileCouldntBeReadException : MapException {\r\n\t\tpublic MapFileCouldntBeReadException(String fpath) : base(fpath, $\"Couldn't Read Given Map File\") { }\r\n\t\tpublic MapFileCouldntBeReadException(String fpath, Exception inner) : base(fpath, $\"Couldn't Read Given Map File\", inner) { }\r\n\t}\r\n\r\n\tclass MapHeaderException : MapException {\r\n\t\tpublic MapHeaderException(String fpath) : base(fpath, $\"Incorrect Map Header In Map File\") { }\r\n\t\tpublic MapHeaderException(String fpath, Exception inner) : base(fpath, $\"Incorrect Map Header In Map File\", inner) { }\r\n\t}\r\n\r\n\tclass MapSyntaxException : MapException {\r\n\t\tpublic MapSyntaxException(String fpath, int lIndex) : base(fpath) { lineIndex = lIndex; }\r\n\t\tpublic MapSyntaxException(String fpath, String message, int lIndex) : base(fpath, message) { lineIndex = lIndex; }\r\n\t\tpublic MapSyntaxException(String fpath, String message, int lIndex, Exception inner) : base(fpath, message, inner) { lineIndex = lIndex; }\r\n\r\n\t\tpublic int lineIndex;\r\n\t}\r\n\r\n\tclass MapLineConversionException : MapSyntaxException {\r\n\t\tpublic MapLineConversionException(String fPath, String line, String desiredType, int lineIndex)\r\n\t\t\t: base(fPath, $\"Couldn't Convert Line '{line}' to Instance Of Type '{desiredType}'\", lineIndex) { }\r\n\t\tpublic MapLineConversionException(String fPath, String line, String desiredType, int lineIndex, Exception inner)\r\n\t\t\t: base(fPath, $\"Couldn't Convert Line '{line}' to Instance Of Type '{desiredType}'\", lineIndex, inner) { }\r\n\t}\r\n\r\n\tclass MapRepeatedFlagCreationException : MapSyntaxException {\r\n\t\tpublic MapRepeatedFlagCreationException(String filePath, String flagName, int lineIndex)\r\n\t\t\t: base(filePath, $\"Cannot create flag '{flagName}' when it already exists\", lineIndex) { }\r\n\t\tpublic MapRepeatedFlagCreationException(String filePath, String flagName, int lineIndex, Exception inner)\r\n\t\t\t: base(filePath, $\"Cannot create flag '{flagName}' when it already exists\", lineIndex, inner) { }\r\n\t}\r\n\r\n\tclass MapFileDefinesZoneAtSamePositionTwiceException : MapSyntaxException {\r\n\t\tpublic MapFileDefinesZoneAtSamePositionTwiceException(String fpath, Vector2 index, int lineIndex)\r\n\t\t\t: base(fpath, $\"Zone Has Been Defined At Position '{index}' Twice\", lineIndex) { }\r\n\t\tpublic MapFileDefinesZoneAtSamePositionTwiceException(String fpath, Vector2 index, int lineIndex, Exception inner)\r\n\t\t\t: base(fpath, $\"Zone Has Been Defined At Position '{index}' Twice\", lineIndex, inner) { }\r\n\t}\r\n\r\n\tclass MapUnknownVisibilityException : MapSyntaxException {\r\n\t\tpublic MapUnknownVisibilityException(String filePath, String type, int lineIndex)\r\n\t\t\t: base(filePath, $\"Unknown Zone Identifier '{type}' Found in Map File\", lineIndex) { }\r\n\t\tpublic MapUnknownVisibilityException(String filePath, String type, int lineIndex, Exception inner)\r\n\t\t\t: base(filePath, $\"Unknown Zone Identifier '{type}' Found in Map File\", lineIndex, inner) { }\r\n\t}\r\n\t#endregion\r\n\r\n\t#region ZoneExceptions\r\n\tclass ZoneException : HollowAetherException {\r\n\t\tpublic ZoneException() : base() { }\r\n\r\n\t\tpublic ZoneException(String msg) : base(msg) { }\r\n\r\n\t\tpublic ZoneException(String msg, Exception inner) : base(msg, inner) { }\r\n\r\n\t\tpublic ZoneException(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t}\r\n\r\n\tclass ZoneReadingException : ZoneException {\r\n\t\tpublic ZoneReadingException(String fpath) : base() { filePath = fpath; }\r\n\t\tpublic ZoneReadingException(String fpath, String message) : base(message) { filePath = fpath; }\r\n\t\tpublic ZoneReadingException(String fpath, String message, Exception inner) : base(message, inner) { filePath = fpath; }\r\n\r\n\t\tpublic String filePath;\r\n\t}\r\n\r\n\tclass ZoneNotFoundException : ZoneReadingException {\r\n\t\tpublic ZoneNotFoundException(String fpath) : base(fpath, $\"Zone At \\\"{fpath}\\\" Not Found\") { }\r\n\t\tpublic ZoneNotFoundException(String fpath, Exception inner) : base(fpath, $\"Zone At \\\"{fpath}\\\" Not Found\", inner) { }\r\n\t}\r\n\r\n\tclass ZoneFileCouldntBeReadException : ZoneReadingException {\r\n\t\tpublic ZoneFileCouldntBeReadException(String fpath) : base(fpath, $\"Couldn't Read Given Zone File\") { }\r\n\t\tpublic ZoneFileCouldntBeReadException(String fpath, Exception inner) : base(fpath, $\"Couldn't Read Given Zone File\", inner) { }\r\n\t}\r\n\r\n\tclass ZoneHeaderException : ZoneReadingException {\r\n\t\tpublic ZoneHeaderException(String fpath) : base(fpath, $\"Incorrect Map Header In Map File\") { }\r\n\t\tpublic ZoneHeaderException(String fpath, Exception inner) : base(fpath, $\"Incorrect Map Header In Map File\") { }\r\n\t}\r\n\r\n\tclass ZoneSyntaxException : ZoneReadingException {\r\n\t\tpublic ZoneSyntaxException(String fpath, int lIndex) : base(fpath) { lineIndex = lIndex; }\r\n\t\tpublic ZoneSyntaxException(String fpath, String message, int lIndex) : base(fpath, message) { lineIndex = lIndex; }\r\n\t\tpublic ZoneSyntaxException(String fpath, String message, int lIndex, Exception inner) : base(fpath, message, inner) { lineIndex = lIndex; }\r\n\r\n\t\tpublic int lineIndex;\r\n\t}\r\n\r\n\r\n\tclass ZoneCouldNotFindAssetToImportException : ZoneSyntaxException {\r\n\t\tpublic ZoneCouldNotFindAssetToImportException(String filePath, Type assetType, String assetID, int lineIndex)\r\n\t\t\t: base(filePath, $\"\", lineIndex) { }\r\n\t\tpublic ZoneCouldNotFindAssetToImportException(String filePath, Type assetType, String assetID, int lineIndex, Exception inner)\r\n\t\t\t: base(filePath, $\"\", lineIndex, inner) { }\r\n\t}\r\n\r\n\tclass ZoneAssetNotFoundException : ZoneSyntaxException {\r\n\t\tpublic ZoneAssetNotFoundException(String filePath, String assetID, int lineIndex)\r\n\t\t\t: base(filePath, $\"\", lineIndex) { }\r\n\t\tpublic ZoneAssetNotFoundException(String filePath, String assetID, int lineIndex, Exception inner)\r\n\t\t\t: base(filePath, $\"\", lineIndex, inner) { }\r\n\t}\r\n\t#endregion\r\n\r\n\t#region Misc\r\n\tclass AssetAssignmentException : HollowAetherException {\r\n\t\tpublic AssetAssignmentException(Type desired, Type given)\r\n\t\t\t: base($\"Cannot assign Asset of Type '{desired}' A Value of Type {given}\") { }\r\n\t\tpublic AssetAssignmentException(Type desired, Type given, Exception inner)\r\n\t\t\t: base($\"Cannot assign Asset of Type '{desired}' A Value of Type {given}\", inner) { }\r\n\t}\r\n\r\n\tclass ZoneWithGivenMapIndexNotFoundException : HollowAetherException {\r\n\t\tpublic ZoneWithGivenMapIndexNotFoundException(Vector2 missingIndex)\r\n\t\t\t: base($\"Zone with key '{missingIndex}' Not Found\") { index = missingIndex; }\r\n\t\tpublic ZoneWithGivenMapIndexNotFoundException(Vector2 missingIndex, Exception inner)\r\n\t\t\t: base($\"Zone with key '{missingIndex}' Not Found\", inner) { index = missingIndex; }\r\n\r\n\t\tpublic Vector2 index;\r\n\t}\r\n\t#endregion\r\n}\r\n" }, { "alpha_fraction": 0.7129436135292053, "alphanum_fraction": 0.7223381996154785, "avg_line_length": 23.891891479492188, "blob_id": "5387cae51146453114c15b768908af764b6d6866", "content_id": "9a17cb0998155d518ca1b788ef7c3e7087e7e886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 960, "license_type": "no_license", "max_line_length": 85, "num_lines": 37, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Crawler.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Crawler : Enemy, IPredefinedTexture {\r\n\t\tpublic Crawler(Vector2 position, int level) : base(position, 32, 32, level, true) {\r\n\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tthrow new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tthrow new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tprotected override void DoEnemyStuff() {\r\n\t\t\tthrow new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tprotected override bool CanGenerateHealth { get; set; } = false;\r\n\r\n\t\tprotected override bool CausesContactDamage { get; set; } = true;\r\n\t\t\r\n\t\tpublic const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7277960777282715, "alphanum_fraction": 0.7277960777282715, "avg_line_length": 30.864864349365234, "blob_id": "8cdc71c64ef07fc9fbdbfc704836a2beac03ecad", "content_id": "4f64e1f3c2b869912ec44056e30a7b61b7d27aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1218, "license_type": "no_license", "max_line_length": 102, "num_lines": 37, "path": "/HollowAether/Lib/InputOutput/Parsers/ZoneCommandImplement/Assistance.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.MapZone;\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tstatic partial class ZoneParser {\r\n\t\tprivate static void AddAsset(String assetID, Asset asset) {\r\n\t\t\tif (zone.assets.ContainsKey(assetID))\r\n\t\t\t\tthrow new HollowAetherException($\"Cannot Create Asset '{assetID}' When it already exists\");\r\n\r\n\t\t\tzone.assets.Add(assetID, asset);\r\n\t\t}\r\n\r\n\t\tprivate static void SetAsset(String ID, object value) {\r\n\t\t\tif (GV.MapZone.globalAssets.ContainsKey(ID))\r\n\t\t\t\tGV.MapZone.globalAssets[ID].SetAsset(value);\r\n\t\t\telse if (zone.assets.ContainsKey(ID))\r\n\t\t\t\tzone.assets[ID].SetAsset(value);\r\n\t\t\telse\r\n\t\t\t\tthrow new HollowAetherException();\r\n\t\t}\r\n\r\n\t\tprivate static bool AssetExists(String ID) {\r\n\t\t\treturn (zone.assets.Keys.Contains(ID) || GlobalVars.MapZone.globalAssets.Keys.Contains(ID));\r\n\t\t}\r\n\r\n\t\tprivate static bool FlagExists(String ID) {\r\n\t\t\treturn (GV.MapZone.globalAssets.ContainsKey(ID) && GV.MapZone.globalAssets[ID].TypesMatch<Flag>());\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.684023916721344, "alphanum_fraction": 0.6906713843345642, "avg_line_length": 35.92436981201172, "blob_id": "a0c86adc785e614535718b1d31fc7352749c563d", "content_id": "04ba8ac7ea81a0c2b7d4884efb791f16b1ea2675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9028, "license_type": "no_license", "max_line_length": 127, "num_lines": 238, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/AnimationView/AnimationViewDataStore.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing SysInfo = System.Windows.Forms.SystemInformation;\r\nusing HollowAether.Lib.GAssets;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic class AnimationViewDataStore : Panel {\r\n\t\tpublic class FramesContainer : Panel {\r\n\t\t\tpublic FramesContainer(AnimationSequence sequence, int tileDimensions) {\r\n\t\t\t\tHeight = tileDimensions; // Encompasses Entire Height Of Frame Tiles\r\n\t\t\t\tBackColor = Color.Black; // Background Color Is Black, To Contrast Tile\r\n\t\t\t\tthis.sequence = sequence; // Store reference to animation sequence for ops\r\n\t\t\t\tthis.tileDimensions = tileDimensions;\r\n\r\n\t\t\t\ttileBoxes.AddRange(EnumerateFramesAsTileBoxes().ToArray());\r\n\t\t\t\tControls.AddRange(tileBoxes.ToArray()); // Add all tiles to control\r\n\t\t\t}\r\n\r\n\t\t\tprivate IEnumerable<TileBox> EnumerateFramesAsTileBoxes() {\r\n\t\t\t\tint offset = 0; // Offset from horizontal axis\r\n\t\t\t\tContextMenuStrip cm = GetContextMenuStrip();\r\n\r\n\t\t\t\tforeach (Frame frame in sequence.Frames) {\r\n\t\t\t\t\tyield return GetTileBox(frame, offset, cm);\r\n\t\t\t\t\toffset += tileDimensions + TILE_OFFSET;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate TileBox GetTileBox(Frame frame, int offset, ContextMenuStrip cm) {\r\n\t\t\t\treturn new TileBox(frame) {\r\n\t\t\t\t\t#region Body\r\n\t\t\t\t\tWidth = tileDimensions,\r\n\t\t\t\t\tHeight = tileDimensions,\r\n\t\t\t\t\tContextMenuStrip = cm,\r\n\t\t\t\t\tLeft = offset,\r\n\t\t\t\t\tBackColor = Color.Red,\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tprivate ContextMenuStrip GetContextMenuStrip() {\r\n\t\t\t\tToolStripMenuItem modify = new ToolStripMenuItem(\"Modify\");\r\n\t\t\t\tmodify.Click += Modify_ContextMenuEventHandler;\r\n\r\n\t\t\t\tToolStripMenuItem delete = new ToolStripMenuItem(\"Delete\");\r\n\t\t\t\tdelete.Click += Delete_ContextMenuEventHandler;\r\n\r\n\t\t\t\tToolStripMenuItem moveLeft = new ToolStripMenuItem(\"Move Left\");\r\n\t\t\t\tmoveLeft.Click += MoveLeft_ContextMenuEventHandler;\r\n\r\n\t\t\t\tToolStripMenuItem moveRight = new ToolStripMenuItem(\"Move Right\");\r\n\t\t\t\tmoveRight.Click += MoveRight_ContextMenuEventHandler;\r\n\r\n\t\t\t\tContextMenuStrip cm = new ContextMenuStrip();\r\n\r\n\t\t\t\tcm.Items.AddRange(new ToolStripItem[] {\r\n\t\t\t\t\tmodify, delete, moveLeft, moveRight\r\n\t\t\t\t});\r\n\r\n\t\t\t\treturn cm;\r\n\t\t\t}\r\n\r\n\t\t\tpublic void ModifyFrame_Call(int index, TileBox tileBox=null) {\r\n\t\t\t\ttileBox = (tileBox == null) ? tileBoxes[index] : tileBox;\r\n\r\n\t\t\t\tstring textureKey = GV.LevelEditor.GetTextureKeyFromInstance(tileBox.Texture);\r\n\r\n\t\t\t\tEditFrameDialog edf = new EditFrameDialog(sequence, index, textureKey);\r\n\t\t\t\tedf.FormClosing += (s, e2) => { tileBox.AssignFrame(sequence[index]); };\r\n\r\n\t\t\t\tedf.Show(); // Display newly made Dialog form to user/caller etc.\r\n\t\t\t}\r\n\r\n\t\t\t#region ContextMenuEventHandlers\r\n\t\t\tprivate void Modify_ContextMenuEventHandler(object sender, EventArgs e) {\r\n\t\t\t\tTileBox tileBox = GetTileBoxFromToolStripItem(sender as ToolStripItem);\r\n\t\t\t\tif (tileBox != null) ModifyFrame_Call(tileBoxes.IndexOf(tileBox), tileBox);\r\n\t\t\t}\r\n\r\n\t\t\tprivate void Delete_ContextMenuEventHandler(object sender, EventArgs e) {\r\n\t\t\t\tif (tileBoxes.Count == 1)\r\n\t\t\t\t\tMessageBox.Show(\"Cannot Have Animation With No Frames\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t\t\telse {\r\n\t\t\t\t\tTileBox tileBox = GetTileBoxFromToolStripItem(sender as ToolStripItem);\r\n\r\n\t\t\t\t\tif (tileBox != null) {\r\n\t\t\t\t\t\tint index = tileBoxes.IndexOf(tileBox); // Get corresponding index\r\n\t\t\t\t\t\tbool lastValue = index == tileBoxes.Count - 1; // Is last tile\r\n\r\n\t\t\t\t\t\t#region DeleteReferences\r\n\t\t\t\t\t\ttileBoxes.RemoveAt(index);\r\n\t\t\t\t\t\tControls.RemoveAt(index);\r\n\t\t\t\t\t\tsequence.Frames.RemoveAt(index);\r\n\t\t\t\t\t\t#endregion\r\n\r\n\t\t\t\t\t\tif (!lastValue) { // Have to readjust remaining tiles\r\n\t\t\t\t\t\t\tforeach (int X in Enumerable.Range(index, tileBoxes.Count - 1)) {\r\n\t\t\t\t\t\t\t\ttileBoxes[X].Left = (X) * (tileDimensions + TILE_OFFSET);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate void MoveLeft_ContextMenuEventHandler(object sender, EventArgs e) {\r\n\t\t\t\tTileBox tileBox = GetTileBoxFromToolStripItem(sender as ToolStripItem);\r\n\r\n\t\t\t\tif (tileBox != null) {\r\n\t\t\t\t\tint index = tileBoxes.IndexOf(tileBox); // Get corresponding index\r\n\r\n\t\t\t\t\tif (index != 0) { // When not first item, can be moved to left\r\n\t\t\t\t\t\ttileBoxes[index].Left = (index - 1) * (tileDimensions + TILE_OFFSET);\r\n\t\t\t\t\t\ttileBoxes[index - 1].Left = (index) * (tileDimensions + TILE_OFFSET);\r\n\r\n\t\t\t\t\t\tGV.CollectionManipulator.SwapListValues(sequence.Frames, index, index - 1);\r\n\t\t\t\t\t\tGV.CollectionManipulator.SwapListValues(tileBoxes, index, index - 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate void MoveRight_ContextMenuEventHandler(object sender, EventArgs e) {\r\n\t\t\t\tTileBox tileBox = GetTileBoxFromToolStripItem(sender as ToolStripItem);\r\n\r\n\t\t\t\tif (tileBox != null) {\r\n\t\t\t\t\tint index = tileBoxes.IndexOf(tileBox); // Get corresponding index\r\n\r\n\t\t\t\t\tif (index != tileBoxes.Count - 1) { // When not last item in tileboxes\r\n\t\t\t\t\t\ttileBoxes[index].Left = (index + 1) * (tileDimensions + TILE_OFFSET);\r\n\t\t\t\t\t\ttileBoxes[index + 1].Left = (index) * (tileDimensions + TILE_OFFSET);\r\n\r\n\t\t\t\t\t\tGV.CollectionManipulator.SwapListValues(sequence.Frames, index, index + 1);\r\n\t\t\t\t\t\tGV.CollectionManipulator.SwapListValues(tileBoxes, index,\t\tindex + 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\tprivate TileBox GetTileBoxFromToolStripItem(ToolStripItem strip) {\r\n\t\t\t\tif (strip != null && strip.Owner as ContextMenuStrip != null) {\r\n\t\t\t\t\treturn (strip.Owner as ContextMenuStrip).SourceControl as TileBox;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn null; // Either strip or strip parent = null so skip\r\n\t\t\t}\r\n\r\n\t\t\tpublic void AppendFrame(Frame newFrame) {\r\n\t\t\t\tsequence.Frames.Add(newFrame); // Add Frame To Animation Sequence Instance\r\n\r\n\t\t\t\tint offset = (sequence.Frames.Count - 1) * (tileDimensions + TILE_OFFSET);\r\n\t\t\t\tTileBox tb = GetTileBox(newFrame, offset, GetContextMenuStrip());\r\n\t\t\t\ttb.AssignTexture(tileBoxes.First().Texture); // HAS TO EXIST BY DEFAULT\r\n\r\n\t\t\t\ttileBoxes.Add(tb); // Add new tile box to stored tileboxes\r\n\t\t\t\tControls.Add(tb); // Display tile box on control / panel\r\n\t\t\t}\r\n\r\n\t\t\tpublic void AssignTexture(Image image) {\r\n\t\t\t\tforeach (TileBox box in Controls) {\r\n\t\t\t\t\tbox.AssignTexture(image);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate const int TILE_OFFSET = 5;\r\n\t\t\tprivate AnimationSequence sequence;\r\n\t\t\tprivate int tileDimensions;\r\n\t\t\tprivate List<TileBox> tileBoxes = new List<TileBox>();\r\n\r\n\t\t\tpublic int Count { get { return tileBoxes.Count; } }\r\n\t\t}\r\n\r\n\t\tpublic AnimationViewDataStore(String sequenceKey) : base() {\r\n\t\t\tSize = GetSize(); // Store size of panel\r\n\t\t\tLeft = HORIZONTAL_OFFSET; // Add offset\r\n\t\t\tBorderStyle = BorderStyle.FixedSingle;\r\n\t\t\r\n\t\t\tBuildControls(sequenceKey);\r\n\t\t\tSequenceKey = sequenceKey;\r\n\r\n\t\t\taddFrameButton.Click += (s, e) => {\r\n\t\t\t\tcontainer.AppendFrame(new Frame(0, 0, 32, 32));\r\n\t\t\t\tcontainer.ModifyFrame_Call(container.Count - 1);\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic void BuildControls(string sequenceKey) {\r\n\t\t\tPathDetailsTextBox = new TextBox() { Width = 400, Height = CONTROLS_HEIGHT, ReadOnly = true };\r\n\r\n\t\t\tint buttonWidth = ((GetSize().Width - PathDetailsTextBox.Width) / 3) - BUTTON_HORIZONTAL_OFFSET; //- 1;\r\n\r\n\t\t\taddFrameButton\t\t = YieldButton(\"Add Frame\", PathDetailsTextBox.Right + BUTTON_HORIZONTAL_OFFSET, buttonWidth);\r\n\t\t\trenameAnimButton = YieldButton(\"Rename Animation\", addFrameButton.Right + BUTTON_HORIZONTAL_OFFSET, buttonWidth);\r\n\t\t\tdeleteSequenceButton = YieldButton(\"Delete Sequence\", renameAnimButton.Right + BUTTON_HORIZONTAL_OFFSET, buttonWidth+1);\r\n\r\n\t\t\tAnimationSequence sequence = GV.MonoGameImplement.importedAnimations[sequenceKey]; // Get animation sequence\r\n\t\t\tcontainer = new FramesContainer(sequence, Height - (CONTROLS_HEIGHT + 4)) { Width = Width, Top = CONTROLS_HEIGHT + 4 };\r\n\r\n\t\t\tControls.AddRange(new Control[] { PathDetailsTextBox, addFrameButton, deleteSequenceButton, renameAnimButton, container });\r\n\t\t}\r\n\r\n\t\tpublic void AssignTexture(Image image) {\r\n\t\t\t(Controls[Controls.Count - 1] as FramesContainer).AssignTexture(image);\r\n\t\t}\r\n\r\n\t\tprivate Button YieldButton(String text, int left, int width) {\r\n\t\t\treturn new Button() {\r\n\t\t\t\tHeight = CONTROLS_HEIGHT,\r\n\t\t\t\tBackColor = Color.FromArgb(255, 240, 240, 240),\r\n\t\t\t\tWidth = width, Left = left, Text = text, Top = -1,\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tpublic void RenameSequenceKey(String newKey) {\r\n\t\t\tSequenceKey = newKey;\r\n\t\t}\r\n\r\n\t\tpublic static Size GetSize() {\r\n\t\t\treturn new Size(CONTAINER_WIDTH - SysInfo.VerticalScrollBarWidth - (2 * HORIZONTAL_OFFSET), CONTAINER_HEIGHT);\r\n\t\t}\r\n\r\n\t\tTextBox PathDetailsTextBox;\r\n\t\tFramesContainer container;\r\n\t\tpublic Button deleteSequenceButton, addFrameButton, renameAnimButton;\r\n\r\n\t\tpublic String SequenceKey { get { return PathDetailsTextBox.Text; } private set { PathDetailsTextBox.Text = value; } }\r\n\r\n\t\tpublic const int CONTAINER_WIDTH = 1080, CONTAINER_HEIGHT = 150;\r\n\t\tpublic const int HORIZONTAL_OFFSET = 35, BUTTON_HORIZONTAL_OFFSET = 15;\r\n\t\tpublic const int CONTROLS_HEIGHT = 26;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7014759182929993, "alphanum_fraction": 0.7052353024482727, "avg_line_length": 32.87378692626953, "blob_id": "d6c3c677b96f2c449c1cb451d8fd2ea933967c30", "content_id": "56f93059d8f261c7960f495b2842143da9bd33e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7184, "license_type": "no_license", "max_line_length": 132, "num_lines": 206, "path": "/HollowAether/Lib/InputOutput/MapZone/Map.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nusing Converter = HollowAether.Lib.InputOutput.Parsers.Converters;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\n\r\nnamespace HollowAether.Lib.MapZone {\r\n\tpublic class Map {\r\n\t\tpublic struct ZoneArgs {\r\n\t\t\tpublic ZoneArgs(String _path, bool _visible) {\r\n\t\t\t\tpath = _path; visible = _visible;\r\n\t\t\t}\r\n\r\n\t\t\tpublic Zone ToInstance(bool initNow) {\r\n\t\t\t\treturn new Zone(this, initNow);\r\n\t\t\t}\r\n\r\n\t\t\tpublic bool visible;\r\n\t\t\tpublic String path;\r\n\t\t}\r\n\r\n\t\tpublic Map(String fpath = null) {\r\n\t\t\tFilePath = (String.IsNullOrWhiteSpace(fpath)) ? GV.FileIO.DefaultMapPath : fpath;\r\n\t\t\t\r\n\t\t\tif (!IOMan.FileExists(FilePath)) throw new MapNotFoundException(FilePath);\r\n\t\t}\r\n\r\n\t\tpublic void Initialize(bool buildCurrentZone = true) {\r\n\t\t\tInputOutput.Parsers.MapParser.Parse(this);\r\n\r\n\t\t\tstartZoneIndex = _currentZoneIndex; // Store start index for ToFileMethod\r\n\r\n\t\t\tif (buildCurrentZone) {\r\n\t\t\t\tif (Program.argZoneIndex.HasValue) _currentZoneIndex = Program.argZoneIndex.Value;\r\n\t\t\t\t// If index passed via command line has value then set the default fpath to it\r\n\r\n\t\t\t\tif (!_currentZoneIndex.HasValue)\r\n\t\t\t\t\tthrow new HollowAetherException($\"No Start Zone Set or Assigned\");\r\n\t\t\t\telse if (!MapZoneCollection.ContainsKey(_currentZoneIndex.Value))\r\n\t\t\t\t\tthrow new HollowAetherException($\"{_currentZoneIndex.Value} Not in Map\");\r\n\r\n\t\t\t\tcurrentZone = new Zone(this[_currentZoneIndex.Value], true); // Current Zone\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic String ToFileContents() {\r\n\t\t\tStringBuilder builder = new StringBuilder($\"{Map.MAP_FILE_HEADER}\\n\\n\");\r\n\r\n\t\t\tbuilder.AppendLine($\"[StartZone{Converter.ValueToString(typeof(Vector2), startZoneIndex)}]\\n\");\r\n\r\n\t\t\tforeach (Asset asset in GV.MapZone.globalAssets.Values) {\r\n\t\t\t\tif (asset is FlagAsset) {\r\n\t\t\t\t\tbool value = (asset.asset as Flag).Value; // Get default value\r\n\t\t\t\t\tbuilder.AppendLine($\"[DefineFlag({asset.assetID}={value})]\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tbuilder.AppendLine(); // Add line break after flag & start zone definition\r\n\r\n\t\t\tforeach (var MZCKeyValues in MapZoneCollection) {\r\n\t\t\t\tString visibility = MZCKeyValues.Value.visible ? \"V\" : \"H\"; // Is visible\r\n\t\t\t\tString pos = Converter.ValueToString(typeof(Vector2), MZCKeyValues.Key);\r\n\t\t\t\tbuilder.AppendLine($\"{visibility}-{pos} \\\\{MZCKeyValues.Value.path}\");\r\n\t\t\t}\r\n\r\n\t\t\treturn builder.ToString(); // Convert to string and return builder\r\n\t\t}\r\n\r\n\t\tpublic void SetStartZone(Vector2 arg) { startZoneIndex = arg; }\r\n\r\n\t\tpublic void SetCurrentZone(Vector2 newIndex, bool skipCheck = false, bool build = true) {\r\n\t\t\tif (!skipCheck && !MapZoneCollection.ContainsKey(newIndex)) // Doesn't Exist\r\n\t\t\t\tthrow new ZoneWithGivenMapIndexNotFoundException(newIndex);\r\n\r\n\t\t\t_currentZoneIndex = newIndex; // Set new index to argument index \r\n\r\n\t\t\tif (build) {\r\n\t\t\t\tCurrentZone.RemoveZoneFromSpriteBatch(); // Remove all objects from game\r\n\t\t\t\tcurrentZone = new Zone(this[_currentZoneIndex.Value], true); // Current Zone\r\n\t\t\t\tCurrentZone.Initialize(); // Initialize zone contents by reading zone file\r\n\t\t\t\tCurrentZone.AddZoneToSpriteBatch(); // Add objects from new zone to game\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic Vector2? ZoneExistsAdjacentTo(Vector2 index) {\r\n\t\t\tforeach (bool xOffset in new bool[] { true, false }) {\r\n\t\t\t\tforeach (int N in new int[] { +1, -1 }) {\r\n\t\t\t\t\tVector2 pos = new Vector2() {\r\n\t\t\t\t\t\tX = ( xOffset) ? index.X + N : index.X,\r\n\t\t\t\t\t\tY = (!xOffset) ? index.Y + N : index.Y,\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\tif (ContainsZone(pos)) return pos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn null; // Null means not index was found\r\n\t\t}\r\n\r\n\t\tpublic static bool CreateEmptyMap(String fpath) {\r\n\t\t\ttry { // Used with level editor, has no real purpose in actual game logic\r\n\t\t\t\tIOMan.WriteEncryptedFile(fpath, $\"{MAP_FILE_HEADER} # Header\\n\", GV.Encryption.oneTimePad);\r\n\t\t\t} catch { return false; }\r\n\r\n\t\t\treturn true; // Succesfully made \r\n\t\t}\r\n\r\n\t\tpublic bool ContainsZone(String filePath) {\r\n\t\t\tforeach (ZoneArgs args in MapZoneCollection.Values) {\r\n\t\t\t\tif (args.path == FilePath) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic bool ContainsZone(Vector2 position) {\r\n\t\t\treturn MapZoneCollection.ContainsKey(position);\r\n\t\t}\r\n\r\n\t\tpublic void AddZone(Vector2 key, String zonePath, bool zoneVisible) {\r\n\t\t\tMapZoneCollection.Add(key, new ZoneArgs(zonePath, zoneVisible));\r\n\t\t}\r\n\r\n\t\tpublic Vector2 GetZoneIndexFromFilePath(String filePath) {\r\n\t\t\tforeach (KeyValuePair<Vector2, ZoneArgs> KVP in MapZoneCollection) {\r\n\t\t\t\tif (KVP.Value.path == filePath) return KVP.Key;\r\n\t\t\t}\r\n\r\n\t\t\tthrow new HollowAetherException();\r\n\t\t}\r\n\r\n\t\tpublic Dictionary<Vector2, ZoneArgs>.Enumerator EnumerateCollection() {\r\n\t\t\treturn MapZoneCollection.GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic ZoneArgs GetZoneArgsFromVector(Vector2 position) {\r\n\t\t\treturn MapZoneCollection[position];\r\n\t\t}\r\n\r\n\t\tpublic ZoneArgs GetZoneArgsFromFilePath(Vector2 position) {\r\n\t\t\treturn MapZoneCollection[position];\r\n\t\t}\r\n\r\n\t\tpublic void DeleteZone(Vector2 zoneIndex) {\r\n\t\t\tMapZoneCollection.Remove(zoneIndex);\r\n\t\t}\r\n\r\n\t\tpublic ZoneArgs this[Vector2 position] {\r\n\t\t\tget { return MapZoneCollection[position]; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Update current zone parameter values</summary>\r\n\t\tpublic void Update() { CurrentZone.Update(); }\r\n\r\n\t\tpublic static readonly String MAP_FILE_HEADER = \"MAP\";\r\n\r\n\t\t/// <summary>Current zone in map</summary>\r\n\t\tprivate Vector2? _currentZoneIndex = Vector2.Zero, startZoneIndex;\r\n\r\n\t\tpublic Vector2 GetStartZoneIndexOrEmpty() {\r\n\t\t\treturn startZoneIndex.HasValue ? startZoneIndex.Value : Vector2.Zero;\r\n\t\t}\r\n\r\n\t\t/// <summary>Dictionary of zones contained within map</summary>\r\n\t\tprivate Dictionary<Vector2, ZoneArgs> MapZoneCollection = new Dictionary<Vector2, ZoneArgs>();\r\n\r\n\t\t/// <summary>File path for given map</summary>\r\n\t\tpublic String FilePath { get; private set; }\r\n\r\n\t\t/// <summary>Number of zones in map</summary>\r\n\t\tpublic int Count { get { return MapZoneCollection.Count; } }\r\n\r\n\t\t/// <summary>All indexes of all known zones contained within map as key collection</summary>\r\n\t\tpublic Dictionary<Vector2, ZoneArgs>.KeyCollection ZoneIndexes { get { return MapZoneCollection.Keys; } }\r\n\r\n\t\t/// <summary>Index of current zone accesible within map which is regularly being update</summary>\r\n\t\tpublic Vector2 Index {\r\n\t\t\tget { if (_currentZoneIndex.HasValue) return _currentZoneIndex.Value; else throw new HollowAetherException($\"Index Not Set\"); }\r\n\t\t\tset { SetCurrentZone(value); } // Stores current zone index & creates new zone instance to replace existing current zone instance\r\n\t\t}\r\n\r\n\t\tprivate Zone currentZone;\r\n\r\n\t\t/// <summary>Instance of zone class representing current zone within map</summary>\r\n\t\tpublic Zone CurrentZone { get { return currentZone; } private set { currentZone = value; } }\r\n\t}\r\n}" }, { "alpha_fraction": 0.7047200798988342, "alphanum_fraction": 0.7153311371803284, "avg_line_length": 37.0428581237793, "blob_id": "f2fdf4d0b4e4ba4369cceb4c4e5fe9c6b4fc68f2", "content_id": "c25d453bfa27765891ce0aff21b60c2e9cd185cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2735, "license_type": "no_license", "max_line_length": 183, "num_lines": 70, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/MultichoiceButton.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic class MultichoiceButton : Button {\r\n\t\tpublic MultichoiceButton(Vector2 position, int finHorizontalOffset=32, int width=SPRITE_WIDTH, int height = SPRITE_HEIGHT, String fontName=DEFAULT_FONT_ID, params String[] options) \r\n\t\t\t: base(position, width, height) {\r\n\t\t\tthis.options.AddRange(options); // Store passed options\r\n\t\t\tfontID = fontName;\r\n\t\t\tthis.finHorizontalOffset = finHorizontalOffset;\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw();\r\n\r\n\t\t\tVector2 size = font.MeasureString(\"<\"); // Should be same for > as well\r\n\t\t\tfloat finVerticalPos = Position.Y + ((Height - size.Y) / 2); // Y Position\r\n\r\n\t\t\tDrawString(\"<\", new Vector2(Position.X + finHorizontalOffset,\t\t\t\t finVerticalPos));\r\n\t\t\tDrawString(\">\", new Vector2(Position.X + Width - size.X - finHorizontalOffset, finVerticalPos));\r\n\r\n\t\t\tstring outputString = (selectedOptionIndex != -1) ? options[selectedOptionIndex] : \"Null\";\r\n\r\n\t\t\tDrawString(outputString, Position + ((new Vector2(Width, Height) - font.MeasureString(outputString)) / 2));\r\n\t\t}\r\n\r\n\t\tprivate void DrawString(String text, Vector2 position) {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(font, text, position, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, Layer + 0.001f);\r\n\t\t}\r\n\r\n\t\tpublic void SetSelectedOption(int index) {\r\n\t\t\tif (index > options.Count - 1) throw new HollowAetherException($\"Button Select Index Out Of Range\"); else {\r\n\t\t\t\tselectedOptionIndex = index; Changed(this); // Store new index, then trigger event handler\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void SelectNextOption() {\r\n\t\t\tif (options.Count > 1) SetSelectedOption(GV.BasicMath.Clamp(selectedOptionIndex + 1, 0, options.Count - 1));\r\n\t\t}\r\n\r\n\t\tpublic void SelectPreviousOption() {\r\n\t\t\tif (options.Count > 1) SetSelectedOption(GV.BasicMath.Clamp(selectedOptionIndex - 1, 0, options.Count - 1));\r\n\t\t}\r\n\r\n\t\tpublic event Action<MultichoiceButton> Changed = (self) => { };\r\n\r\n\t\tpublic string ActiveSelection { get { return (selectedOptionIndex == -1) ? null : options[selectedOptionIndex]; } }\r\n\r\n\t\tprivate int selectedOptionIndex = -1;\r\n\t\tpublic List<String> options = new List<String>();\r\n\t\tpublic const String DEFAULT_FONT_ID = \"homescreen\";\r\n\t\tprivate SpriteFont font { get { return GV.MonoGameImplement.fonts[fontID]; } }\r\n\t\tprivate String fontID;\r\n\t\tprivate int finHorizontalOffset;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7113853693008423, "alphanum_fraction": 0.7161624431610107, "avg_line_length": 36.06060791015625, "blob_id": "16d465316f63639221b4cc5308fb0d2090994d85", "content_id": "7636318399dfb0d02851de1748b40ac65779f832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2514, "license_type": "no_license", "max_line_length": 99, "num_lines": 66, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/ButtonList.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic class ButtonList : IEnumerable<Button> {\r\n\t\tpublic ButtonList(int markActive=0, int buttonSpan=3, params Button[] args) {\r\n\t\t\tif (args.Length == 0) throw new HollowAetherException($\"Button List needs at least one button\");\r\n\r\n\t\t\tbuttons = new List<Button>(buttonSpan); // General length 3\r\n\t\t\tAddButtons(args); // Store all buttons within list locally\r\n\t\t\tactiveButtonIndex = markActive; // Store current active index\r\n\t\t\tbuttons[activeButtonIndex].Active = true; // Set to true\r\n\t\t}\r\n\r\n\t\tpublic IEnumerator<Button> GetEnumerator() { return buttons.GetEnumerator(); }\r\n\r\n\t\tIEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }\r\n\r\n\t\tpublic void AddButtons(params Button[] args) { buttons.AddRange(args); }\r\n\r\n\t\tpublic void RemoveButton(Button button) { buttons.Remove(button); }\r\n\r\n\t\tpublic void MoveToNextButton() {\r\n\t\t\tbuttons[activeButtonIndex].Toggle(); // De activate chosen button by changing animation\r\n\t\t\tactiveButtonIndex = (activeButtonIndex + 1 >= buttons.Count) ? 0 : activeButtonIndex + 1;\r\n\t\t\tbuttons[activeButtonIndex].Toggle(); // Activate newly selected button by changing animation\r\n\t\t}\r\n\r\n\t\tpublic void MoveToPreviousButton() {\r\n\t\t\tbuttons[activeButtonIndex].Toggle(); // De activate chosen button by changing animation\r\n\t\t\tactiveButtonIndex = (activeButtonIndex - 1 < 0) ? buttons.Count - 1 : activeButtonIndex - 1;\r\n\t\t\tbuttons[activeButtonIndex].Toggle(); // Activate newly selected button by changing animation\r\n\t\t}\r\n\r\n\t\tpublic void Update(bool updateAnimation) {\r\n\t\t\tforeach (Button button in buttons) button.Update(updateAnimation);\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tforeach (Button button in buttons) button.Draw();\r\n\t\t}\r\n\r\n\t\tpublic Button Last() { return buttons[buttons.Count - 1]; }\r\n\r\n\t\tpublic Button this[int X] { get { return buttons[X]; } }\r\n\r\n\t\tpublic int Length { get { return buttons.Count; } }\r\n\r\n\t\tpublic int ActiveButtonIndex { get { return activeButtonIndex; } set {\r\n\t\t\tif (activeButtonIndex >= buttons.Count)\r\n\t\t\t\tthrow new HollowAetherException(\"Button Count Out Of Range\");\r\n\r\n\t\t\twhile (activeButtonIndex != value) MoveToNextButton();\r\n\t\t} }\r\n\r\n\t\tpublic Button ActiveButton { get { return buttons[activeButtonIndex]; } }\r\n\r\n\t\tprivate int activeButtonIndex;\r\n\t\tprivate List<Button> buttons = new List<Button>();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7038074135780334, "alphanum_fraction": 0.7094064950942993, "avg_line_length": 36, "blob_id": "b8aa0b6364be52e08a2e32253a4e2492d8e6f2db", "content_id": "6781b732aa67231f38e422f62188ad2fd3a920d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3574, "license_type": "no_license", "max_line_length": 127, "num_lines": 94, "path": "/HollowAether/Lib/Global/GlobalVars/BasicMath.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class BasicMath {\r\n\t\t\tpublic static T Clamp<T>(T value, T minimum, T maximum) where T : IComparable<T> {\r\n\t\t\t\tif (value.CompareTo(minimum) < 0) return minimum; else if (value.CompareTo(maximum) > 0) return maximum; else return value;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static int RoundToNearestMultiple(int value, int factor, bool ignoreZero = true) {\r\n\t\t\t\tint factorCount = (int)Math.Round(value / (double)factor, MidpointRounding.ToEven);\r\n\t\t\t\treturn (ignoreZero && factorCount == 0) ? (factorCount + 1) * factor : factorCount * factor;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static int RoundDownToNearestMultiple(int value, int factor, bool ignoreZero = true) {\r\n\t\t\t\tint factorCount = (int)Math.Floor(value / (double)factor); // Number of times factors appear\r\n\t\t\t\treturn (ignoreZero && factorCount == 0) ? (factorCount + 1) * factor : factorCount * factor;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static int RoundDownToNearestMultiple(float value, float factor, bool ignoreZero = true) {\r\n\t\t\t\tint factorCount = (int)Math.Floor(value / factor); // Number of times factors appear\r\n\t\t\t\treturn (int)Math.Round((ignoreZero && factorCount == 0) ? (factorCount + 1) * factor : factorCount * factor);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static System.Drawing.Rectangle ScaleRectangle(System.Drawing.Rectangle rect, float XScale, float YScale) {\r\n\t\t\t\tint XPos = (int)(rect.X * XScale), YPos = (int)(rect.Y * YScale);\r\n\t\t\t\tint width = (int)(rect.Width * XScale), height = (int)(rect.Height * YScale);\r\n\t\t\t\treturn new System.Drawing.Rectangle(XPos, YPos, width, height);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static System.Drawing.Rectangle ScaleRectangle(System.Drawing.Rectangle rect, float scale) {\r\n\t\t\t\treturn ScaleRectangle(rect, scale, scale);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static System.Drawing.Rectangle ScaleRectangle(System.Drawing.Rectangle rect, int XScale, int YScale) {\r\n\t\t\t\treturn ScaleRectangle(rect, (float)XScale, (float)YScale);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static System.Drawing.Rectangle ScaleRectangle(System.Drawing.Rectangle rect, int scale) {\r\n\t\t\t\treturn ScaleRectangle(rect, (float)scale);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static float DegreesToRadians(float degrees) {\r\n\t\t\t\treturn RadDegRatio * degrees;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static float RadiansToDegrees(float radians) {\r\n\t\t\t\treturn radians * DegRadRatio;\r\n\t\t\t}\r\n\r\n\t\t\t/*public static double NormaliseRadianAngle(float theta) {\r\n\t\t\t\treturn theta - (2 * Math.PI) * Math.Floor((theta + Math.PI) / (2 * Math.PI));\r\n\t\t\t}*/\r\n\r\n\t\t\tpublic static double NormaliseRadianAngle(double theta) {\r\n\t\t\t\twhile (theta < 0) theta += 2 * Math.PI;\r\n\r\n\t\t\t\treturn theta;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static double RecursiveNormaliseRadianAngle(double theta) {\r\n\t\t\t\treturn (theta > 0) ? theta : RecursiveNormaliseRadianAngle(theta + (2 * Math.PI));\r\n\t\t\t}\r\n\r\n\t\t\tprivate static readonly float RadDegRatio = (float)(Math.PI / 180), DegRadRatio = (float)(180 / Math.PI);\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7137789726257324, "alphanum_fraction": 0.7155525088310242, "avg_line_length": 38.05464553833008, "blob_id": "0771b8b2fcef9667bf0e80cecacb087aabdce9ea", "content_id": "bc54f1ed6d9f3606e5820118019eb13f06e93fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7332, "license_type": "no_license", "max_line_length": 133, "num_lines": 183, "path": "/HollowAether/Lib/Forms/LevelEditor/Script/ScriptEditor.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing System.Windows.Forms.Integration;\r\nusing System.IO;\r\nusing ICSharpCode.AvalonEdit;\r\nusing ICSharpCode.AvalonEdit.Highlighting;\r\nusing ICSharpCode.AvalonEdit.Highlighting.Xshd;\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.MapZone;\r\nusing System.Windows.Controls;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class ScriptEditor : Form {\r\n\t\tpublic ScriptEditor(String fpath, bool? _isZoneFile=null, bool readNow = true) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\tif (!InputOutputManager.FileExists(fpath)) {\r\n\t\t\t\tMessageBox.Show(\r\n\t\t\t\t\t$\"Could Not Find File '{fpath}'\", \r\n\t\t\t\t\t\"File Doesn't Exist Error\",\r\n\t\t\t\t\tMessageBoxButtons.OK, \r\n\t\t\t\t\tMessageBoxIcon.Error\r\n\t\t\t\t);\r\n\r\n\t\t\t\tDispose(true);\r\n\t\t\t}\r\n\r\n\t\t\tfilePath = fpath; width = Width; height = Height;\r\n\r\n\t\t\t//initialFileContents = InputOutputManager.ReadEncryptedFile(fpath, GlobalVars.oneTimePad);\r\n\t\t\tif (readNow) ReadFile(InputOutputManager.ReadEncryptedFile(fpath, GlobalVars.Encryption.oneTimePad), _isZoneFile);\r\n\t\t\t//if (_isZoneFile.HasValue) isZoneFile = _isZoneFile.Value; else DetermineFileType();\r\n\t\t}\r\n\r\n\t\tpublic static ScriptEditor EditorFromFileContents(String contents, String fpath, bool? _isZoneFile = null) {\r\n\t\t\tScriptEditor editor = new ScriptEditor(fpath, readNow: false); // Create new zone editor but don't read file\r\n\t\t\teditor.ReadFile(contents, _isZoneFile); return editor; // Pass contents as file contents then return editor\r\n\t\t}\r\n\r\n\t\tpublic void ReadFile(String fContents, bool? _isZoneFile) {\r\n\t\t\tinitialFileContents = fContents; // Store file contents passed via arg\r\n\t\t\tif (_isZoneFile.HasValue) isZoneFile = _isZoneFile.Value; else DetermineFileType();\r\n\t\t}\r\n\r\n\t\tpublic void ChangeFileContents(String text) {\r\n\t\t\t((Controls[indexOfTextEditorControl] as ElementHost).Child as TextEditor).Text = text;\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds AvalonEditor and set's syntax for desired type</summary>\r\n\t\tprivate void ScriptEditor_Load(object sender, EventArgs e) {\r\n\t\t\tTextEditor editor = new TextEditor() {HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled};\r\n\r\n\t\t\tbool syntaxSet = (isZoneFile) ? BuildZoneSyntaxHighlighting(ref editor) : BuildMapSyntaxHighlighting(ref editor);\r\n\r\n\t\t\t#region MessageBox\r\n\t\t\tif (!syntaxSet)\r\n\t\t\t\tMessageBox.Show(\"Couldn't Find Appropriate Syntax File\", \r\n\t\t\t\t\t\"Syntax Find Error\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\r\n\t\t\t#endregion\r\n\r\n\t\t\tindexOfTextEditorControl = Controls.Count;\r\n\r\n\t\t\teditor.FontFamily = new System.Windows.Media.FontFamily(\"Courier New\");\r\n\t\t\teditor.FontSize = 10;\r\n\r\n\t\t\tthis.Controls.Add(new ElementHost() {\r\n\t\t\t\tSize = new Size(Width - 18 - 5, Height - 60), Child = editor,\r\n\t\t\t\tLocation = new Point(5, menuStrip.Height + Padding.Top)\r\n\t\t\t});\r\n\r\n\t\t\teditor.Text = initialFileContents; // store contents of file\r\n\t\t}\r\n\r\n\t\t/// <summary>Thrown when form dimensions have changed</summary>\r\n\t\tprivate void ScriptEditor_SizeChanged(object sender, EventArgs e) {\r\n\t\t\tControls[indexOfTextEditorControl].Size = GetTextEditorSize();\r\n\t\t}\r\n\r\n\t\tprivate void ScriptEditor_KeyDown(object sender, KeyEventArgs e) {\r\n\t\t\tif (e.KeyCode == Keys.Down) {\r\n\t\t\t\tConsole.WriteLine(\"Push Down\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Determines filetype of file when not expressly given</summary>\r\n\t\tprivate void DetermineFileType() {\r\n\t\t\t/*if (Map.CheckMapHeader(initialFileContents)) { isZoneFile = false; } \r\n\t\t\telse if (Map.CheckMapHeader(initialFileContents)) { isZoneFile = true; } \r\n\t\t\telse {\r\n\t\t\t\t#region ShowError\r\n\t\t\t\tMessageBox.Show($\"File '{filePath}' Isn't Of Type Map Or Header\", \"File Read Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t\t\tDispose(true);\r\n\t\t\t\t#endregion\r\n\t\t\t}*/\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds editor syntax coloring for map files</summary>\r\n\t\t/// <param name=\"editor\">TextEditor control</param>\r\n\t\t/// <returns>Boolean indicating whether syntax was set</returns>\r\n\t\tprivate bool BuildMapSyntaxHighlighting(ref TextEditor editor) {\r\n\t\t\tif (!InputOutputManager.FileExists(mapSyntaxFile)) return false;\r\n\r\n\t\t\ttry {\r\n\t\t\t\tusing (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(mapSyntaxFile)) {\r\n\t\t\t\t\teditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);\r\n\t\t\t\t}\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"[^ \\n\\r]+\\\\[^ \\n\\r]+\"), //(@\"\\w:\\\\[^\\r\\n]+\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"String\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"([Tt]rue)|([Ff]alse)\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"Boolean\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"([Xx|Yy]:\\d+)\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"Vector\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"([Ss]tart[Zz]one)|([Dd]efine[Ff]lag)\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"Command\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t} catch { return false; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds editor syntax coloring for zone files</summary>\r\n\t\t/// <param name=\"editor\">TextEditor control</param>\r\n\t\t/// <returns>Boolean indicating whether syntax was set</returns>\r\n\t\tprivate bool BuildZoneSyntaxHighlighting(ref TextEditor editor) {\r\n\t\t\tif (!InputOutputManager.FileExists(zoneSyntaxFile)) return false;\r\n\r\n\t\t\ttry {\r\n\t\t\t\tusing (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(zoneSyntaxFile)) {\r\n\t\t\t\t\teditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);\r\n\t\t\t\t}\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"\\[[^\\n\\r]+\\]\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"ID\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\teditor.SyntaxHighlighting.MainRuleSet.Rules.Add(new HighlightingRule() {\r\n\t\t\t\t\tRegex = new System.Text.RegularExpressions.Regex(@\"\\([^\\n\\r]+\\)\"),\r\n\t\t\t\t\tColor = editor.SyntaxHighlighting.GetNamedColor(\"Attribute\")\r\n\t\t\t\t});\r\n\r\n\t\t\t\teditor.TextArea.TextView.Redraw();\r\n\t\t\t\treturn true;\r\n\t\t\t} catch { return false; }\r\n\t\t}\r\n\r\n\t\t/// <summary>Get's new editor size after form resize</summary>\r\n\t\tprivate Size GetTextEditorSize() {\r\n\t\t\treturn new Size(Width - 18 - 5, Height - 60 - menuStrip.Height - Padding.Top);\r\n\t\t}\r\n\r\n\t\tpublic String GetEditorTextContents() {\r\n\t\t\treturn ((Controls[indexOfTextEditorControl] as ElementHost).Child as TextEditor).Text;\r\n\t\t}\r\n\r\n\t\tprivate static String mapSyntaxFile = InputOutput.InputOutputManager.Join(Editor.levelEditorBasePath, \"MapSyntax.XSHD\");\r\n\t\tprivate static String zoneSyntaxFile = InputOutput.InputOutputManager.Join(Editor.levelEditorBasePath, \"ZoneSyntax.XSHD\");\r\n\t\tprivate int width, height, indexOfTextEditorControl;\r\n\r\n\t\tpublic bool isZoneFile;\r\n\t\tprivate String initialFileContents, filePath;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7375215291976929, "alphanum_fraction": 0.7495697140693665, "avg_line_length": 32.17647171020508, "blob_id": "274ff9ff207f98d924736c822cedc056816e0475", "content_id": "79560b226c86e2658fb54907050b58f885358748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 122, "num_lines": 34, "path": "/HollowAether/Lib/GAssets/Effects/DashOverlay.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.FX {\r\n\tpublic class DashOverlay : VolatileSprite {\r\n\t\tpublic DashOverlay(Vector2 position, Action UponDeletion=null) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT) {\r\n\t\t\tInitializeVolatility(VolatilityType.Other, new ImplementVolatility((IMGO) =>\r\n\t\t\t\t// Delete sprite when animation for dash sprite has been completed.\r\n\t\t\t\tAnimation.CurrentSequence.FrameIndex + 1 >= Animation.CurrentSequence.Length\r\n\t\t\t));\r\n\r\n\t\t\tInitialize(\"fx\\\\dashoverlay\"); // Initialise with overlay texture\r\n\r\n\t\t\tif (UponDeletion != null) VolatilityManager.Deleting += UponDeletion;\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(32, 32,0, 0, 8, runCount: 2);\r\n\t\t}\r\n\r\n\t\tprivate const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7040643692016602, "alphanum_fraction": 0.7130962610244751, "avg_line_length": 39.19767379760742, "blob_id": "d2617068683dba8a04844e02e931c3cf555236ba", "content_id": "f54aacebaf79b34fd6dcc7bd037f32d32866388c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7088, "license_type": "no_license", "max_line_length": 129, "num_lines": 172, "path": "/HollowAether/Lib/Global/GameWindow/SaveLoad.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\nusing WinF = System.Windows.Forms;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing GPBIWT = HollowAether.Lib.GAssets.HUD.GamePadButtonIconWithText;\r\nusing GPB = HollowAether.Lib.GAssets.HUD.GamePadButtonIcon.GamePadButton;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tstatic class SaveLoad {\r\n\t\tstatic SaveLoad() { Initialize(); }\r\n\r\n\t\tstatic void Initialize() {\r\n\t\t\tint windowWidth = GV.Variables.windowWidth, windowHeight = GV.Variables.windowHeight;\r\n\r\n\t\t\t// buttons = new SaveButton[InputOutput.SaveManager.SAVE_SLOTS]; // Number of save slots\r\n\t\t\t// int buttonWidth = 1400, buttonHeight = 200, buttonYOffset = (int)(buttonHeight * 1.15f);\r\n\t\t\tint buttonWidth = windowWidth - 100, buttonHeight = windowHeight * 2/9, buttonYOffset = (int)(buttonHeight * 1.15f);\r\n\r\n\t\t\t#region Build Save Buttons\r\n\t\t\tButton[] _buttons = new Button[InputOutput.SaveManager.SAVE_SLOTS+1]; // Local button store\r\n\t\t\tVector2 initialPosition = new Vector2((windowWidth - buttonWidth) / 2, windowHeight * 2 / 45);\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, InputOutput.SaveManager.SAVE_SLOTS)) {\r\n\t\t\t\t_buttons[X] = new SaveButton(initialPosition, X, buttonWidth, buttonHeight) { Layer = 0.4f };\r\n\r\n\t\t\t\t_buttons[X].Click += SaveLoad_Click;\r\n\r\n\t\t\t\tinitialPosition.Y += buttonYOffset; // Push to leave space for new button sprite\r\n\t\t\t}\r\n\r\n\t\t\tint backButtonWidth = (int)(Button.SPRITE_WIDTH*3.5f), backButtonHeight = (int)(Button.SPRITE_HEIGHT*3.5f);\r\n\t\t\tVector2 backButtonPos = new Vector2((windowWidth - backButtonWidth) / 2, initialPosition.Y);\r\n\r\n\t\t\t#region Build Return To Homestate Position\r\n\t\t\t_buttons[_buttons.Length - 1] = new TextButton(backButtonPos, \"Back\", backButtonWidth, backButtonHeight) { Layer = 0.4f };\r\n\t\t\t_buttons.Last().Click += (self) => { ReturnToHomeState(); };\r\n\t\t\t#endregion\r\n\r\n\t\t\tbuttons = new ButtonList(0, InputOutput.SaveManager.SAVE_SLOTS + 1, _buttons); // Create buttons list\r\n\t\t\t#endregion\r\n\r\n\t\t\tVector2 generalVerticalOffset = new Vector2(0, GPBIWT.SPRITE_HEIGHT + 8f); // Extended offset = 8 pixels\r\n\r\n\t\t\tVector2 loadButtonPosition = new Vector2(windowWidth - (2 * GPBIWT.SPRITE_WIDTH), windowHeight - generalVerticalOffset.Y);\r\n\t\t\tVector2 backButtonPosition = loadButtonPosition - new Vector2(GPBIWT.SPRITE_WIDTH, generalVerticalOffset.Y);\r\n\t\t\tVector2 deleteButtonPosition = backButtonPosition - new Vector2(-GPBIWT.SPRITE_WIDTH, generalVerticalOffset.Y);\r\n\r\n\t\t\tdisplayedButtons = new GPBIWT[] {\r\n\t\t\t\tnew GPBIWT(deleteButtonPosition, GPB.Y, \"Delete\", GPBIWT.TextPosition.BeforeButton) { Layer = 0.9f },\r\n\t\t\t\tnew GPBIWT(backButtonPosition, GPB.B, \"Back\", GPBIWT.TextPosition.BeforeButton) { Layer = 0.9f },\r\n\t\t\t\tnew GPBIWT(loadButtonPosition, GPB.A, \"Load\", GPBIWT.TextPosition.BeforeButton) { Layer = 0.9f }\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate static void SaveLoad_Click(Button self) {\r\n\t\t\tint index = (self as SaveButton).SaveIndex; // To Index\r\n\r\n\t\t\tif (!InputOutput.SaveManager.SaveExists(index))\r\n\t\t\t\tInputOutput.SaveManager.CreateBlankSave(index);\r\n\r\n\t\t\tGV.MonoGameImplement.gameState = GameState.GameRunning;\r\n\r\n\t\t\tGV.MonoGameImplement.saveIndex = index; // Set index\r\n\t\t\tGameRunning.LoadSave(index); // Load desired save file\r\n\t\t}\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false);\r\n\r\n\t\t\tbuttons.Draw(); // Draw save and back buttons\r\n\r\n\t\t\tforeach (GPBIWT button in displayedButtons)\r\n\t\t\t\tbutton.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() { Initialize(); }\r\n\t\t\r\n\t\tpublic static void FullScreenReset(bool isFullScreen) {\r\n\t\t\tif (GV.MonoGameImplement.gameState == GameState.SaveLoad)\r\n\t\t\t\tReset(); // If Current Game State, Then Reset\r\n\t\t}\r\n\r\n\t\tpublic static void Update() {\r\n\t\t\tforeach (Button button in buttons)\t\t button.Update(false);\r\n\t\t\tforeach (GPBIWT button in displayedButtons) button.Update(false);\r\n\t\t\t\r\n\t\t\tGV.PeripheralIO.ControlState controlState = GV.PeripheralIO.currentControlState;\r\n\r\n\t\t\tbool altPressed = GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.LeftAlt, Keys.RightAlt); // Whether alt key is pressed\r\n\t\t\tbool enter = GetEnterInput(), goBack = GetReturnInput(), deleteSave = GetDeleteSaveInput(); // Determines What To Do Below\r\n\t\t\tbool moveForward = controlState.Down || controlState.Right, moveBackward = controlState.Up || controlState.Left; // Buttons\r\n\t\t\tbool nothingPressed = !(altPressed || enter || goBack || deleteSave || moveForward || moveBackward); // If no input detected\r\n\r\n\t\t\tif (WaitForInputToBeRemoved) {\r\n\t\t\t\tif (nothingPressed) WaitForInputToBeRemoved = false;\r\n\t\t\t\treturn; // Input has been removed || Is still in affect\r\n\t\t\t}\r\n\r\n\t\t\tif (inputTimeout > 0) {\r\n\t\t\t\tif (nothingPressed) inputTimeout = 0; // Remove input time out, user can input again\r\n\t\t\t\telse inputTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t} else if (!nothingPressed) {\r\n\t\t\t\tif (goBack)\t ReturnToHomeState();\r\n\t\t\t\telse if\t(moveForward) buttons.MoveToNextButton();\r\n\t\t\t\telse if (moveBackward) buttons.MoveToPreviousButton();\r\n\t\t\t\telse if (enter)\t\t buttons.ActiveButton.InvokeClick();\r\n\t\t\t\telse if (deleteSave) DeleteSave(buttons.ActiveButtonIndex);\r\n\r\n\t\t\t\tinputTimeout = 150; // Dont accept input for given value in milleseconds\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region GetButtonStates\r\n\t\tprivate static bool GetEnterInput() {\r\n\t\t\treturn (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.Buttons.A == ButtonState.Pressed)\r\n\t\t\t\t|| GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Enter);\r\n\t\t}\r\n\r\n\t\tprivate static bool GetReturnInput() {\r\n\t\t\treturn (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.Buttons.B == ButtonState.Pressed)\r\n\t\t\t\t|| GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Back, Keys.B);\r\n\t\t}\r\n\r\n\t\tprivate static bool GetDeleteSaveInput() {\r\n\t\t\treturn (GV.PeripheralIO.gamePadConnected && GV.PeripheralIO.currentGPState.Buttons.Y == ButtonState.Pressed)\r\n\t\t\t\t|| GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Y);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate static void DeleteSave(int index) {\r\n\t\t\tif (InputOutput.SaveManager.SaveExists(index)) {\r\n\t\t\t\tWinF.DialogResult result = WinF.MessageBox.Show(\r\n\t\t\t\t\t\"Are You Sure You Want To Delete Save {index}\",\r\n\t\t\t\t\t\"Confirm\", WinF.MessageBoxButtons.YesNoCancel\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result == WinF.DialogResult.Yes) {\r\n\t\t\t\t\tInputOutput.SaveManager.DeleteSave(index);\r\n\t\t\t\t\t(buttons[index] as SaveButton).DeleteDetails();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static void ReturnToHomeState() {\r\n\t\t\tGV.MonoGameImplement.gameState = GameState.Home;\r\n\t\t\tHome.Reset(); // Reset home screen window\r\n\t\t}\r\n\r\n\t\tprivate static ButtonList buttons;\r\n\r\n\t\tprivate static GPBIWT[] displayedButtons;\r\n\r\n\t\tpublic static bool WaitForInputToBeRemoved { get; set; }\r\n\r\n\t\tprivate static int inputTimeout = 0;\r\n\t\tpublic static void FullScreenReset() { Reset(); }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7173396944999695, "alphanum_fraction": 0.7323831915855408, "avg_line_length": 38.74193572998047, "blob_id": "1c3b614862550109f02e2b7fd4cdeb44b64c4f5b", "content_id": "6fc0dfa15247fc9434f7534a93ae22cbe92b04b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 170, "num_lines": 31, "path": "/HollowAether/Lib/GAssets/Items/Chests/ItemChest.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/*public sealed class ItemChest : Chest {\r\n\t\tpublic ItemChest(Vector2 position) : base(position) { }\r\n\r\n\t\tprotected override void ReleaseContents() {\r\n\t\t\tAnimation[\"begun\"] = AnimationSequence.FromRange(32, 32, 15, 0, 3); // new AnimationSequence(0, new Frame(0, 0, FRAME_WIDTH, FRAME_HEIGHT)); // Ignore Block Dimensions\r\n\t\t\t//Animation[\"finished\"] = new AnimationSequence(0, new Frame(7, 0, FRAME_WIDTH, FRAME_HEIGHT, FRAME_WIDTH, FRAME_HEIGHT));\r\n\t\t\t//Animation[\"opened\"] = AnimationSequence.FromRange(FRAME_WIDTH, FRAME_HEIGHT, 0, 0, 8, FRAME_WIDTH, FRAME_HEIGHT, 5);\r\n\r\n\t\t\tAnimation.SetAnimationSequence(\"begun\"); // Set animation sequence to inital animation frame. Ignore others for now.\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tbase.BuildSequenceLibrary();\r\n\t\t}\r\n\t}*/\r\n}\r\n" }, { "alpha_fraction": 0.7461928725242615, "alphanum_fraction": 0.7563451528549194, "avg_line_length": 34.651161193847656, "blob_id": "588757b4cd804e9ac12f73f841decac49728bf31", "content_id": "c0f0ed04e9516427a3985d1c85a4367aafaad5bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1578, "license_type": "no_license", "max_line_length": 168, "num_lines": 43, "path": "/HollowAether/Lib/GAssets/Blocks/AngledBlock.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/*public partial class AngledBlock : CollideableSprite, IBlock, IInitializableEntity { // Only builds right angled blocks, Other implementation comes later if possible\r\n\t\tpublic AngledBlock() : this(new Vector2(), 0, 0, IBRightAngledTriangle.BlockType.A) { }\r\n\r\n\t\tpublic AngledBlock(Vector2 position, int width, int height, IBRightAngledTriangle.BlockType _type) \r\n\t\t\t: base(position, width, height) { type = _type; } \r\n\r\n\t\tpublic AngledBlock(Vector2 position, int width, int height, bool _rightAllign=true, bool topAllign=false) \r\n\t\t\t: base(position, width, height) {\r\n\t\t\ttype = IBRightAngledTriangle.AllignmentsToBlockType(_rightAllign, topAllign);\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t//animation[GlobalVars.MonoGameImplement.defaultAnimationSequenceKey] = new AnimationSequence(0, new Frame(0, 0, 32, 32));\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRightAngledTriangle(Position, Width, Height, type));\r\n\t\t}\r\n\r\n\t\t//public static void AngledBlockFrom3Vects(Vector2 a, Vector2 b, Vector2 c) { }\r\n\r\n\t\tpublic IBRightAngledTriangle.BlockType type;\r\n\t}*/\r\n}\r\n" }, { "alpha_fraction": 0.6865726709365845, "alphanum_fraction": 0.68916916847229, "avg_line_length": 31.283950805664062, "blob_id": "166a7d1db2600a8e0300ef1fe0db67bed05d5128", "content_id": "249358cec28338759292b0c846c5e08ab01f6403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2698, "license_type": "no_license", "max_line_length": 117, "num_lines": 81, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/ZoneFeatures.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing Microsoft.Xna.Framework;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class ZoneFeatures : Form {\r\n\t\tpublic struct ZoneDetails {\r\n\t\t\tpublic ZoneDetails(String fpath, Vector2 pos, bool _visible) {\r\n\t\t\t\tvisible = _visible;\r\n\t\t\t\tfilePath = fpath;\r\n\t\t\t\tposition = pos;\r\n\t\t\t\tsucceeded = true;\r\n\t\t\t}\r\n\r\n\t\t\tpublic bool visible;\r\n\t\t\tpublic bool succeeded;\r\n\t\t\tpublic String filePath;\r\n\t\t\tpublic Vector2 position;\r\n\r\n\t\t\tpublic static ZoneDetails Failed { get { return new ZoneDetails() { succeeded = false }; } }\r\n\t\t}\r\n\r\n\t\tpublic ZoneFeatures() { InitializeComponent(); }\r\n\r\n\t\tprivate static ZoneDetails Get(ref ZoneFeatures form) {\r\n\t\t\tDialogResult result = form.ShowDialog(); // Show and wait until done\r\n\r\n\t\t\tint? xPos = GlobalVars.Misc.StringToInt(form.xTextBox.Text);\r\n\t\t\tint? yPos = GlobalVars.Misc.StringToInt(form.yTextBox.Text);\r\n\r\n\t\t\tbool numFail = !xPos.HasValue || !yPos.HasValue;\r\n\t\t\tbool fileTitleFail = String.IsNullOrWhiteSpace(form.fileNameTextBox.Text);\r\n\r\n\t\t\tif (result != DialogResult.OK || numFail || fileTitleFail) {\r\n\t\t\t\tif (numFail) {\r\n\t\t\t\t\tif (!xPos.HasValue) MessageBox.Show($\"Couldn't cast X-Input to integer\", \"Num Error\");\r\n\t\t\t\t\tif (!yPos.HasValue) MessageBox.Show($\"Couldn't cast Y-Input to integer\", \"Num Error\");\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif (fileTitleFail) MessageBox.Show($\"Invalid title for zone file\", \"Title Error\");\r\n\r\n\t\t\t\treturn ZoneDetails.Failed; // Return failed zone detail structure\r\n\t\t\t}\r\n\r\n\t\t\treturn new ZoneDetails(\r\n\t\t\t\tIOMan.Join(\"Zones\", form.fileNameTextBox.Text.Replace(\" \", \"\")), \r\n\t\t\t\tnew Vector2(xPos.Value, yPos.Value), \r\n\t\t\t\tform.visibleRadioButton.Checked\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic static ZoneDetails Get() { return Get(\"File Name.ZNE\", Vector2.Zero, true, false); }\r\n\r\n\t\tpublic static ZoneDetails Get(String filePath, Vector2? position=null, bool visible=true, bool pathReadonly=true) {\r\n\t\t\tZoneFeatures form = new ZoneFeatures();\r\n\r\n\t\t\t#region Set Vars\r\n\t\t\tform.fileNameTextBox.Text = filePath; //IOMan.GetFileTitleFromPath(filePath);\r\n\t\t\tform.fileNameTextBox.ReadOnly = pathReadonly; // Path Can Be Edited\r\n\r\n\t\t\tVector2 pos = position.HasValue ? position.Value : Vector2.Zero;\r\n\r\n\t\t\tform.xTextBox.Text = pos.X.ToString();\r\n\t\t\tform.yTextBox.Text = pos.Y.ToString();\r\n\t\t\t#endregion\r\n\r\n\t\t\tZoneDetails returnVal = Get(ref form);\r\n\t\t\tform.Dispose(); // Free from memory\r\n\r\n\t\t\treturn returnVal; // Return details\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7339391112327576, "alphanum_fraction": 0.7382902503013611, "avg_line_length": 48.727272033691406, "blob_id": "1e34658966a51ba55e49d7b70d23739f7c18fee8", "content_id": "c2ad91d5dfc313f089165f208d52a95cca74fb92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7816, "license_type": "no_license", "max_line_length": 127, "num_lines": 154, "path": "/HollowAether/Lib/GAssets/BodySprite.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Collideable Sprite which can experience the effects of gravity</summary>\r\n\tpublic abstract partial class BodySprite : CollideableSprite, IBody {\r\n\t\tpublic BodySprite() : base() { }\r\n\r\n\t\tpublic BodySprite(Vector2 position, int width, int height, bool aRunning=true) : base(position, width, height, aRunning) { }\r\n\t\r\n\t\t/// <summary>Method to implement downwards gravitational pull</summary>\r\n\t\t/// <remarks>Note this only allows the player to fall, running through or into blocks is for something else</remarks>\r\n\t\tpublic virtual void ImplementGravity() {\r\n\t\t\tif (Falling(1, 0) || Falling(-1, 0)) { // If u haven't intersected with any known collideable blocks\r\n\t\t\t\t// Velocity = Acceleration * Time; Displacement = Velocity * Time^2 = Acceleration * Time^2\r\n\t\t\t\tif (velocity.Y == 0) velocity.Y = defaultFallingVelocity; // Begun falling, start with default\r\n\r\n\t\t\t\tvelocity.Y += GravitationalAcceleration * elapsedTime; // Increment velocity by change in acceleration\r\n\r\n\t\t\t\tOffsetSpritePosition(Y: YDisplacement); // Push sprite by desired vertical offset\r\n\r\n\t\t\t\tif (FixDownwardCollisionAfterFalling()) {\r\n\t\t\t\t\tStopFalling(); // Player is no longer falling so reset falling\r\n\t\t\t\t\tVerticalDownwardBoundaryFix(); // Fix downward collision once occured\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected virtual bool FixDownwardCollisionAfterFalling() {\r\n\t\t\treturn !(Falling(1, 0) ^ Falling(-1, 0)) && HasIntersectedTypes(GV.MonoGameImplement.BlockTypes);\r\n\t\t}\r\n\r\n\t\t/// <summary>Method to check wether player is currently above a block or not</summary>\r\n\t\tpublic virtual bool Falling() { return !(HasIntersectedTypes(GV.MonoGameImplement.BlockTypes)); }\r\n\r\n\t\t/// <summary>Method to check wether player is currently above a block or not</summary>\r\n\t\t/// <param name=\"offset\">Value by which to offset boundary for check</param>\r\n\t\tpublic bool Falling(Vector2 offset) { return CheckOffsetMethodCaller(offset, () => Falling()); }\r\n\r\n\t\tpublic bool Falling(float X, float Y) { return Falling(new Vector2(X, Y)); }\r\n\r\n\t\t/// <summary>Method to implement when player has stopped falling</summary>\r\n\t\t/// <remarks>Interpret any downward force damage here then call base.StopFalling() to reset vars</remarks>\r\n\t\tprotected virtual void StopFalling() { velocity.Y = 0; }\r\n\r\n\t\tprivate float? SharedCollisionHandler(ICollideable[] collided, Direction direction, Func<IBoundaryContainer, bool> checker) {\r\n\t\t\tif (collided.Length > 1) collided = (from X in collided where checker(X.Boundary) select X).ToArray(); // Shorten block span\r\n\t\t\treturn LoopGetPositionFromDirection(collided, direction); // Get new position after collision with collided items & return\r\n\t\t}\r\n\r\n\t\t/// <summary>Fixes sprite position when it has intersected a block</summary>\r\n\t\tprotected virtual void VerticalDownwardBoundaryFix() {\r\n\t\t\tICollideable[] collided = CompoundIntersects(GV.MonoGameImplement.BlockTypes).Cast<ICollideable>().ToArray();\r\n\t\t\tfloat? position = SharedCollisionHandler(collided, Direction.Top, GenericVerticalBoundaryFixValidityCheck);\r\n\r\n\t\t\tif (position.HasValue) {\r\n\t\t\t\tSetPosition(Y: position.Value); // If new position has value, set sprite to new sprite position\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected virtual void HorizontalBoundaryFix(bool movingLeft) {\r\n\t\t\tDirection directionToCorrect = (movingLeft) ? Direction.Right : Direction.Left; // Determine which direction to correct in\r\n\t\t\tICollideable[] collided = CompoundIntersects(GV.MonoGameImplement.BlockTypes).Cast<ICollideable>().ToArray(); // Collideable\r\n\r\n\t\t\tfloat? position = SharedCollisionHandler(collided, directionToCorrect, GenericHorizontalBoundaryFixValidityCheck);\r\n\r\n\t\t\tif (position.HasValue) SetPosition(X: position.Value); // If new position has value, set sprite to new sprite position\r\n\t\t}\r\n\r\n\t\t/// <summary>Method to check which boundaries are valid for a downward boundary check</summary>\r\n\t\t/// <param name=\"container\">Boundary to check compatibility with</param>\r\n\t\t/// <returns>Whether boundary is valid for check</returns>\r\n\t\tprotected virtual bool GenericVerticalBoundaryFixValidityCheck(IBoundaryContainer container) {\r\n\t\t\tRectangle A = container.SpriteRect, B = SpriteRect; // B = self\r\n\t\t\treturn B.X >= A.X - B.Width && B.X + B.Width <= A.X + A.Width; \r\n\t\t\t// True when intersected blocks X values holds self X values\r\n\t\t}\r\n\r\n\t\tprotected bool GenericHorizontalBoundaryFixValidityCheck(IBoundaryContainer container) {\r\n\t\t\tRectangle target = container.SpriteRect, self = container.SpriteRect; // Store vars\r\n\t\t\treturn self.Y > target.Y - self.Height && self.Y < target.Y + target.Height;\r\n\t\t}\r\n\r\n\t\t/// <summary>Loops through all collided monogame objects and gets desired position</summary>\r\n\t\t/// <param name=\"collided\">All collided IMGO's which've been intersected with</param>\r\n\t\t/// <param name=\"direction\">The direction to which a new position is required</param>\r\n\t\t/// <returns>New position which sprite should be pushed to</returns>\r\n\t\tprotected float? LoopGetPositionFromDirection(ICollideable[] collided, Direction direction) {\r\n\t\t\tvar position = IntersectingPositions.Empty; // to hold intersecting positions\r\n\r\n\t\t\tforeach (ICollideable _object in collided) // For all collided IMonoGameObjects\r\n\t\t\t\tposition.Set(direction, Boundary.GetNonIntersectingPositions(_object.Boundary)[direction]);\r\n\r\n\t\t\treturn position[direction]; //\r\n\t\t}\r\n\r\n\t\tprotected float? LoopGetPositionFromDirection(Vector2 offset, ICollideable[] collided, Direction direction) {\r\n\t\t\treturn CheckOffsetMethodCaller(offset, () => LoopGetPositionFromDirection(collided, direction));\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Update root method\r\n\t\t}\r\n\r\n\t\t/// <summary>Calculates the horizontal displacement of the sprite with a given velocity</summary>\r\n\t\tpublic float GetHorizontalDisplacement() {\r\n\t\t\treturn (Math.Abs(velocity.X) > TerminalVelocity.X ? TerminalVelocity.X : velocity.X) * elapsedTime;\r\n\t\t}\r\n\r\n\t\t/// <summary>Calculates the vertical displacement of the sprite with a given velocity</summary>\r\n\t\tpublic float GetVerticalDisplacement() {\r\n\t\t\treturn (Math.Abs(velocity.Y) > TerminalVelocity.Y ? TerminalVelocity.Y : velocity.Y) * elapsedTime;\r\n\t\t}\r\n\t\t\r\n\t\t/// <summary>Velocity of body/mesh</summary>\r\n\t\tpublic Vector2 velocity = Vector2.Zero;\r\n\r\n\t\t/// <summary>Default falling velocity of sprite (starting from 0 too subtle)</summary>\r\n\t\tprotected float defaultFallingVelocity = GV.MonoGameImplement.gravity * 2; // 2 seconds after falling\r\n\r\n\t\t/// <summary>Gets horizontal displacement offered by velocity</summary>\r\n\t\tpublic float XDisplacement { get { return GetHorizontalDisplacement(); } }\r\n\r\n\t\t/// <summary>Gets vertical displacement offered by velocity</summary>\r\n\t\tpublic float YDisplacement { get { return GetVerticalDisplacement(); } }\r\n\r\n\t\t/// <summary>Combines both horizontal and vertical displacement into a Vector2</summary>\r\n\t\tpublic Vector2 Displacement { get { return velocity * elapsedTime; } }\r\n\r\n\t\t/// <summary>The greatest velocity of the given body/mesh</summary>\r\n\t\tpublic virtual Vector2 TerminalVelocity { get; protected set; } = new Vector2(0, 125);\r\n\t\t\r\n\t\t/// <summary>Acceleration of given sprite when not at rest/mobile</summary>\r\n\t\tpublic virtual Vector2 Acceleration { get; protected set; } = new Vector2(0, 0);\r\n\r\n\t\tpublic virtual float GravitationalAcceleration { get; protected set; } = GV.MonoGameImplement.gravity;\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.7135802507400513, "alphanum_fraction": 0.7214815020561218, "avg_line_length": 31.19672203063965, "blob_id": "858263711a2219f5101edf870f00658b4c4dc671", "content_id": "1730ed67f53cb2cb6d0592a02465a64c19fb4dcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2027, "license_type": "no_license", "max_line_length": 126, "num_lines": 61, "path": "/HollowAether/Lib/GAssets/Items/SaveStation.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic partial class SaveStation : CollideableSprite, IInteractable {\r\n\t\tpublic SaveStation() : base() { }\r\n\r\n\t\tpublic SaveStation(Vector2 position, int width=FRAME_WIDTH, int height=FRAME_HEIGHT) : base(position, width, height, true) {\r\n\t\t\t// Initialize(@\"cs\\npcsym\"); // Initialise sprite from construction\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(\r\n\t\t\t\tFRAME_WIDTH, FRAME_HEIGHT, 6, 1, 8, FRAME_WIDTH, FRAME_HEIGHT, 1, true, 0\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic void Interact() {\r\n\t\t\tif (CanInteract) {\r\n\t\t\t\tHUD.ContextMenu.CreateOKCancel(\"You've reached a save point\\nWould you like to save now?\",\r\n\t\t\t\t\t(ok) => { if (ok) InputOutput.SaveManager.SaveCurrentGameState(GV.MonoGameImplement.saveIndex); }\r\n\t\t\t\t);\r\n\r\n\t\t\t\tCanInteract = false; interaction_timeout = INTERACTION_TIMEOUT; // Set interaction off\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates animation. Doesn't update whilst hood is running as designated\r\n\r\n\t\t\tif (!CanInteract && interaction_timeout > 0) interaction_timeout -= elapsedMilitime; else CanInteract = true;\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(SpriteRect));\r\n\t\t}\r\n\r\n\t\tpublic bool CanInteract { get; set; } = true;\r\n\r\n\t\tpublic bool Interacted { get; } = false; // Always can interact\r\n\r\n\t\tprivate static readonly int INTERACTION_TIMEOUT = 1500;\r\n\r\n\t\tprivate int interaction_timeout = 0;\r\n\r\n\t\tpublic const int FRAME_WIDTH=32, FRAME_HEIGHT=32;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7157564759254456, "alphanum_fraction": 0.7157564759254456, "avg_line_length": 32.369232177734375, "blob_id": "285050e414032ec583e20e8a92b782fc13981a13", "content_id": "f63b4c83d895e8843c6ce3a99124d1789cff2c6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2236, "license_type": "no_license", "max_line_length": 144, "num_lines": 65, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Forms/SetZoneDimensions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class SetZoneDimensions : Form {\r\n\t\tSetZoneDimensions(string zonePath, int width, int height) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\twidthTextBox.Text = width.ToString();\r\n\t\t\theightTextBox.Text = height.ToString();\r\n\t\t\tzoneTextBox.Text = zonePath;\r\n\t\t}\r\n\r\n\t\tprivate void SetZoneDimensions_Load(object sender, EventArgs e) {\r\n\r\n\t\t}\r\n\r\n\t\tpublic static Tuple<int, int> Run(string zonePath, int width, int height) {\r\n\t\t\tSetZoneDimensions dimensions = new SetZoneDimensions(zonePath, width, height);\r\n\r\n\t\t\tDialogResult result = dimensions.ShowDialog(); // Display form instance as a dialog\r\n\r\n\t\t\tint? newWidth = null, newHeight = null; // To store new variables\r\n\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tnewWidth = GV.Misc.StringToInt(dimensions.widthTextBox.Text);\r\n\t\t\t\tnewHeight = GV.Misc.StringToInt(dimensions.heightTextBox.Text);\r\n\r\n\t\t\t\tif (!newWidth.HasValue) DisplayMessagebox(dimensions.widthTextBox.Text, \"Width\");\r\n\t\t\t\tif (!newHeight.HasValue) DisplayMessagebox(dimensions.heightTextBox.Text, \"Height\");\r\n\t\t\t}\r\n\r\n\t\t\treturn new Tuple<int, int>(\r\n\t\t\t\t(newWidth.HasValue) ? newWidth.Value : width,\r\n\t\t\t\t(newHeight.HasValue) ? newHeight.Value : height\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tprivate static void DisplayMessagebox(string text, string attrib) {\r\n\t\t\tMessageBox.Show($\"Couldn't Convert {attrib} Attribute '{text}' To a Number\", \"Conversion Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\tDialogResult = DialogResult.OK; this.Close();\r\n\t\t}\r\n\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) {\r\n\t\t\tDialogResult = DialogResult.Cancel; this.Close();\r\n\t\t}\r\n\r\n\t\tprivate void SetZoneDimensions_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\tif (DialogResult != DialogResult.OK && DialogResult != DialogResult.Cancel) {\r\n\t\t\t\tDialogResult = DialogResult.Cancel; // Just in case, not set to value\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7043634653091431, "alphanum_fraction": 0.7079536318778992, "avg_line_length": 51.64444351196289, "blob_id": "55c95da4db29b413102415284ac0d22d2da09200", "content_id": "501a982fa20dc288dfd2210df146a2c674511686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7244, "license_type": "no_license", "max_line_length": 222, "num_lines": 135, "path": "/HollowAether/Lib/GAssets/Animation/AnimationSequence.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.Exceptions.CE;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Class to store a series of frames and cycle through them one at a time</summary>\r\n\tpublic class AnimationSequence {\r\n\t\t/// <summary>Sets default base values for use by class</summary>\r\n\t\t/// <param name=\"initIndex\">index of current frame in sequence</param>\r\n\t\tAnimationSequence(int initIndex) { FrameIndex = initIndex; }\r\n\t\t\r\n\t\t/// <summary>Creates animation sequence from passed frame arguments</summary>\r\n\t\t/// <param name=\"initIndex\">Index of frame to begin animtion with</param>\r\n\t\t/// <param name=\"_frames\">Frames to add to animation sequence</param>\r\n\t\tpublic AnimationSequence(int initIndex = 0, params Frame[] _frames) : this(initIndex) { frames.AddRange(_frames); }\r\n\r\n\t\t/// <summary>Builds animation sequence from XY frame tuples</summary>\r\n\t\t/// <param name=\"initIndex\">Index of frame to begin animtion with</param>\r\n\t\t/// <param name=\"width\">Width of frames</param> <param name=\"height\">Height of frames</param>\r\n\t\t/// <param name=\"blockWidth\">Width of blocks</param> <param name=\"blockHeight\">Height of blocks</param>\r\n\t\t/// <param name=\"args\">XY pairs for values in animation in multiples of block width and height</param>\r\n\t\tpublic static AnimationSequence FromTuples(int width, int height, int blockWidth = 32, int blockHeight = 32, int runCount=1, int initIndex = 0, params Tuple<int, int>[] args) {\r\n\t\t\treturn new AnimationSequence(initIndex, GenerateFramesFromSequence(width, height, blockWidth, blockHeight, runCount, args).ToArray());\r\n\t\t}\r\n\r\n\t\t/// <summary>Builds animation sequence from straight strip in texture</summary>\r\n\t\t/// <param name=\"numOfFrames\">Number of frames in strip</param>\r\n\t\t/// <param name=\"initIndex\">Index of frame to begin animtion with</param>\r\n\t\t/// <param name=\"keepY\">Whether the strip is horizontal or vertical</param>\r\n\t\t/// <param name=\"startPositionX\">Beginning position on X axis to build frame</param>\r\n\t\t/// <param name=\"startPositionY\">Beginning position on Y axis to build frame</param>\r\n\t\t/// <param name=\"width\">Width of frames</param> <param name=\"height\">Height of frames</param>\r\n\t\t/// <param name=\"blockWidth\">Width of blocks</param> <param name=\"blockHeight\">Height of blocks</param>\r\n\t\tpublic static AnimationSequence FromRange(int width, int height, int startPositionX, int startPositionY, int numOfFrames, int blockWidth = 32, int blockHeight = 32, int runCount=1, bool keepY = true, int initIndex = 0) {\r\n\t\t\tFunc<int, Frame> GetFrame = (N) => {\r\n\t\t\t\t// Gets frame accounting for whether X or Y changes\r\n\t\t\t\tvar pos = new Tuple<int, int>( // relativePosition\r\n\t\t\t\t\t(keepY) ? startPositionX + N : startPositionX,\r\n\t\t\t\t\t(keepY) ? startPositionY : startPositionY + N\r\n\t\t\t\t);\r\n\t\t\t\t\r\n\t\t\t\treturn new Frame(pos.Item1, pos.Item2, width, height, blockWidth, blockHeight, runCount);\r\n\t\t\t};\r\n\r\n\t\t\treturn new AnimationSequence(0, (from X in Enumerable.Range(0, numOfFrames) select GetFrame(X)).ToArray());\r\n\t\t}\r\n\r\n\t\t/// <summary>Yields framesfrom XY value combinations</summary>\r\n\t\t/// <param name=\"width\">Width of frames</param> <param name=\"height\">Height of frames</param>\r\n\t\t/// <param name=\"blockWidth\">Width of blocks</param> <param name=\"blockHeight\">Height of blocks</param>\r\n\t\t/// <param name=\"positions\">XY pairs for values in animation in multiples of block width and height</param>\r\n\t\tprivate static IEnumerable<Frame> GenerateFramesFromSequence(int width, int height, int blockWidth, int blockHeight, int runCount, params Tuple<int, int>[] positions) {\r\n\t\t\tforeach (Tuple<int, int> position in positions) // Yield new frame for each in tuple collection\r\n\t\t\t\tyield return new Frame(position.Item1, position.Item2, width, height, blockWidth, blockHeight, runCount);\r\n\t\t}\r\n\r\n\t\t/// <summary>Converts animation to animation file contents</summary>\r\n\t\t/// <param name=\"animationName\">Name of animation to store</param>\r\n\t\t/// <param name=\"sequence\">Sequence to convert to animation</param>\r\n\t\tpublic static String ToFileContents(String animationName, AnimationSequence sequence) {\r\n\t\t\tvar builder = new StringBuilder(\"\\\"\" + animationName + \"\\\" {\\n\");\r\n\r\n\t\t\tforeach (Frame frame in sequence.frames) {\r\n\t\t\t\tbuilder.Append($\" {frame.ToFileContents()}\\n\");\r\n\t\t\t}\r\n\r\n\t\t\tbuilder.Append(\"}\\n\"); // Closing curly brace for animation\r\n\r\n\t\t\treturn builder.ToString(); // Convert to string and return\r\n\t\t}\r\n\r\n\t\t/// <summary>Reverses all frames in current sequence</summary>\r\n\t\tpublic void Reverse() { frames.Reverse(); }\r\n\r\n\t\t/// <summary>Adds frame to animation</summary>\r\n\t\t/// <param name=\"frame\">Frame to add</param>\r\n\t\tpublic void AddFrame(Frame frame) { frames.Add(frame); }\r\n\r\n\t\t/// <summary>Resets animation sequence to beginning</summary>\r\n\t\t/// <param name=\"value\">Index to return to, default is 0</param>\r\n\t\tpublic void ResetSequence(int value = 0) { FrameIndex = value; }\r\n\r\n\t\t/// <summary>Converts this animation to how it appears in an animation file</summary>\r\n\t\t/// <param name=\"animationName\">Name of animation to store</param>\r\n\t\tpublic String ToFileContents(String animationName) {\r\n\t\t\treturn ToFileContents(animationName, this);\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets current frame in animation sequence</summary>\r\n\t\t/// <param name=\"increment\">Whether to allow sequence to move on to next frame</param>\r\n\t\t/// <returns>Current animation frame before increment if incremented</returns>\r\n\t\tpublic Frame GetFrame(bool increment = true) {\r\n\t\t\tint returnIndex = FrameIndex; // stores current frame index before modification\r\n\t\t\tif (increment) FrameIndex = (FrameIndex + 1 < Length) ? FrameIndex + 1 : 0;\r\n\t\t\treturn frames[returnIndex]; // Increments and then returns previous frame in animation\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets frame of sequence at known index</summary>\r\n\t\t/// <param name=\"index\">Index to retrieve frame from</param>\r\n\t\tprivate Frame GetFrameFromIndex(int index) {\r\n\t\t\ttry { return frames[index]; } // Try to return frame of sequence from given index. If doesn't exist then throw exception\r\n\t\t\tcatch { throw new AnimationException($\"Sequence of length {Length} doesn't have value at index {index + 1}\"); }\r\n\t\t}\r\n\r\n\t\t/// <summary>Returns a given frame in sequence</summary>\r\n\t\t/// <param name=\"index\">Index of frame to return</param>\r\n\t\tpublic Frame this[int index] { get { return GetFrameFromIndex(index); } }\r\n\r\n\t\t/// <summary>Public accessor for frames in sequence</summary>\r\n\t\tpublic List<Frame> Frames { get { return frames; } }\r\n\r\n\t\t/// <summary>Index of current frame</summary>\r\n\t\tpublic int FrameIndex { get; private set; } = 0;\r\n\t\t\r\n\t\t/// <summary>Whether animation is from file stream</summary>\r\n\t\tpublic bool IsImported { get; set; } = false;\r\n\r\n\t\t/// <summary>Length of frames in given animation sequence</summary>\r\n\t\tpublic int Length { get { return frames.Count; } }\r\n\r\n\t\t/// <summary>Current frame in animation sequence, ignores increment</summary>\r\n\t\tpublic Frame CurrentFrame { get { return GetFrame(false); } }\r\n\r\n\t\t/// <summary>Frames in given sequence</summary>\r\n\t\tprivate List<Frame> frames = new List<Frame>();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7239680290222168, "alphanum_fraction": 0.7290279865264893, "avg_line_length": 41.160919189453125, "blob_id": "5e686a7ed1e7e19734b679b053d631e9538111dc", "content_id": "03217f0b4229986240128262b05a09b5931251df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7512, "license_type": "no_license", "max_line_length": 132, "num_lines": 174, "path": "/HollowAether/Lib/GAssets/BG+FG/Transition.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic static class Transition {\r\n\t\tprivate sealed class FadeSprite : VolatileSprite {\r\n\t\t\tpublic FadeSprite(Vector2 position, AnimationSequence _default) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT, true) {\r\n\t\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = _default;\r\n\t\t\t\tInitialize(textureKey); // Initialise from construction\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\t\tbase.Initialize(textureKey); // Call base constructor to \r\n\r\n\t\t\t\tInitializeVolatility(VolatilityType.Other, new ImplementVolatility(VolatilityImplement));\r\n\t\t\t\t// Initialise volatility to check when it is best to remove sprite from sprite batch\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\t\tbase.Update(updateAnimation);\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Draw() {\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.End(); // End already running with camera\r\n\r\n\t\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false); // Start without camera\r\n\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\t\tTexture, position: Position,\r\n\t\t\t\t\tsourceRectangle: Animation.currentFrame.ToRect(),\r\n\t\t\t\t\tscale: new Vector2(transitionZoom),\r\n\t\t\t\t\tcolor: Color.White\r\n\t\t\t\t);\r\n\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.End(); // End non camera sprite batch\r\n\r\n\t\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(); // Init with camera for next sprites\r\n\t\t\t}\r\n\r\n\t\t\tprivate bool VolatilityImplement(IMonoGameObject self) {\r\n\t\t\t\t// When animation has reached end, ensure sprite is added to removal batch and ready to be deleted\r\n\t\t\t\treturn Animation.CurrentSequence.FrameIndex + 1 >= Animation.CurrentSequence.Length;\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t\t//throw new NotImplementedException();\r\n\t\t\t}\r\n\r\n\t\t\tpublic static String textureKey = @\"fx\\fadewhite\";\r\n\r\n\t\t\tpublic static readonly int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\t\t}\r\n\r\n\t\tpublic enum Transitions {\r\n\t\t\tUniform, // Equal transition view\r\n\t\t\tLeftHeavy, // More transition on the left\r\n\t\t\tRightHeavy, // more transition on the right\r\n\t\t\tUpHeavy, // more transition above\r\n\t\t\tBottomHeavy // more transition below\r\n\t\t}\r\n\r\n\t\tpublic enum TransitionShape {\r\n\t\t\tDiamond = 0,\r\n\t\t\tCircle = 1\r\n\t\t}\r\n\r\n\t\tpublic static void CreateTransition(Transitions transition = Transitions.Uniform, TransitionShape shape=TransitionShape.Diamond) {\r\n\t\t\tif (transitionRunning) return; // Already running, don't run again\r\n\r\n\t\t\tFrame[] frames = GetFrames((int)shape); // Store all frames for desired shape animation\r\n\r\n\t\t\tint width = GV.Variables.windowWidth, height = GV.Variables.windowHeight;\r\n\r\n\t\t\tint horizontalSpriteSpan = (int)Math.Ceiling(width / FadeSprite.SPRITE_WIDTH / transitionZoom);\r\n\t\t\tint verticalSpriteSpan = (int)Math.Ceiling(height / FadeSprite.SPRITE_HEIGHT / transitionZoom);\r\n\r\n\t\t\tswitch ((int)transition) {\r\n\t\t\t\tcase 0: CreateUniformTransition ((int)shape, frames, horizontalSpriteSpan, verticalSpriteSpan); break;\r\n\t\t\t\tcase 1: CreateLeftHeavyTransition ((int)shape, frames, horizontalSpriteSpan, verticalSpriteSpan); break;\r\n\t\t\t\tcase 2: CreateRightHeavyTransition ((int)shape, frames, horizontalSpriteSpan, verticalSpriteSpan); break;\r\n\t\t\t\tcase 3: CreateUpHeavyTransition ((int)shape, frames, horizontalSpriteSpan, verticalSpriteSpan); break;\r\n\t\t\t\tcase 4: CreateBottomHeavyTransition ((int)shape, frames, horizontalSpriteSpan, verticalSpriteSpan); break;\r\n\t\t\t}\r\n\r\n\t\t\ttransitionRunning = true;\r\n\t\t}\r\n\r\n\t\tprivate static void CreateUniformTransition(int shape, Frame[] frames, int xSpan, int ySpan) {\r\n\t\t\tforeach (int Y in Enumerable.Range(0, ySpan)) {\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, xSpan)) {\r\n\t\t\t\t\tVector2 position = new Vector2(X*FadeSprite.SPRITE_WIDTH*transitionZoom, Y*FadeSprite.SPRITE_HEIGHT*transitionZoom);\r\n\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(new FadeSprite(position, new AnimationSequence(0, frames)));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//((IVolatile)GV.MonoGameImplement.monogameObjects[spriteID]).VolatileManager.Deleting += () => transitionRunning = false;\r\n\t\t\t// Add event to final volatile sprite so new transitions can be made after it's deletion/removal-from-SpriteBatch.\r\n\t\t}\r\n\r\n\t\tprivate static void CreateLeftHeavyTransition(int shape, Frame[] frames, int xSpan, int ySpan) {\r\n\t\t\tthrow new NotImplementedException($\"Left heavy not yet done\");\r\n\r\n\t\t\tString spriteID = String.Empty; // Var to store any new sprite IDs\r\n\r\n\t\t\tforeach (int Y in Enumerable.Range(0, ySpan)) {\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, xSpan)) {\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t//((IVolatile)GV.MonoGameImplement.monogameObjects[spriteID]).VolatileManager.Deleting += () => transitionRunning = false;\r\n\t\t\t// Add event to final volatile sprite so new transitions can be made after it's deletion/removal-from-SpriteBatch.\r\n\t\t}\r\n\r\n\t\tprivate static void CreateRightHeavyTransition(int shape, Frame[] frames, int xSpan, int ySpan) {\r\n\t\t\tthrow new NotImplementedException($\"Right heavy not yet done\");\r\n\r\n\t\t\tString spriteID = String.Empty; // Var to store any new sprite IDs\r\n\r\n\t\t\t((IVolatile)GV.MonoGameImplement.monogameObjects[spriteID]).VolatilityManager.Deleting += () => transitionRunning = false;\r\n\t\t\t// Add event to final volatile sprite so new transitions can be made after it's deletion/removal-from-SpriteBatch.\r\n\t\t}\r\n\r\n\t\tprivate static void CreateUpHeavyTransition(int shape, Frame[] frames, int xSpan, int ySpan) {\r\n\t\t\tthrow new NotImplementedException($\"Up heavy not yet done\");\r\n\r\n\t\t\tString spriteID = String.Empty; // Var to store any new sprite IDs\r\n\r\n\t\t\t((IVolatile)GV.MonoGameImplement.monogameObjects[spriteID]).VolatilityManager.Deleting += () => transitionRunning = false;\r\n\t\t\t// Add event to final volatile sprite so new transitions can be made after it's deletion/removal-from-SpriteBatch.\r\n\t\t}\r\n\r\n\t\tprivate static void CreateBottomHeavyTransition(int shape, Frame[] frames, int xSpan, int ySpan) {\r\n\t\t\tthrow new NotImplementedException($\"Down heavy not yet done\");\r\n\r\n\t\t\tString spriteID = String.Empty; // Var to store any new sprite IDs\r\n\r\n\t\t\t((IVolatile)GV.MonoGameImplement.monogameObjects[spriteID]).VolatilityManager.Deleting += () => transitionRunning = false;\r\n\t\t\t// Add event to final volatile sprite so new transitions can be made after it's deletion/removal-from-SpriteBatch.\r\n\t\t}\r\n\r\n\t\t/// <summary>Get Sequeunce for animation of desired shape</summary>\r\n\t\t/// <param name=\"shape\">Shape (Y-Value) for frames in animation</param>\r\n\t\t/// <returns>Sequence containing desired animation</returns>\r\n\t\tprivate static AnimationSequence GetFullSequence(int shape) {\r\n\t\t\treturn AnimationSequence.FromRange(32, 32, 0, shape, 16, 32, 32, 1, true, 0);\r\n\t\t}\r\n\r\n\t\t/// <summary>Get all frames in sequence for given transition</summary>\r\n\t\t/// <param name=\"shape\">Shape (Y-Value) for frames in animation</param>\r\n\t\t/// <returns>All frames for the desired animation sequence</returns>\r\n\t\tprivate static Frame[] GetFrames(int shape) {\r\n\t\t\treturn GetFullSequence(shape).Frames.ToArray();\r\n\t\t}\r\n\r\n\t\t/// <summary>Value by which to zoom transitions in</summary>\r\n\t\tpublic static readonly float transitionZoom = 1.875f;\r\n\r\n\t\t/// <summary>Used to prevent simultaneous transition creations</summary>\r\n\t\tprivate static bool transitionRunning = false;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7592592835426331, "alphanum_fraction": 0.7592592835426331, "avg_line_length": 25, "blob_id": "43fbfc3c6a0f350d437b5a290a754b363bce439d", "content_id": "5d6e7ad2bb20dd3e05ed722cd8be1cae80e0dddd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 326, "license_type": "no_license", "max_line_length": 76, "num_lines": 12, "path": "/HollowAether/Lib/Interfaces/IBody.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary>Interface for any class which can experience gravity</summary>\r\n\tpublic interface IBody { void ImplementGravity(); }\r\n}\r\n" }, { "alpha_fraction": 0.6998806595802307, "alphanum_fraction": 0.707040548324585, "avg_line_length": 36.986045837402344, "blob_id": "77d7fe1ec741099685a8e0a438d06b068d58acfd", "content_id": "9d52605f62fe8ee43003aa66c4509600f801860f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 8382, "license_type": "no_license", "max_line_length": 134, "num_lines": 215, "path": "/HollowAether/Lib/GAssets/BG+FG/Background.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic class Background : List<BackgroundLayer>, IGeneralUpdateable, IDrawable {\r\n\t\tpublic Background() : base() { }\r\n\r\n\t\tpublic Background(int capacity) : base(capacity) { }\r\n\r\n\t\tpublic Background(IEnumerable<BackgroundLayer> collection) : base(collection) { }\r\n\r\n\t\tpublic void Update() {\r\n\t\t\tforeach (BackgroundLayer layer in this) {\r\n\t\t\t\tif (layer is IGeneralUpdateable)\r\n\t\t\t\t\t(layer as IGeneralUpdateable).Update();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false);\r\n\r\n\t\t\tforeach (BackgroundLayer layer in this)\r\n\t\t\t\tlayer.Draw(generalLayer);\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic List<BackgroundLayer> layers;\r\n\t\tpublic static float generalLayer = 0.15f;\r\n\t}\r\n\r\n\tpublic class BackgroundLayer {\r\n\t\tpublic BackgroundLayer(String textureKey, Frame frame, float relativeLayer = 1f) {\r\n\t\t\tthis.textureKey = textureKey;\r\n\t\t\tthis.relativeLayer = relativeLayer;\r\n\t\t\tthis.frame = frame;\r\n\r\n\t\t\tTexture2D texture = Texture; // Store\r\n\t\t\tsize = frame.ToRect().Size;\r\n\t\t}\r\n\r\n\t\tpublic BackgroundLayer(String textureKey, Frame frame, int width, int height, float relativeLayer = 1f) \r\n\t\t\t: this(textureKey, frame, relativeLayer) { size = new Point(width, height);\t}\r\n\r\n\t\tpublic virtual void Draw(float rootLayer) {\r\n\t\t\tRectangle region = ScreenRegion; // Store screen region instance locally\r\n\t\t\tTexture2D backgroundTexture = GV.MonoGameImplement.textures[textureKey];\r\n\r\n\t\t\tDrawFromPosition(offset, rootLayer, backgroundTexture); // Draw from initial position\r\n\r\n\t\t\tif (!RepeatHorizontally && !RepeatVertically) DrawFromPosition(offset, rootLayer, backgroundTexture); else {\r\n\t\t\t\tif (RepeatHorizontally && RepeatVertically) {\r\n\t\t\t\t\tforeach (int direction in new int[] { +1, -1 }) {\r\n\t\t\t\t\t\tforeach (Vector2 yPos in YieldVerticalSpritePositions(offset, size.Y, direction)) {\r\n\t\t\t\t\t\t\tDrawRow(backgroundTexture, yPos.Y, rootLayer); // For each vertical layer segment\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (RepeatHorizontally) {\r\n\t\t\t\t\tDrawRow(backgroundTexture, offset.Y, rootLayer);\r\n\t\t\t\t} else if (RepeatVertically) {\r\n\t\t\t\t\tforeach (int direction in new int[] { +1, -1 }) {\r\n\t\t\t\t\t\tforeach (Vector2 newPos in YieldVerticalSpritePositions(offset, size.X, direction)) {\r\n\t\t\t\t\t\t\tDrawFromPosition(newPos, rootLayer, backgroundTexture);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void DrawFromPosition(Vector2 pos, float rootLayer, Texture2D texture) {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\ttexture,\r\n\t\t\t\t//position\t\t\t : pos,\r\n\t\t\t\tlayerDepth\t\t\t : GetAbsoluteLayer(this, rootLayer),\r\n\t\t\t\tsourceRectangle\t\t : frame.ToRect(),\r\n\t\t\t\tdestinationRectangle : new Rectangle((pos).ToPoint(), size),\r\n\t\t\t\tcolor\t\t\t\t : Color.White\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\t#region RepeatDrawers\r\n\t\tprivate void DrawRow(Texture2D texture, float yPosition, float rootLayer) {\r\n\t\t\tVector2 position = new Vector2(offset.X, yPosition); // start point\r\n\r\n\t\t\tforeach (int direction in new int[] { +1, -1 }) {\r\n\t\t\t\tforeach (Vector2 newPos in YieldHorizontalSpritePositions(position, size.X, direction)) {\r\n\t\t\t\t\tDrawFromPosition(newPos, rootLayer, texture);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region PositionCalculators\r\n\t\tprotected static IEnumerable<float> YieldSpritePositionVariables(float current, int increment, int direction, int maxVal) {\r\n\t\t\twhile ((direction > 0 && current < maxVal) || (direction < 0 && current > 0)) {\r\n\t\t\t\tyield return current; current += direction * increment; // Yield sequential layer positiona\r\n\t\t\t}\r\n\r\n\t\t\tyield return current; // Final yield to account for loop ending before completion\r\n\t\t}\r\n\r\n\t\tprotected static IEnumerable<Vector2> YieldHorizontalSpritePositions(Vector2 current, int width, int direction) {\r\n\t\t\tIEnumerable<float> iter = YieldSpritePositionVariables(current.X, width, direction, GV.Variables.windowWidth);\r\n\t\t\treturn (from X in iter select new Vector2(X, current.Y)); // Constant Y Value, yield alternating horizontal X values\r\n\t\t}\r\n\r\n\t\tprotected static IEnumerable<Vector2> YieldVerticalSpritePositions(Vector2 current, int height, int direction) {\r\n\t\t\tIEnumerable<float> iter = YieldSpritePositionVariables(current.Y, height, direction, GV.Variables.windowHeight);\r\n\t\t\treturn (from Y in iter select new Vector2(current.X, Y)); // Constant X Value, yield alternating vertical Y values\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\tprivate Rectangle GetEncompassingScreenRegion() {\r\n\t\t\treturn new Rectangle(offset.ToPoint(), new Point((int)(GV.Variables.windowWidth), (int)(GV.Variables.windowHeight)));\r\n\t\t}\r\n\r\n\t\tpublic static float GetAbsoluteLayer(BackgroundLayer self, float rootLayer) {\r\n\t\t\treturn (float)(rootLayer + (Math.Pow(10, -3) * self.relativeLayer));\r\n\t\t}\r\n\r\n\t\tprotected Rectangle ScreenRegion { get { return GetEncompassingScreenRegion(); } }\r\n\r\n\t\tpublic Texture2D Texture { get { return GV.MonoGameImplement.textures[textureKey]; } }\r\n\r\n\t\tpublic bool RepeatHorizontally { get; set; } = false;\r\n\r\n\t\tpublic bool RepeatVertically { get; set; } = false;\r\n\r\n\t\tprotected Frame frame;\r\n\r\n\t\tprotected String textureKey;\r\n\r\n\t\tprotected Vector2 offset;\r\n\r\n\t\tpublic Vector2 Offset { get { return offset; } set { offset = value; } }\r\n\r\n\t\tpublic Point size;\r\n\r\n\t\tpublic float relativeLayer;\r\n\t}\r\n\r\n\tpublic class MovingBackgroundLayer : BackgroundLayer, IGeneralUpdateable {\r\n\t\tpublic MovingBackgroundLayer(String textureKey, Frame frame, float relativeLayer) : base(textureKey, frame, relativeLayer) { }\r\n\r\n\t\tpublic MovingBackgroundLayer(String textureKey, Frame frame, int width, int height, float relativeLayer)\r\n\t\t\t: base(textureKey, frame, width, height, relativeLayer) { }\r\n\r\n\t\tpublic void Update() {\r\n\t\t\tif (Velocity.X != 0 && (offset.X > GV.Variables.windowWidth || offset.X < 0))\r\n\t\t\t\toffset.X = size.X - Math.Abs(YieldSpritePositionVariables(offset.X, size.X, -1, GV.Variables.windowWidth).Last());\r\n\r\n\t\t\tif (Velocity.Y != 0 && (offset.Y > GV.Variables.windowHeight || offset.Y < 0))\r\n\t\t\t\toffset.Y = size.Y - Math.Abs(YieldSpritePositionVariables(offset.Y, size.Y, -1, GV.Variables.windowHeight).Last());\r\n\r\n\t\t\toffset += Velocity * GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds * (float)Math.Pow(10, -3);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 Velocity { get; set; } = Vector2.Zero;\r\n\t}\r\n\r\n\tpublic class StretchedBackgroundLayer : BackgroundLayer {\r\n\t\tpublic StretchedBackgroundLayer(String textureKey, Frame frame, float relativeLayer) : base(textureKey, frame, relativeLayer) { }\r\n\r\n\t\tpublic override void Draw(float rootLayer) {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\tTexture,\r\n\t\t\t\t//position:\t\t\t offset + GV.MonoGameImplement.camera.Position,\r\n\t\t\t\tlayerDepth\t\t\t : GetAbsoluteLayer(this, rootLayer),\r\n\t\t\t\tsourceRectangle\t\t : frame.ToRect(),\r\n\t\t\t\tdestinationRectangle : new Rectangle(Point.Zero, ScreenRegion.Size),\r\n\t\t\t\tcolor\t\t\t\t : Color.White\r\n\t\t\t);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic class ScaledBackgroundLayer : BackgroundLayer {\r\n\t\tpublic ScaledBackgroundLayer(String textureKey, Frame frame, float relativeLayer) : base(textureKey, frame, relativeLayer) {\r\n\t\t\tunscaledSize = size;\r\n\t\t}\r\n\r\n\t\tpublic float Scale { get { return scale; } set { scale = value; size = (unscaledSize.ToVector2() * value).ToPoint(); } }\r\n\r\n\t\tprivate float scale = 1;\r\n\r\n\t\tprivate Point unscaledSize;\r\n\t}\r\n\r\n\tpublic class MovingScaledBackgroundLayer : ScaledBackgroundLayer, IGeneralUpdateable {\r\n\t\tpublic MovingScaledBackgroundLayer(String textureKey, Frame frame, float relativeLayer) : base(textureKey, frame, relativeLayer) { }\r\n\r\n\t\tpublic void Update() {\r\n\t\t\tif (Velocity.X != 0 && (offset.X > GV.Variables.windowWidth || offset.X < 0))\r\n\t\t\t\toffset.X = size.X - Math.Abs(YieldSpritePositionVariables(offset.X, size.X, -1, GV.Variables.windowWidth).Last());\r\n\r\n\t\t\tif (Velocity.Y != 0 && (offset.Y > GV.Variables.windowHeight || offset.Y < 0))\r\n\t\t\t\toffset.Y = size.Y - Math.Abs(YieldSpritePositionVariables(offset.Y, size.Y, -1, GV.Variables.windowHeight).Last());\r\n\r\n\t\t\toffset += Velocity * GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds * (float)Math.Pow(10, -3);\r\n\t\t}\r\n\r\n\t\tpublic Vector2 Velocity { get; set; } = Vector2.Zero;\r\n\t}\r\n\r\n\t/*public class ParallaxingBackgroundLayer : BackgroundLayer {\r\n\r\n\t}*/\r\n}" }, { "alpha_fraction": 0.6793444752693176, "alphanum_fraction": 0.6927952766418457, "avg_line_length": 33.93333435058594, "blob_id": "31551034ca47ebc410e5b6395caffdbed8a7499e", "content_id": "337ecc49c1a99f7d937f418467bde24c3cbb06d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6470, "license_type": "no_license", "max_line_length": 152, "num_lines": 180, "path": "/HollowAether/Lib/GAssets/HUD/ContextMenuSprites.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\tpublic static partial class ContextMenu {\r\n\t\tprivate class ContextSpriteCharacter : IPushable {\r\n\t\t\tpublic class CharaAttributes : ICloneable {\r\n\t\t\t\tpublic CharaAttributes() : this(new Color(255, 255, 255), 0f, SpriteEffects.None) { }\r\n\r\n\t\t\t\tpublic CharaAttributes(Color _color, float _rotation, SpriteEffects effects) {\r\n\t\t\t\t\tcolor = _color;\r\n\t\t\t\t\trotation = _rotation;\r\n\t\t\t\t\teffect = effects;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic object Clone() { return new CharaAttributes(color, rotation, effect); }\r\n\r\n\t\t\t\tpublic override string ToString() {\r\n\t\t\t\t\treturn $\"C:{color.ToVector4()}, R:{rotation}, FX:{effect}\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic Color color;\r\n\t\t\t\tpublic float rotation;\r\n\t\t\t\tpublic SpriteEffects effect;\r\n\t\t\t}\r\n\r\n\t\t\tpublic ContextSpriteCharacter(char character, Vector2 _position, CharaAttributes attributes) {\r\n\t\t\t\tchara = character;\r\n\t\t\t\tPosition = _position;\r\n\t\t\t\tAttributes = (CharaAttributes)attributes.Clone(); // Create shallow clone\r\n\t\t\t}\r\n\r\n\t\t\tpublic ContextSpriteCharacter(char character, String font, Vector2 position, CharaAttributes attributes)\r\n\t\t\t\t: this(character, position, attributes) { Font = font; }\r\n\r\n\t\t\tpublic ContextSpriteCharacter(char character, Vector2 position, Color fontColor, float charRotation = 0f, SpriteEffects fx = SpriteEffects.None)\r\n\t\t\t\t: this(character, position, new CharaAttributes(fontColor, charRotation, fx)) { }\r\n\r\n\t\t\tpublic ContextSpriteCharacter(char character, String font, Vector2 position, Color color, float rotation = 0f, SpriteEffects fx = SpriteEffects.None)\r\n\t\t\t\t: this(character, font, position, new CharaAttributes(color, rotation, fx)) { }\r\n\r\n\t\t\tpublic override string ToString() {\r\n\t\t\t\treturn $\"CharStringSprite : '{chara}'\";\r\n\t\t\t}\r\n\r\n\t\t\tpublic void PushTo(Vector2 position, float over = 0.8f) {\r\n\t\t\t\tif (PushArgs.PushValid(position, Position))\r\n\t\t\t\t\tPush(new PushArgs(position, Position, over));\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Push(PushArgs args) { if (!BeingPushed) PushPack = args; }\r\n\r\n\t\t\tpublic void Update() {\r\n\t\t\t\tfloat elapsedTime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds * (float)Math.Pow(10, -3);\r\n\t\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) { PushPack = null; /* Delete push pack */ }\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Draw() {\r\n\t\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(\r\n\t\t\t\t\tGV.MonoGameImplement.fonts[Font], chara.ToString(),\r\n\t\t\t\t\tPosition, Attributes.color, Attributes.rotation,\r\n\t\t\t\t\tVector2.Zero, 1, Attributes.effect, 0\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tpublic Vector2 Size() {\r\n\t\t\t\treturn GV.MonoGameImplement.fonts[Font].MeasureString(chara.ToString());\r\n\t\t\t}\r\n\r\n\t\t\tpublic char chara;\r\n\r\n\t\t\tpublic CharaAttributes Attributes { get; private set; }\r\n\r\n\t\t\tpublic Vector2 Position { get; set; }\r\n\r\n\t\t\tpublic String Font { get; set; } = DEFAULT_FONT;\r\n\r\n\t\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\t\t}\r\n\r\n\t\tprivate class OKMenuSprite : Sprite {\r\n\t\t\tpublic OKMenuSprite() : base(GetPosition(), ScaledSpriteWidth, ScaledSpriteHeight, true) {\r\n\t\t\t\tInitialize(\"cs\\\\textbox\");\r\n\t\t\t\tLayer = 0.9f;\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\t\tbase.Initialize(textureKey); // Initialise any other existing values\r\n\t\t\t\t\r\n\t\t\t\tfloat yPosition = Position.Y + ((SPRITE_HEIGHT - OKMenuCursorSprite.SPRITE_HEIGHT + 8) * SECONDARY_SCALE * ContextScale) / 2;\r\n\r\n\t\t\t\tVector2 yesPosition = new Vector2(Position.X - (16 * SECONDARY_SCALE * ContextScale), yPosition);\r\n\t\t\t\tVector2 noPosition = new Vector2(Position.X + (68 * SECONDARY_SCALE * ContextScale), yPosition);\r\n\r\n\t\t\t\tcursor = new OKMenuCursorSprite(yesPosition, noPosition);\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\t\tbase.Update(updateAnimation);\r\n\r\n\t\t\t\tcursor.Update(updateAnimation);\r\n\r\n\t\t\t\tbool leftInput = GV.PeripheralIO.currentControlState.Left;\r\n\t\t\t\tbool rightInput = GV.PeripheralIO.currentControlState.Right;\r\n\r\n\t\t\t\tif (leftInput ^ rightInput) cursor.PointsToYes = leftInput;\r\n\t\t\t\t\r\n\t\t\t\tif (GV.PeripheralIO.CheckMultipleButtons(true, null, Buttons.A)\r\n\t\t\t\t || GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Enter))\r\n\t\t\t\t\tOkContextMenuComplete(cursor.PointsToYes);\r\n\t\t\t}\r\n\r\n\t\t\tpublic override void Draw() { cursor.Draw(); base.Draw(); }\r\n\r\n\t\t\tprivate static Vector2 GetPosition() {\r\n\t\t\t\treturn new Vector2(spriteRect.Right - (0.75f * ScaledSpriteWidth), spriteRect.Top - (0.5f * ScaledSpriteHeight));\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = new AnimationSequence(\r\n\t\t\t\t\t0, new Frame(310, 102, SPRITE_WIDTH, SPRITE_HEIGHT, 1, 1, 1)\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tprivate static int ScaledSpriteWidth { get { return (int)(SPRITE_WIDTH * SECONDARY_SCALE * ContextScale); } }\r\n\r\n\t\t\tprivate static int ScaledSpriteHeight { get { return (int)(SPRITE_HEIGHT * SECONDARY_SCALE * ContextScale); } }\r\n\r\n\t\t\tpublic const int SPRITE_WIDTH = 154, SPRITE_HEIGHT = 52;\r\n\r\n\t\t\tpublic static readonly float SECONDARY_SCALE = 0.35f;\r\n\r\n\t\t\tOKMenuCursorSprite cursor;\r\n\t\t}\r\n\r\n\t\tprivate class OKMenuCursorSprite : Sprite {\r\n\t\t\tpublic OKMenuCursorSprite(Vector2 yesPosition, Vector2 noPosition)\r\n\t\t\t\t: base(yesPosition, ScaledSpriteWidth, ScaledSpriteHeight, true) {\r\n\t\t\t\tInitialize(\"cs\\\\textbox\");\r\n\t\t\t\tYesPosition = yesPosition;\r\n\t\t\t\tNoPosition = noPosition;\r\n\t\t\t\tLayer = 1f;\t\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = new AnimationSequence(\r\n\t\t\t\t\t0, new Frame(224, 176, 32, 32, 1, 1, 1)\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t\t\tpublic const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 32;\r\n\r\n\t\t\tpublic static int ScaledSpriteWidth { get { return (int)(SPRITE_WIDTH * OKMenuSprite.SECONDARY_SCALE * ContextScale); } }\r\n\r\n\t\t\tpublic static int ScaledSpriteHeight { get { return (int)(SPRITE_HEIGHT * OKMenuSprite.SECONDARY_SCALE * ContextScale); } }\r\n\r\n\t\t\tprivate bool pointsToYes = true;\r\n\r\n\t\t\tprivate Vector2 YesPosition, NoPosition;\r\n\r\n\t\t\tpublic bool PointsToYes { get { return pointsToYes; }\r\n\t\t\t\tset {\r\n\t\t\t\t\tpointsToYes = value; // Set private value\r\n\t\t\t\t\tPosition = (value) ? YesPosition : NoPosition;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5867970585823059, "alphanum_fraction": 0.5941320061683655, "avg_line_length": 25.266666412353516, "blob_id": "765f2700d86d9563fa73340c8794b7cf6941845e", "content_id": "086675c3c609c66fd25b0d6f0b55949ccbf4a79b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4910, "license_type": "no_license", "max_line_length": 169, "num_lines": 180, "path": "/HollowAether/Lib/GAssets/Boundary/Shapes/IBRectangle.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial struct IBRectangle : IEquatable<IBRectangle>, IBoundary {\r\n\t\t#region builtin\r\n\t\tprivate static IBRectangle emptyRectangle = new IBRectangle();\r\n\r\n\t\tpublic float X;\r\n\t\tpublic float Y;\r\n\t\tpublic float Width;\r\n\t\tpublic float Height;\r\n\r\n\t\tpublic static IBRectangle Empty {\r\n\t\t\tget { return emptyRectangle; }\r\n\t\t}\r\n\r\n\t\tpublic float Left {\r\n\t\t\tget { return this.X; }\r\n\t\t}\r\n\r\n\t\tpublic float Right {\r\n\t\t\tget { return (this.X + this.Width); }\r\n\t\t}\r\n\r\n\t\tpublic float Top {\r\n\t\t\tget { return this.Y; }\r\n\t\t}\r\n\r\n\t\tpublic float Bottom {\r\n\t\t\tget { return (this.Y + this.Height); }\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle(float x, float y, float width, float height) {\r\n\t\t\tthis.X = x;\r\n\t\t\tthis.Y = y;\r\n\t\t\tthis.Width = width;\r\n\t\t\tthis.Height = height;\r\n\t\t}\r\n\r\n\t\tpublic static bool operator ==(IBRectangle a, IBRectangle b) {\r\n\t\t\treturn ((a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height));\r\n\t\t}\r\n\r\n\t\tpublic bool Contains(int x, int y) {\r\n\t\t\treturn ((((this.X <= x) && (x < (this.X + this.Width))) && (this.Y <= y)) && (y < (this.Y + this.Height)));\r\n\t\t}\r\n\r\n\t\tpublic bool Contains(Vector2 value) {\r\n\t\t\treturn ((((this.X <= value.X) && (value.X < (this.X + this.Width))) && (this.Y <= value.Y)) && (value.Y < (this.Y + this.Height)));\r\n\t\t}\r\n\r\n\t\tpublic bool Contains(Point value) {\r\n\t\t\treturn ((((this.X <= value.X) && (value.X < (this.X + this.Width))) && (this.Y <= value.Y)) && (value.Y < (this.Y + this.Height)));\r\n\t\t}\r\n\r\n\t\tpublic bool Contains(IBRectangle value) {\r\n\t\t\treturn ((((this.X <= value.X) && ((value.X + value.Width) <= (this.X + this.Width))) && (this.Y <= value.Y)) && ((value.Y + value.Height) <= (this.Y + this.Height)));\r\n\t\t}\r\n\r\n\t\tpublic static bool operator !=(IBRectangle a, IBRectangle b) {\r\n\t\t\treturn !(a == b);\r\n\t\t}\r\n\r\n\t\tprivate void Offset(Point offset) {\r\n\t\t\tX += offset.X;\r\n\t\t\tY += offset.Y;\r\n\t\t}\r\n\r\n\t\tprivate void Offset(int offsetX, int offsetY) {\r\n\t\t\tX += offsetX;\r\n\t\t\tY += offsetY;\r\n\t\t}\r\n\r\n\t\tpublic Vector2 Center {\r\n\t\t\tget {\r\n\t\t\t\treturn new Vector2((this.X + this.Width) / 2, (this.Y + this.Height) / 2);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Inflate(int horizontalValue, int verticalValue) {\r\n\t\t\tX -= horizontalValue;\r\n\t\t\tY -= verticalValue;\r\n\t\t\tWidth += horizontalValue * 2;\r\n\t\t\tHeight += verticalValue * 2;\r\n\t\t}\r\n\r\n\t\tpublic bool IsEmpty {\r\n\t\t\tget {\r\n\t\t\t\treturn ((((this.Width == 0) && (this.Height == 0)) && (this.X == 0)) && (this.Y == 0));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool Equals(IBRectangle other) {\r\n\t\t\treturn this == other;\r\n\t\t}\r\n\r\n\t\tpublic override bool Equals(object obj) {\r\n\t\t\treturn (obj is IBRectangle) ? this == ((IBRectangle)obj) : false;\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn string.Format(\"{{X:{0} Y:{1} Width:{2} Height:{3}}}\", X, Y, Width, Height);\r\n\t\t}\r\n\r\n\t\tpublic override int GetHashCode() {\r\n\t\t\treturn ((int)this.X ^ (int)this.Y ^ (int)this.Width ^ (int)this.Height);\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBRectangle r2) {\r\n\t\t\treturn !(r2.Left > Right\r\n\t\t\t\t\t || r2.Right < Left\r\n\t\t\t\t\t || r2.Top > Bottom\r\n\t\t\t\t\t || r2.Bottom < Top\r\n\t\t\t\t\t);\r\n\r\n\t\t}\r\n\r\n\t\tpublic void Intersects(ref IBRectangle value, out bool result) {\r\n\t\t\tresult = !(value.Left > Right\r\n\t\t\t\t\t || value.Right < Left\r\n\t\t\t\t\t || value.Top > Bottom\r\n\t\t\t\t\t || value.Bottom < Top\r\n\t\t\t\t\t);\r\n\r\n\t\t}\r\n\r\n\t\t/// <include file=\"doc\\Rectangle.uex\" path=\"docs/doc[@for=\"Rectangle.Union\"]/*\"> \r\n\t\t/// <devdoc>\r\n\t\t/// <para>\r\n\t\t/// Creates a rectangle that represents the union between a and\r\n\t\t/// b. \r\n\t\t/// </para>\r\n\t\t/// </devdoc> \r\n\t\tpublic static IBRectangle Union(IBRectangle a, IBRectangle b) {\r\n\t\t\tfloat x1 = Math.Min(a.X, b.X);\r\n\t\t\tfloat x2 = Math.Max(a.X + a.Width, b.X + b.Width);\r\n\t\t\tfloat y1 = Math.Min(a.Y, b.Y);\r\n\t\t\tfloat y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);\r\n\r\n\t\t\treturn new IBRectangle(x1, y1, x2 - x1, y2 - y1);\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tpublic IBRectangle(Rectangle rect) : this(rect.X, rect.Y, rect.Width, rect.Height) { }\r\n\r\n\t\tpublic IBRectangle(Vector2 topLeft, Vector2 bottomRight) : this(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y) { }\r\n\r\n\t\tpublic void Offset(Vector2 vect) {\r\n\t\t\tX += vect.X;\r\n\t\t\tY += vect.Y;\r\n\t\t}\r\n\r\n\t\tpublic void Offset(float X = 0, float Y = 0) {\r\n\t\t\tOffset(new Vector2(X, Y));\r\n\t\t}\r\n\r\n\t\tpublic static implicit operator Rectangle(IBRectangle self) {\r\n\t\t\treturn new Rectangle((int)self.X, (int)self.Y, (int)self.Width, (int)self.Height);\r\n\t\t}\r\n\r\n\t\tpublic static implicit operator IBRectangle(Rectangle self) {\r\n\t\t\treturn new IBRectangle(self.X, self.Y, self.Width, self.Height);\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle Container { get { return this; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7268389463424683, "alphanum_fraction": 0.7339960336685181, "avg_line_length": 39.91666793823242, "blob_id": "1fb5de3fd13d87ba88a0adbe17315c1e206c29ac", "content_id": "886c80853100eeffef9bd4a341d4dc53e3039d50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2517, "license_type": "no_license", "max_line_length": 130, "num_lines": 60, "path": "/HollowAether/Lib/Global/GlobalVars/TextureCreation.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\r\n\t\tpublic static class TextureCreation {\r\n\t\t\t/// <summary>Builds a monochramatic texture of a given color</summary>\r\n\t\t\t/// <param name=\"color\">Color of texture</param>\r\n\t\t\t/// <returns>Newly defined texture matching specifications</returns>\r\n\t\t\tpublic static Texture2D GenerateBlankTexture(Color color, int width=1, int height=1) {\r\n\t\t\t\tTexture2D texture = new Texture2D(hollowAether.GraphicsDevice, width, height);\r\n\r\n\t\t\t\ttexture.SetData<Color>((from X in Enumerable.Range(0, width * height) select color).ToArray());\r\n\r\n\t\t\t\treturn texture; // Generates and returns texture of a single color to caller.\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Builds a monochramatic texture of a given color determined by RGB valued</summary>\r\n\t\t\t/// <param name=\"red\">Red Hue</param> <param name=\"blue\">Blue Hue</param>\r\n\t\t\t/// <param name=\"green\">Green Hue</param> <param name=\"alpha\">Transparency</param>\r\n\t\t\t/// <returns>Newly defined texture matching specifications</returns>\r\n\t\t\tpublic static Texture2D GenerateBlankTexture(float red, float green, float blue, float alpha = 1f, int width=1, int height=1) {\r\n\t\t\t\treturn GenerateBlankTexture(new Color(red, green, blue, alpha), width, height);\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary>Builds a monochramatic texture of a given color determined by RGB valued</summary>\r\n\t\t\t/// <param name=\"red\">Red Hue</param> <param name=\"blue\">Blue Hue</param>\r\n\t\t\t/// <param name=\"green\">Green Hue</param> <param name=\"alpha\">Transparency</param>\r\n\t\t\t/// <returns>Newly defined texture matching specifications</returns>\r\n\t\t\tpublic static Texture2D GenerateBlankTexture(int red, int green, int blue, int alpha = 255, int width=1, int height=1) {\r\n\t\t\t\treturn GenerateBlankTexture(new Color(red, green, blue, alpha), width=1, height=1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6788725256919861, "alphanum_fraction": 0.6844713091850281, "avg_line_length": 35.35817337036133, "blob_id": "375ecef0a4220a880b9a81521842e9bfd3c903b0", "content_id": "e2ee7c80a617e1793c5d9926c6fb388b748ff81d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15541, "license_type": "no_license", "max_line_length": 136, "num_lines": 416, "path": "/HollowAether/Main.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing System.Threading;\r\nusing System.Runtime.InteropServices;\r\nusing System.Text.RegularExpressions;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib;\r\nusing HollowAether.Text;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Forms;\r\nusing HollowAether.Lib.InputOutput;\r\nusing MapZone = HollowAether.Lib.MapZone;\r\nusing CS = HollowAether.Text.ColoredString;\r\nusing U = HollowAether.Lib.Misc.CommandLineHelp;\r\n#endregion\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether {\r\n\tpublic static class Program {\r\n\t\t[DllImport(\"user32.dll\", SetLastError = true)]\r\n\t\tstatic extern bool SetProcessDPIAware();\r\n\r\n#if WINDOWS || LINUX\r\n\t\t[STAThread] static void Main(params String[] args) {\r\n\t\t\tApplication.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);\r\n\t\t\tif (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware(); // Dots per Inch\r\n\t\t\t// Builds Generic Application Preferences; Must Come Before First Object Creation //\r\n\r\n\t\t\ttry { ParseCommandLine(args); } catch (Exception e) {\r\n\t\t\t\t// Run A New Error Message Form With All Found Exceptions\r\n\r\n\t\t\t\tif (throwException) throw;\r\n\r\n\t\t\t\tif (GlobalVars.hollowAether.god != null)\r\n\t\t\t\t\tGlobalVars.hollowAether.god.EndGame();\r\n\r\n\t\t\t\tErrorMessage form = new ErrorMessage(e);\r\n\t\t\t\t\r\n\t\t\t\twhile (e.InnerException != null) {\r\n\t\t\t\t\tform.AddException(e.InnerException);\r\n\t\t\t\t\te = e.InnerException; // add inner\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tApplication.Run(form);\r\n\t\t\t}\r\n\t\t}\r\n#else\r\n\t\t#region NonCompatibleOSHandler\r\n\t\t[STAThread] static void Main() {\r\n\t\t\tString incorrectOS = \"Sorry, HollowAether Isn't Compatible With Your Current OS :(\";\r\n\t\t\tMessageBox.Show(incorrectOS, \"OS Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\r\n\t\t}\r\n\t\t#endregion\r\n#endif\r\n\r\n\t\tprivate static void ParseCommandLine(String[] args) {\r\n\t\t\tif (args.Length == 0) { /*RunGame();*/ return; } // If no args given then run the game and return to caller\r\n\r\n\t\t\tString str = (from X in args select (X.Count(N => N == ' ') >= 1) ? $\"\\\"{X}\\\"\" : X).Aggregate((Y, Z) => $\"{Y} {Z}\");\r\n\t\t\t// Parses through every word in args and tries to re-interpret them as they would appear if passed from the command line\r\n\r\n\t\t\tDictionary<String, String[]> parsedCLArguments = StartUpMethods.InputParserScriptInterpreter(str); // parses CLA\r\n\t\t\t// bool runGameAfterArgs = false, runLevelEditorAfterArgs = false, dontRun = false; // arg interpretor bools\r\n\r\n\t\t\t#region Implement\r\n\t\t\tforeach (String flag in parsedCLArguments.Keys) {\r\n\t\t\t\tswitch (flag.ToLower()) {\r\n\t\t\t\t\tcase \"\\0\": // default args\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region RunGame\r\n\t\t\t\t\tcase \"r\":\r\n\t\t\t\t\tcase \"run\":\r\n\t\t\t\t\tcase \"rungame\":\r\n\t\t\t\t\tcase \"run_game\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\trunGameAfterArgs = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region LevelEditor\r\n\t\t\t\t\tcase \"le\":\r\n\t\t\t\t\tcase \"leveleditor\":\r\n\t\t\t\t\tcase \"level_editor\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\trunLevelEditorAfterArgs = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region DontRun\r\n\t\t\t\t\tcase \"dr\":\r\n\t\t\t\t\tcase \"dontrun\":\r\n\t\t\t\t\tcase \"dont_run\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tdontRun = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region runZone\r\n\t\t\t\t\tcase \"rz\":\r\n\t\t\t\t\tcase \"runzone\":\r\n\t\t\t\t\tcase \"run_zone\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\trunZoneAfterArgs = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region EncryptFile\r\n\t\t\t\t\tcase \"ef\":\r\n\t\t\t\t\tcase \"encryptfile\":\r\n\t\t\t\t\tcase \"encrypt_file\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tEncryptFile(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region EncryptDirectory\r\n\t\t\t\t\tcase \"ed\":\r\n\t\t\t\t\tcase \"encryptdir\":\r\n\t\t\t\t\tcase \"encrypt_dir\":\r\n\t\t\t\t\tcase \"encryptdirectory\":\r\n\t\t\t\t\tcase \"encrypt_directory\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tEncryptDirectory(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region DecryptFile\r\n\t\t\t\t\tcase \"df\":\r\n\t\t\t\t\tcase \"decryptfile\":\r\n\t\t\t\t\tcase \"decrypt_file\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tDecryptFile(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region DecryptDirectory\r\n\t\t\t\t\tcase \"dd\":\r\n\t\t\t\t\tcase \"decryptdir\":\r\n\t\t\t\t\tcase \"decrypt_dir\":\r\n\t\t\t\t\tcase \"decryptdirectory\":\r\n\t\t\t\t\tcase \"decrypt_directory\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tDecryptDirectory(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region Map\r\n\t\t\t\t\tcase \"m\":\r\n\t\t\t\t\tcase \"map\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tSetMap(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region FullScreen\r\n\t\t\t\t\tcase \"f\":\r\n\t\t\t\t\tcase \"fullscreen\":\r\n\t\t\t\t\tcase \"full_screen\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tSetFullScreen();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region Windowed\r\n\t\t\t\t\tcase \"w\":\r\n\t\t\t\t\tcase \"windowed\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tSetWindowed();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region 60FPS\r\n\t\t\t\t\tcase \"60fps\":\r\n\t\t\t\t\tcase \"fps60\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tGlobalVars.MonoGameImplement.framesPerSecond = 60;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region 30FPS\r\n\t\t\t\t\tcase \"30fps\":\r\n\t\t\t\t\tcase \"fps30\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tGlobalVars.MonoGameImplement.framesPerSecond = 30;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region 20FPS\r\n\t\t\t\t\tcase \"20fps\":\r\n\t\t\t\t\tcase \"fps20\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tGlobalVars.MonoGameImplement.framesPerSecond = 20;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region 15FPS\r\n\t\t\t\t\tcase \"15fps\":\r\n\t\t\t\t\tcase \"fps15\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tGlobalVars.MonoGameImplement.framesPerSecond = 15;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region Zoom\r\n\t\t\t\t\tcase \"z\":\r\n\t\t\t\t\tcase \"zoom\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tSetZoom(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region SetZone\r\n\t\t\t\t\tcase \"sz\":\r\n\t\t\t\t\tcase \"setzone\":\r\n\t\t\t\t\tcase \"set_zone\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tSetZone(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region ThrowException\r\n\t\t\t\t\tcase \"te\":\r\n\t\t\t\t\tcase \"throwexception\":\r\n\t\t\t\t\tcase \"throw_exception\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tthrowException = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region EncryptPrint\r\n\t\t\t\t\tcase \"ep\":\r\n\t\t\t\t\tcase \"encryptprint\":\r\n\t\t\t\t\tcase \"encrypt_print\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tEncryptEcho(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region DecryptPrint\r\n\t\t\t\t\tcase \"dp\":\r\n\t\t\t\t\tcase \"decryptprint\":\r\n\t\t\t\t\tcase \"decrypt_print\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tDecryptEcho(parsedCLArguments[flag]);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#region Help\r\n\t\t\t\t\tcase \"h\":\r\n\t\t\t\t\tcase \"help\":\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t\t\tPrintHelp();\r\n\t\t\t\t\t\tdontRun = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tConsole.WriteLine($\"CLIWarning: Flag '{flag}' Not Found\");\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\t\t\t\r\n\t\t\tif (dontRun) return; // don't run takes command precedence when passed from the command line\r\n\r\n\t\t\tint C = new int[] { runZoneAfterArgs ? 1 : 0, runGameAfterArgs ? 1 : 0, runLevelEditorAfterArgs ? 1 : 0 }.Aggregate((a, b) => a + b);\r\n\t\t\t// Check whether more then one of the necessary HollowAether run bools is true by aggregating them using an integer\r\n\t\t\t\r\n\t\t\tif (C >= 2) { throw new HollowAetherException(\"More Then One Necessary HollowAether Argument Passed\"); }\r\n\t\t\t\r\n\t\t\tif (C == 0 || runGameAfterArgs) {\r\n\t\t\t\tRunGame();\r\n\t\t\t} else if (runLevelEditorAfterArgs) {\r\n\t\t\t\tApplication.Run(new Editor(GlobalVars.FileIO.DefaultMapPath));\r\n\t\t\t} else { // RunZoneAfterArgs\r\n\t\t\t\t//RunZone(parsedCLArguments[]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t#region CommandLineImplementers\r\n\t\t/// <summary>Runs HollowAether Game</summary>\r\n\t\tprivate static void RunGame() {\r\n\t\t\tGlobalVars.hollowAether.Run();\r\n\t\t}\r\n\r\n\t\t/// <summary>Set's Hollow Aether Game To Full Screen</summary>\r\n\t\tprivate static void InitializeFullScreen() {\r\n\t\t\tGlobalVars.MonoGameImplement.FullScreen = true;\r\n\t\t}\r\n\r\n\t\t/// <summary>Decrypts A Given File Using OneTimePad</summary>\r\n\t\tprivate static void DecryptFile(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new DecryptFileException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 2) throw new DecryptFileException(\"Too Many Args Given\");\r\n\r\n\t\t\tString path = commandLineArgs[0], tar = (commandLineArgs.Length == 2) ? commandLineArgs[1] : null;\r\n\t\t\tif (!InputOutputManager.FileExists(path)) throw new DecryptFileArgNotFoundException(path);\r\n\r\n\t\t\tif (String.IsNullOrWhiteSpace(tar)) // Sets target file when no given target file is passed\r\n\t\t\t\ttar = InputOutputManager.ChangeExtension(path, \"D\"+InputOutputManager.GetExtension(path).Replace(\".\",\"\"));\r\n\r\n\t\t\tInputOutputManager.WriteFile(tar, InputOutputManager.ReadEncryptedFile(path, GlobalVars.Encryption.oneTimePad));\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts A Given File Using OneTimePad</summary>\r\n\t\tprivate static void EncryptFile(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new EncryptFileException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 2) throw new EncryptFileException(\"Too Many Args Given\");\r\n\r\n\t\t\tString path = commandLineArgs[0], tar = (commandLineArgs.Length == 2) ? commandLineArgs[1] : null;\r\n\t\t\tif (!InputOutputManager.FileExists(path)) throw new EncryptFileArgNotFoundException(path);\r\n\t\t\t\r\n\t\t\tif (String.IsNullOrWhiteSpace(tar)) // Sets target file when no given target file is passed\r\n\t\t\t\ttar = InputOutputManager.ChangeExtension(path, \"E\"+InputOutputManager.GetExtension(path).Replace(\".\",\"\"));\r\n\r\n\t\t\tInputOutputManager.WriteEncryptedFile(tar, InputOutputManager.ReadFile(path), GlobalVars.Encryption.oneTimePad);\r\n\t\t}\r\n\r\n\t\t/// <summary>Decrypts all files including sub files in a given directory using OneTimePad</summary>\r\n\t\tprivate static void DecryptDirectory(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new DecryptDirectoryException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 2) throw new DecryptDirectoryException(\"Too Many Args Given\");\r\n\r\n\t\t\tString path = commandLineArgs[0], tar = (commandLineArgs.Length == 2) ? commandLineArgs[1] : null;\r\n\t\t\tif (!InputOutputManager.DirectoryExists(path)) throw new DecryptDirectoryArgNotFoundException(path);\r\n\r\n\t\t\tif (String.IsNullOrWhiteSpace(tar)) tar = InputOutputManager.Join(path, \"Decrypted\");\r\n\t\t\tInputOutputManager.SequenceConstruct(tar); // Construct all folders upto target\r\n\t\t\t\r\n\t\t\tforeach (String sysPath in StartUpMethods.SystemParserScriptInterpreter(path)) {\r\n\t\t\t\tString truncatedPath = sysPath.Replace(path + \"\\\\\", \"\"); // just path after\r\n\t\t\t\tString containingDirs = InputOutputManager.GetDirectoryName(truncatedPath);\r\n\t\t\t\tString fileTar = InputOutputManager.Join(tar, truncatedPath); // store in tar folder\r\n\t\t\t\tInputOutputManager.SequenceConstruct(InputOutputManager.GetDirectoryName(fileTar));\r\n\r\n\t\t\t\tDecryptFile(new String[] { sysPath, fileTar }); // Decrypt given file\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Encrypts all files including sub files in a given directory using OneTimePad</summary>\r\n\t\tprivate static void EncryptDirectory(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new DecryptDirectoryException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 2) throw new DecryptDirectoryException(\"Too Many Args Given\");\r\n\r\n\t\t\tString path = commandLineArgs[0], tar = (commandLineArgs.Length == 2) ? commandLineArgs[1] : null;\r\n\t\t\tif (!InputOutputManager.DirectoryExists(path)) throw new DecryptDirectoryArgNotFoundException(path);\r\n\r\n\t\t\tif (String.IsNullOrWhiteSpace(tar)) tar = InputOutputManager.Join(path, \"Encrypted\");\r\n\t\t\tInputOutputManager.SequenceConstruct(tar); // Construct all folders upto target\r\n\r\n\t\t\tforeach (String sysPath in StartUpMethods.SystemParserScriptInterpreter(path)) {\r\n\t\t\t\tString truncatedPath = sysPath.Replace(path + \"\\\\\", \"\"); // just path after\r\n\t\t\t\tString containingDirs = InputOutputManager.GetDirectoryName(truncatedPath);\r\n\t\t\t\tString fileTar = InputOutputManager.Join(tar, truncatedPath); // store in tar folder\r\n\t\t\t\tInputOutputManager.SequenceConstruct(InputOutputManager.GetDirectoryName(fileTar));\r\n\r\n\t\t\t\tEncryptFile(new String[] { sysPath, fileTar }); // Decrypt given file\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Set's map file used by program</summary>\r\n\t\tprivate static void SetMap(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new SetGameZoomException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 1) throw new SetGameZoomException(\"Too Many Args Given\");\r\n\r\n\t\t\t/*if (!InputOutputManager.FileExists(commandLineArgs[0]))\r\n\t\t\t\tthrow new MapNotFoundException(commandLineArgs[0]);*/\r\n\r\n\t\t\tGlobalVars.FileIO.DefaultMapPath = commandLineArgs[0];\r\n\t\t}\r\n\r\n\t\t/// <summary>Set's zoom used by hollow aether</summary>\r\n\t\tprivate static void SetZoom(String[] commandLineArgs) {\r\n\t\t\tif (commandLineArgs.Length == 0) throw new SetGameZoomException(\"No Arguments Given\");\r\n\t\t\tif (commandLineArgs.Length > 1) throw new SetGameZoomException(\"Too Many Args Given\");\r\n\r\n\t\t\ttry { GlobalVars.MonoGameImplement.gameZoom = float.Parse(commandLineArgs[0]); } catch (FormatException e) {\r\n\t\t\t\tthrow new SetGameZoomArgumentIncorrectTypeException(commandLineArgs[0], e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Makes game full screen</summary>\r\n\t\tprivate static void SetFullScreen() { GlobalVars.MonoGameImplement.FullScreen = true; }\r\n\r\n\t\t/// <summary>Makes game windowed</summary>\r\n\t\tprivate static void SetWindowed() { GlobalVars.MonoGameImplement.FullScreen = false; }\r\n\r\n\t\t/// <summary>Set's the zone index in the current zone file to target with the game</summary>\r\n\t\tprivate static void SetZone(String[] args) {\r\n\t\t\tif (!runGameAfterArgs && !runZoneAfterArgs) Console.WriteLine(\"CLIWarning: Setting Zone When RunGame Hasn't Been Set\");\r\n\t\t\tif (args.Length == 0) throw new HollowAetherException($\"SetZone command has no args given to it\");\r\n\r\n\t\t\tString mergedArgs = args.Aggregate((a, b) => $\"{a} {b}\"); // compile args to single string of desired length\t\t\t\t\t\t\t\t\t\t\t \r\n\r\n\t\t\ttry { argZoneIndex = Parser.Vector2Parser(mergedArgs); } catch (Exception e) {\r\n\t\t\t\tthrow new HollowAetherException($\"Couldn't convert given argument '{mergedArgs}' to a Vector2 Value\", e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void EncryptEcho(String[] args) {\r\n\t\t\tif (args.Length == 0) throw new HollowAetherException($\"Encrypt Echo command has no args given to it\");\r\n\t\t\tif (!InputOutputManager.FileExists(args[0])) throw new System.IO.FileNotFoundException(args[0]);\r\n\r\n\t\t\tConsole.WriteLine(GlobalVars.Encryption.oneTimePad.Encrypt(InputOutputManager.ReadFile(args[0])));\r\n\t\t}\r\n\r\n\t\tpublic static void DecryptEcho(String[] args) {\r\n\t\t\tif (args.Length == 0) throw new HollowAetherException($\"Decrypt Echo command has no args given to it\");\r\n\t\t\tif (!InputOutputManager.FileExists(args[0])) throw new System.IO.FileNotFoundException(args[0]);\r\n\r\n\t\t\tConsole.WriteLine(InputOutputManager.ReadEncryptedFile(args[0], GlobalVars.Encryption.oneTimePad));\r\n\t\t}\r\n\r\n\t\tprivate static void RunZone(String[] args) {\r\n\t\t\tConsole.WriteLine(\"Run zone not yet done\");\r\n\t\t}\r\n\r\n\t\t/// <summary>Prints help in nice pretty colors</summary>\r\n\t\tprivate static void PrintHelp() {\r\n\t\t\tforeach (Object str in U.GenerateHelpString()) {\r\n\t\t\t\tif (str is String) Console.Write(str);\r\n\t\t\t\telse ((ColoredString)str).Write();\r\n\t\t\t}\r\n\r\n\t\t\tConsole.WriteLine(); // Leave line break after string\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Bool indicating whether or not to run anything</summary>\r\n\t\tprivate static bool dontRun = false;\r\n\r\n\t\t/// <summary>Bool indicating whether to not catch exceptions and let them be thrown</summary>\r\n\t\tprivate static bool throwException = false;\r\n\r\n\t\t/// <summary>Bool indicating whether to run the game window</summary>\r\n\t\tprivate static bool runGameAfterArgs = false;\r\n\r\n\t\t/// <summary>Bool indicating whether to uns a single zone</summary>\r\n\t\tprivate static bool runZoneAfterArgs = false;\r\n\r\n\t\t/// <summary>Bool indicating whether to run Game level editor</summary>\r\n\t\tprivate static bool runLevelEditorAfterArgs = false;\r\n\r\n\t\tpublic static Vector2? argZoneIndex = null;\r\n\t\tpublic static String argZoneFile; // When just running a zone\r\n\t}\r\n}" }, { "alpha_fraction": 0.6867193579673767, "alphanum_fraction": 0.6966606974601746, "avg_line_length": 35.36190414428711, "blob_id": "df3777a78712937dc994a0b5a671accd4e93382e", "content_id": "4e2569408bdb693d0b1dbd8d827199fce543317f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 134, "num_lines": 105, "path": "/HollowAether/Lib/Global/GameWindow/Home.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tstatic class Home {\r\n\t\tstatic Home() { Reset(); }\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false);\r\n\r\n\t\t\tbuttons.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End(); \r\n\t\t}\r\n\r\n\t\tprivate static void BuildButtonPositions() {\r\n\t\t\tint width = GV.Variables.windowWidth, height = GV.Variables.windowHeight; // Store window dimensions\r\n\t\t\tfloat buttonWidth = (Button.SPRITE_WIDTH * BUTTON_SCALE) + 55, buttonHeight = Button.SPRITE_HEIGHT * BUTTON_SCALE;\r\n\r\n\t\t\tVector2 position = new Vector2((width - buttonWidth) / 2, height - (3 * (buttonHeight + 25))); // Default button posiition\r\n\t\t\tVector2 position2 = position + new Vector2(0, buttonHeight + 25); // Secondary button position, below previous\r\n\t\t\tVector2 position3 = position + new Vector2(0, 2 * (buttonHeight + 25)); // Tertiary button position, again below previous\r\n\r\n\t\t\tTextButton startButton = new TextButton(position, \"Start\", (int)buttonWidth, (int)buttonHeight) { Layer = 0.4f };\r\n\t\t\tTextButton settingsButton = new TextButton(position2, \"Settings\", (int)buttonWidth, (int)buttonHeight) { Layer = 0.4f };\r\n\t\t\tTextButton exitButton = new TextButton(position3, \"Exit\", (int)buttonWidth, (int)buttonHeight) { Layer = 0.4f };\r\n\r\n\t\t\tstartButton.Click += (self) => {\r\n\t\t\t\tGV.MonoGameImplement.gameState = GameState.SaveLoad;\r\n\t\t\t\tSaveLoad.WaitForInputToBeRemoved = true;\r\n\t\t\t\tSaveLoad.Reset(); // Reset new game state\r\n\t\t\t};\r\n\r\n\t\t\tsettingsButton.Click += (self) => {\r\n\t\t\t\tGV.MonoGameImplement.gameState = GameState.Settings;\r\n\t\t\t\tSettings.WaitForInputToBeRemoved = true;\r\n\t\t\t\tSettings.Reset(); // Reset new game state\r\n\t\t\t};\r\n\r\n\t\t\texitButton.Click += (self) => {\r\n\t\t\t\tGV.hollowAether.god.EndGame();\r\n\t\t\t};\r\n\r\n\t\t\tbuttons = new ButtonList(0, 3, startButton, settingsButton, exitButton);\r\n\t\t}\r\n\t\r\n\t\tpublic static void Update() {\r\n\t\t\tbuttons.Update(false);\r\n\r\n\t\t\tGV.PeripheralIO.ControlState controlState = GV.PeripheralIO.currentControlState;\r\n\r\n\t\t\tif (inputTimeout > 0) {\r\n\t\t\t\tif (controlState.KeyboardNotPressed() && controlState.GamepadNotPressed())\r\n\t\t\t\t\tinputTimeout = 0; // Remove input time out, user can input again\r\n\t\t\t\telse inputTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t} else {\r\n\t\t\t\tbool altPressed = GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.LeftAlt, Keys.RightAlt);\r\n\r\n\t\t\t\tif (controlState.KeyboardNotPressed() && controlState.GamepadNotPressed() || altPressed)\r\n\t\t\t\t\treturn; // No input detected, skip forward to next update call\r\n\r\n\t\t\t\tif (controlState.Down || controlState.Right) buttons.MoveToNextButton();\r\n\t\t\t\telse if (controlState.Up || controlState.Left) buttons.MoveToPreviousButton();\r\n\r\n\t\t\t\telse if (controlState.Gamepad.Jump || GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.Enter))\r\n\t\t\t\t\tbuttons.ActiveButton.InvokeClick(); // If any of the above inputs have been entered then execute\r\n\r\n\t\t\t\tinputTimeout = 300; // Dont accept input for given value in milleseconds\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() {\r\n\t\t\tBuildButtonPositions(); // Set the position of any buttons used by this class\r\n\r\n\t\t\ttry {\r\n\t\t\t\tGV.MonoGameImplement.background = GV.MonoGameImplement.backgrounds[\"GW_HOME_SCREEN\"];\r\n\t\t\t} catch {\r\n\t\t\t\tConsole.WriteLine(\"Failed\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void FullScreenReset(bool isFullScreen) {\r\n\t\t\tif (GV.MonoGameImplement.gameState == GameState.Home) Reset();\r\n\t\t}\r\n\r\n\t\tprivate const float BUTTON_SCALE = 3.5f;\r\n\r\n\t\tprivate static int inputTimeout = 0;\r\n\r\n\t\tprivate static ButtonList buttons;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7850098609924316, "alphanum_fraction": 0.7850098609924316, "avg_line_length": 26.97142791748047, "blob_id": "e2f90843585ed3c5e262f2ebcceb62f4b532106f", "content_id": "66b4632477ee11a42ed266aa576e3a8b83810981", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 99, "num_lines": 35, "path": "/HollowAether/Lib/Global/GlobalVars/Encryption.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class Encryption {\r\n\t\t\tpublic static String encryptionKey = \"Rasetsu\"; // used to encrypt ingoing and outgoing files\r\n\t\t\tpublic static OneTimePad oneTimePad = new OneTimePad(encryptionKey); // new pad for manipulation\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7181872725486755, "alphanum_fraction": 0.7181872725486755, "avg_line_length": 34.21739196777344, "blob_id": "2b51bc3c25192712ebeea8ca50aff419429aca25", "content_id": "39e3483442a09fc10e51f441392a83bd62bc9854", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3334, "license_type": "no_license", "max_line_length": 106, "num_lines": 92, "path": "/HollowAether/Lib/Entity/EntityAttributes.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Converters = HollowAether.Lib.InputOutput.Parsers.Converters;\r\n#endregion\r\n\r\nnamespace HollowAether {\r\n\tpublic class EntityAttribute : Object, ICloneable {\r\n\t\tpublic EntityAttribute(Type attributeType, bool isReadOnly=false) {\r\n\t\t\tIsReadOnly = isReadOnly; // Store whether attribute can be altered\r\n\t\t\tType = attributeType; // Store what type this entity attribute aceepts\r\n\t\t}\r\n\r\n\t\tpublic EntityAttribute(object defaultValue, Type attributeType, bool isReadOnly=false) \r\n\t\t\t: this(attributeType, isReadOnly) { SetAttribute(defaultValue); }\r\n\r\n\t\tpublic object Clone() { return (EntityAttribute)MemberwiseClone(); }\r\n\r\n\t\tpublic object GetValue() {\r\n\t\t\tif (!this.IsAssigned) throw new EntityAttributeUnassignedValueRetrievalException(); else {\r\n\t\t\t\treturn value; // Value has been assigned so return stored value.\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Returns Value if Value isn't Asset else Return Asset Value</summary>\r\n\t\t/// <returns>Actual Value Represented By Entity Attribute.</returns>\r\n\t\tpublic object GetActualValue() {\r\n\t\t\tobject value = GetValue(); // Gets actual value or assets ref. Also checks for value not assigned etc. \r\n\t\t\treturn (this.IsAssetReference) ? (value as Asset).asset : value; // Get actual value pointed to by attr\r\n\t\t}\r\n\r\n\t\tpublic void Delete() {\r\n\t\t\tif (IsReadOnly) throw new EntityAttributeReadOnlyDeletionException();\r\n\t\t\tvalue = null; // Erase Value Of Entity Attribute By Setting To Null.\r\n\t\t}\r\n\r\n\t\tpublic void SetAttribute(object newValue) {\r\n\t\t\tif (IsAssigned && IsReadOnly) throw new EntityAttributeReadOnlyAssignmentAttemptException();\r\n\r\n\t\t\tif (newValue != null) {\r\n\t\t\t\tif (newValue is Asset) { // Is Asset Reference\r\n\t\t\t\t\tif (!(newValue as Asset).TypesMatch(this.Type))\r\n\t\t\t\t\t\tthrow new EntityAttributeInvalidTypeAssignmentException((newValue as Asset).assetType, Type);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (!GV.Misc.DoesExtend(newValue.GetType(), this.Type))\r\n\t\t\t\t\t\tthrow new EntityAttributeInvalidTypeAssignmentException(newValue.GetType(), Type);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvalue = newValue; // If no exception thrown then new value is a valid value\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic string ToFileContents(bool throwExceptionIfUnassigned=true) {\r\n\t\t\tif (IsAssigned) {\r\n\t\t\t\treturn Converters.ValueToString(Type, value);\r\n\t\t\t\t/*if (IsAssetReference) return $\"[{(value as Asset).assetID}]\"; else {\r\n\t\t\t\t\treturn Converters.ValueToString(Type, value);\r\n\t\t\t\t}*/\r\n\t\t\t} else {\r\n\t\t\t\tif (!throwExceptionIfUnassigned) return String.Empty; else {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Cannot Convert Unassigned Value\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool IsAssetReference { get { return value is Asset; } }\r\n\r\n\t\tpublic bool IsAssigned { get { return value != null; } }\r\n\r\n\t\tpublic object Value { get { return value; } set { SetAttribute(value); } }\r\n\r\n\t\tpublic readonly bool IsReadOnly;\r\n\t\tpublic readonly Type Type;\r\n\t\tprivate object value = null;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6967628002166748, "alphanum_fraction": 0.7056145668029785, "avg_line_length": 38.34693908691406, "blob_id": "78e9aea3ef37edd02d0b7fb7b3d893d39349842d", "content_id": "e3c370b3a62b2acd973bd6a7ef467ca1ce1d56c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7910, "license_type": "no_license", "max_line_length": 127, "num_lines": 196, "path": "/HollowAether/Lib/GAssets/Living/Enemy.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic abstract class Enemy : VolatileBodySprite {\r\n\t\tpublic Enemy(Vector2 position, int width, int height, int level, bool animationRunning) \r\n\t\t\t: base(position, width, height, animationRunning) {\r\n\t\t\tLevel = level; // Store level to instance\r\n\t\t\tLayer = 0.45f;\r\n\r\n\t\t\tInitializeVolatility(VolatilityType.Other, new ImplementVolatility(ReadyToDelete));\r\n\r\n\t\t\tKilled += Enemy_Killed;\r\n\r\n\t\t\tVolatilityManager.Deleting += () => { Console.WriteLine($\"Deleted {SpriteID}\"); };\r\n\t\t}\r\n\r\n\t\tprivate void Enemy_Killed(Enemy obj) {\r\n\t\t\tforeach (int X in Enumerable.Range(1, GV.Variables.random.Next(1, 5))) {\r\n\t\t\t\tint spanIndex = GV.Variables.random.Next(0, 2); // Point Span Enum Index\r\n\t\t\t\tBurstPoint.PointSpan span = (BurstPoint.PointSpan)spanIndex;\r\n\r\n\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(new BurstPoint(Position, span));\r\n\t\t\t}\r\n\r\n\t\t\t//throw new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tprivate void VolatilityManager_Deleting() {\r\n\t\t\tforeach (int X in Enumerable.Range(1, GV.Variables.random.Next(1, 5))) {\r\n\t\t\t\tint spanIndex = GV.Variables.random.Next(0, 2); // Point Span Enum Index\r\n\t\t\t\tBurstPoint.PointSpan span = (BurstPoint.PointSpan)spanIndex;\r\n\r\n\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(new BurstPoint(Position, span));\r\n\t\t\t}\r\n\r\n\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(new BurstPoint(Position, BurstPoint.PointSpan.Medium));\r\n\r\n\t\t\t//throw new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey); // Initialise base sprite features. Ensures any base logic is properly implemented\r\n\r\n\t\t\tDamaged = (self, amount) => {\r\n\t\t\t\tif (self.Alive) {\r\n\t\t\t\t\tint damage = GV.BasicMath.Clamp(amount, 0, Health); // Clamp damage to ensure it's always less then the health of enemy\r\n\r\n\t\t\t\t\t#region EffectCreation\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(new HitSprite(Position, 16, 16, HitSprite.HitType.Red)); // Make hit sprite\r\n\t\t\t\t\tFX.ValueChangedEffect.FlickerColor fxColor = FX.ValueChangedEffect.FlickerColor.White; // Color for effect sprite to draw\r\n\t\t\t\t\tGV.MonoGameImplement.additionBatch.AddRangeNameless(FX.ValueChangedEffect.CreateStatic(Position, -damage, 1000, fxColor));\r\n\t\t\t\t\t#endregion\r\n\r\n\t\t\t\t\t#region DamageTaking\r\n\t\t\t\t\tself.healthBar.TakeDamage(damage); // Take health from current enemy\r\n\t\t\t\t\tif (Health == 0) Killed(this); // If was killed, execute event handler\r\n\t\t\t\t\tinvincibilityTime = 750; // Make unable to be hurt for 0.75 seconds\r\n\t\t\t\t\t#endregion\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\tKilled += (self) => { RecursiveKilledHitEffectDisplayer(GV.Variables.random.Next(5, 15)); };\r\n\r\n\t\t\thealthBar = new EnemyHealthBar(GetHealthBarInitialPosition(), Width, EnemyHealthBar.DEFAULT_HEIGHT, GetHealth());\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw(); // Draw actual sprite instance\r\n\r\n\t\t\tif (Alive && Health != healthBar.MaxHealth) {\r\n\t\t\t\thealthBar.Draw(); // Draw health bar to game\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t/// <summary>Basically sets it up so a set number of sprites are generated one after the other recursively</summary>\r\n\t\t/// <param name=\"count\">Number of FX sprites to generate. By default it is 5 but can accept any value</param>\r\n\t\tprivate void RecursiveKilledHitEffectDisplayer(int count=5) {\r\n\t\t\tif (count >= 0) { // So long as number of sprites to display is not -ve\r\n\t\t\t\tint hsDimensions = 18; // Size of hit sprite which is about to be displayed by method\r\n\r\n\t\t\t\tVector2 position = Position /*- new Vector2(hsDimensions)*/ + new Vector2(\r\n\t\t\t\t\tGV.Variables.random.Next(Width), GV.Variables.random.Next(Height)\r\n\t\t\t\t); // Position of newly defined hit sprite, randomised to enemy sprite rect\r\n\r\n\t\t\t\tHitSprite hit = new HitSprite(position, hsDimensions, hsDimensions, HitSprite.HitType.Blue);\r\n\t\t\t\t// Creates new hit sprite with desired dimensions and of type HitSprite.HitType.Blue\r\n\r\n\t\t\t\thit.VolatilityManager.Deleting += () => { RecursiveKilledHitEffectDisplayer(count - 1); };\r\n\t\t\t\t// When the volatile hit sprite is being removed/deleted, call this method again to create new\r\n\r\n\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(hit); // Add effect sprite to store\r\n\t\t\t} else deathFXSpritesComplete = true; // Enemy ready to delete now\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Also takes care of volatility\r\n\r\n\t\t\tif (CanGenerateHealth && Alive && Health != healthBar.MaxHealth && false) {\r\n\t\t\t\t/*if (timeNotDamaged >= 5000) {\r\n\t\t\t\t\tgeneratedHealthStore += 3f * elapsedTime;\r\n\r\n\t\t\t\t\tif (generatedHealthStore > 1) { // If generated at least 1 point\r\n\t\t\t\t\t\thealthBar.RegainHealth((int)generatedHealthStore);\r\n\t\t\t\t\t\tgeneratedHealthStore -= 1; // Reset to close to 0\r\n\t\t\t\t\t}\r\n\t\t\t\t} else { timeNotDamaged += elapsedMilitime; }*/\r\n\t\t\t}\r\n\r\n\t\t\tif (Alive) {\r\n\t\t\t\tDoEnemyStuff(); // Implement enemy algorithm defined in any child classes\r\n\r\n\t\t\t\tif (CausesContactDamage && GV.MonoGameImplement.Player.Intersects(this)) {\r\n\t\t\t\t\tif (!GV.MonoGameImplement.Player.CurrentWeapon.Attacking)\r\n\t\t\t\t\t\tGV.MonoGameImplement.Player.Attack(GV.MonoGameImplement.ContactDamage);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (invincibilityTime > 0) { invincibilityTime -= elapsedMilitime; } else {\r\n\t\t\t\t\tbool weaponAttacking = GV.MonoGameImplement.Player.CurrentWeapon.Attacking\r\n\t\t\t\t\t\t\t\t\t|| GV.MonoGameImplement.Player.CurrentWeapon.Thrown;\r\n\r\n\t\t\t\t\tif (weaponAttacking && GV.MonoGameImplement.Player.CurrentWeapon.Intersects(this))\r\n\t\t\t\t\t\tAttack(GV.MonoGameImplement.Player.CurrentWeapon.GetDamage());\r\n\r\n\t\t\t\t\tIMonoGameObject[] damagingIntersects = CompoundIntersects<IDamagingToEnemies>();\r\n\r\n\t\t\t\t\tif (damagingIntersects.Length > 0) {\r\n\t\t\t\t\t\tint damage = (from X in damagingIntersects select (X as IDamaging).GetDamage()).Aggregate((a, b) => a + b);\r\n\t\t\t\t\t\tAttack(damage);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} else Animation.Opacity -= 0.075f * elapsedTime; /* Lose by 7.5% every second */ \r\n\t\t}\r\n\r\n\t\tpublic override void OffsetSpritePosition(Vector2 XY) {\r\n\t\t\tbase.OffsetSpritePosition(XY); // Offsets enemy\r\n\t\t\tif (healthBar != null) healthBar.Offset(XY); // Offsets health bar for enemy\r\n\t\t}\r\n\r\n\t\tpublic override void SetPosition(Vector2 nPos) {\r\n\t\t\tbase.SetPosition(nPos); // Sets position of actual enemy sprite\r\n\t\t\tif (healthBar != null) healthBar.Offset(GetHealthBarInitialPosition() - healthBar.Position);\r\n\t\t}\r\n\r\n\t\tprotected Vector2 GetHealthBarInitialPosition() { return Position - new Vector2(0, 3 * EnemyHealthBar.DEFAULT_HEIGHT); }\r\n\r\n\t\tpublic virtual void Attack(int damage) { if (Alive) Damaged(this, damage); }\r\n\r\n\t\tprotected virtual uint GetHealth() {\r\n\t\t\treturn 1; // Default returns 1\r\n\t\t}\r\n\r\n\t\t/// <summary>When enemy can be deleted from game</summary>\r\n\t\t/// <param name=\"self\">Current instance, use if needed</param>\r\n\t\t/// <returns>Bool indicating sprite can be deleted</returns>\r\n\t\tprotected virtual bool ReadyToDelete(IMonoGameObject self) {\r\n\t\t\treturn !Alive && deathFXSpritesComplete;\r\n\t\t}\r\n\r\n\t\t/// <summary>Implementation of actual enemy logic</summary>\r\n\t\tprotected abstract void DoEnemyStuff();\r\n\r\n\t\tprivate EnemyHealthBar healthBar;\r\n\r\n\t\tpublic int Level { get; protected set; }\r\n\r\n\t\tpublic int Health { get { return healthBar.Health; } }\r\n\r\n\t\tpublic bool Alive { get; protected set; } = true;\r\n\r\n\t\tprotected abstract bool CanGenerateHealth { get; set; }\r\n\r\n\t\tprotected abstract bool CausesContactDamage { get; set; }\r\n\r\n\t\tprotected int timeNotDamaged = 0; // Time when not damaged\r\n\r\n\t\tprivate float generatedHealthStore = 0;\r\n\r\n\t\tprivate bool deathFXSpritesComplete = false;\r\n\r\n\t\tprivate int invincibilityTime = 0;\r\n\r\n\t\tpublic event Action<Enemy, int> Damaged;\r\n\r\n\t\tpublic event Action<Enemy> Killed = (self) => { self.Alive = false; };\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7139909863471985, "alphanum_fraction": 0.718117356300354, "avg_line_length": 43.08720779418945, "blob_id": "c9bd5e3269fe1c7851ee91284810a7ccc96ebfcd", "content_id": "cb06f1eb1e3144a38793064fac137c8b204e12a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7757, "license_type": "no_license", "max_line_length": 130, "num_lines": 172, "path": "/HollowAether/Lib/Misc/DashArgs.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.MapZone;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic sealed partial class Player : BodySprite {\r\n\t\tclass DashArgs {\r\n\t\t\t//public enum DashingDirection { Right, TopRight, Top, TopLeft, Left, BottomLeft, Bottom, BottomRight }\r\n\r\n\t\t\tpublic enum DashingDirection { Right, BottomRight, Bottom, BottomLeft, Left, TopLeft, Top, TopRight }\r\n\r\n\t\t\tDashArgs(Player self) {\r\n\t\t\t\ttimeDashing = defaultDashingTime; // Assign to default dashing time. Will dash for this long.\r\n\t\t\t\tthis.player = self; // Store reference to existing player instance\r\n\r\n\t\t\t\tFX.DashOverlay overlay = new FX.DashOverlay(self.Position, () => dashOverlayCompleted = true) { Layer = self.Layer + 0.005f };\r\n\t\t\t\tGV.MonoGameImplement.additionBatch.AddNameless(overlay); // Store to displayed object store\r\n\t\t\t}\r\n\r\n\t\t\tpublic DashArgs(Player self, DashingDirection direction) : this(self) { Initialise(direction); }\r\n\r\n\t\t\tpublic DashArgs(Player self, bool facingLeft) : this(self) {\r\n\t\t\t\tInitialise(GetDashingDirection(GetDefaultDashingDirection(facingLeft)));\r\n\t\t\t}\r\n\r\n\t\t\tprivate void Initialise(DashingDirection direction) {\r\n\t\t\t\tdashingDirection = direction; // Store direction of movement for current dash\r\n\t\t\t\tdashingVelocity = ConvertVelocityMagnitudeToVector(defaultDashingVelocity);\r\n\r\n\t\t\t\tswitch (direction) {\r\n\t\t\t\t\tcase DashingDirection.Left: case DashingDirection.BottomLeft: case DashingDirection.TopLeft: xFactor = -1; break;\r\n\t\t\t\t\tcase DashingDirection.Right: case DashingDirection.BottomRight: case DashingDirection.TopRight: xFactor = +1; break;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tswitch (direction) {\r\n\t\t\t\t\tcase DashingDirection.Bottom: case DashingDirection.BottomLeft: case DashingDirection.BottomRight: yFactor = +1; break;\r\n\t\t\t\t\tcase DashingDirection.Top: case DashingDirection.TopLeft: case DashingDirection.TopRight: yFactor = -1; break;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic DashingDirection GetDefaultDashingDirection(bool facingLeft) {\r\n\t\t\t\treturn (facingLeft) ? DashingDirection.Left : DashingDirection.Right;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static DashingDirection GetDashingDirection(DashingDirection _default) {\r\n\t\t\t\tbool leftInput = GV.PeripheralIO.currentControlState.Left || GV.PeripheralIO.GamePadThumstickPointingLeft(false);\r\n\t\t\t\tbool bottomInput = GV.PeripheralIO.currentControlState.Down || GV.PeripheralIO.GamePadThumstickPointingDown(false);\r\n\t\t\t\tbool rightInput = GV.PeripheralIO.currentControlState.Right || GV.PeripheralIO.GamePadThumstickPointingRight(false);\r\n\t\t\t\tbool topInput = GV.PeripheralIO.currentControlState.Up || GV.PeripheralIO.GamePadThumstickPointingUp(false);\r\n\r\n\t\t\t\tbool topLeftInput = leftInput && topInput;\r\n\t\t\t\tbool topRightInput = rightInput && topInput;\r\n\t\t\t\tbool bottomLeftInput = leftInput && bottomInput;\r\n\t\t\t\tbool bottomRightInput = rightInput && bottomInput;\r\n\r\n\t\t\t\tif (topRightInput) return DashingDirection.TopRight;\r\n\t\t\t\telse if (topLeftInput) return DashingDirection.TopLeft;\r\n\t\t\t\telse if (bottomRightInput) return DashingDirection.BottomRight;\r\n\t\t\t\telse if (bottomLeftInput) return DashingDirection.BottomLeft;\r\n\t\t\t\telse if (leftInput) return DashingDirection.Left;\r\n\t\t\t\telse if (rightInput) return DashingDirection.Right;\r\n\t\t\t\telse if (topInput) return DashingDirection.Top;\r\n\t\t\t\telse if (bottomInput) return DashingDirection.Bottom;\r\n\t\t\t\telse return _default; // Facing direction\r\n\t\t\t}\r\n\r\n\t\t\tprivate Vector2 ConvertVelocityMagnitudeToVector(float velocity) {\r\n\t\t\t\treturn (new Vector2(xFactor, yFactor)) * (new Vector2(velocity)) * sinCosRatio;\r\n\t\t\t}\r\n\r\n\t\t\tpublic bool Update() {\r\n\t\t\t\tif (!dashOverlayCompleted) return true; // Still dashing, wait till completion\r\n\r\n\t\t\t\tfloat deltaVelocity = dashingAcceleration * player.elapsedTime; // Increment dashing acceleration\r\n\t\t\t\ttimeDashing -= player.elapsedTime; // Decrement time dashing in preperation to stop dashing forward\r\n\t\t\t\tdashingVelocity += ConvertVelocityMagnitudeToVector(deltaVelocity); // Get new velocity\r\n\r\n\t\t\t\tif (timeDashing < 0 || sinCosRatio == Vector2.Zero) { return false; } else {\r\n\t\t\t\t\tplayer.OffsetSpritePosition(dashingVelocity * player.elapsedTime);\r\n\r\n\t\t\t\t\t#region CollisionHandlers\r\n\t\t\t\t\tif (player.HasIntersectedTypes(GV.MonoGameImplement.BlockTypes)) {\r\n\t\t\t\t\t\tswitch (dashingDirection) {\r\n\t\t\t\t\t\t\tcase DashingDirection.Left: FixHorizontal(false); break; // Left\r\n\t\t\t\t\t\t\tcase DashingDirection.Right: FixHorizontal(true); break; // Right\r\n\t\t\t\t\t\t\tcase DashingDirection.Bottom: FixVertical(false); break; // Bottom\r\n\t\t\t\t\t\t\tcase DashingDirection.Top: FixVertical(true); break; // Top\r\n\r\n\t\t\t\t\t\t\t#region Complicated\r\n\t\t\t\t\t\t\tcase DashingDirection.TopLeft: // TopLeft\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Left\"))\r\n\t\t\t\t\t\t\t\t\tFixHorizontal(false);\r\n\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Top\"))\r\n\t\t\t\t\t\t\t\t\tFixVertical(true);\r\n\r\n\t\t\t\t\t\t\t\tbreak; // Before you judge me, note contents of method return may change after first boundary fix\r\n \t\t\t\t\t\t\tcase DashingDirection.TopRight: // TopRight\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Right\"))\r\n\t\t\t\t\t\t\t\t\tFixHorizontal(true);\r\n\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Top\"))\r\n\t\t\t\t\t\t\t\t\tFixVertical(true);\r\n\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\tcase DashingDirection.BottomLeft: // BottomLeft\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Left\"))\r\n\t\t\t\t\t\t\t\t\tFixHorizontal(false);\r\n\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Bottom\"))\r\n\t\t\t\t\t\t\t\t\tFixVertical(false);\r\n\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\tcase DashingDirection.BottomRight: // BottomRight\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Right\"))\r\n\t\t\t\t\t\t\t\t\tFixHorizontal(true);\r\n\r\n\t\t\t\t\t\t\t\tif (player.GetIntersectedBoundaryLabels(GV.MonoGameImplement.BlockTypes).Contains(\"Bottom\"))\r\n\t\t\t\t\t\t\t\t\tFixVertical(false);\r\n\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t#endregion\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t#endregion\r\n\r\n\t\t\t\t\treturn true; // Dashing is still happening, prevent deletion\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate void FixVertical(bool upward) {\r\n\t\t\t\tif (upward) player.VerticalUpwardBoundaryFix();\r\n\t\t\t\telse player.VerticalDownwardBoundaryFix();\r\n\r\n\t\t\t\tdashingVelocity.Y = sinCosRatio.Y = 0;\r\n\t\t\t}\r\n\r\n\t\t\tprivate void FixHorizontal(bool right) {\r\n\t\t\t\tif (right) player.HorizontalMovingRightBoundaryFix();\r\n\t\t\t\telse player.HorizontalMovingLeftBoundaryFix();\r\n\r\n\t\t\t\tdashingVelocity.X = sinCosRatio.X = 0;\r\n\t\t\t}\r\n\r\n\t\t\tprivate Vector2 sinCosRatio = new Vector2(\r\n\t\t\t\t(float)Math.Sin(GV.Variables.degrees45ToRadians),\r\n\t\t\t\t(float)Math.Cos(GV.Variables.degrees45ToRadians)\r\n\t\t\t);\r\n\r\n\t\t\tprivate bool dashOverlayCompleted = false;\r\n\t\t\tprivate float timeDashing; // The time the player has remaining to dash, when 0 dashing stops\r\n\t\t\tpublic Vector2 dashingVelocity; // The veolocity the player is dashing at a given point in time\r\n\t\t\tprivate DashingDirection dashingDirection; // Direction for dash args to point and then move towards\r\n\t\t\tprivate static readonly float defaultDashingVelocity = 75f, dashingAcceleration = 300f, defaultDashingTime = 1.2f;\r\n\t\t\tprivate int xFactor = 0, yFactor = 0; // Direction in vertical or horizontal plane for player to travel in\r\n\t\t\tprivate Player player; // Player reference\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6855319738388062, "alphanum_fraction": 0.6871421933174133, "avg_line_length": 36.195899963378906, "blob_id": "fbc6c1bb0f59a521252f82d66eb03a96d6924d66", "content_id": "99515b4d75e93d79a2d5c1977f4d0204fbaf3694", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16770, "license_type": "no_license", "max_line_length": 142, "num_lines": 439, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\nusing System.Runtime.InteropServices;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.InputOutput.Parsers;\r\n\r\nusing LE = HollowAether.Lib.Forms.LevelEditor;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Forms {\r\n\tpublic partial class Editor : Form {\r\n\t\tprivate class ZoneListViewItem : ListViewItem {\r\n\t\t\tpublic ZoneListViewItem(Vector2 position, Map.ZoneArgs args) : base(args.path) {\r\n\t\t\t\tSubItems.Insert(1, new ListViewSubItem(this, args.visible ? \"V\" : \"N\"));\r\n\t\t\t\tzoneArgs = args; // Store both zone file path and visibility indicator\r\n\t\t\t\tthis.position = position; // Position of given in a map setting\r\n\t\t\t}\r\n\r\n\t\t\tpublic Map.ZoneArgs zoneArgs;\r\n\t\t\tpublic Vector2 position;\r\n\r\n\t\t\tpublic String ZonePath { get { return zoneArgs.path; }\r\n\t\t\t\tset {\r\n\t\t\t\t\tzoneArgs.path = value;\r\n\t\t\t\t\t// Check move zone\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic bool ZoneVisible { get { return zoneArgs.visible; }\r\n\t\t\t\tset {\r\n\t\t\t\t\tzoneArgs.visible = value; // Store update value for zone file\r\n\t\t\t\t\tSubItems[1].Text = value ? \"V\" : \"N\"; // Update column value\r\n\t\t\t\t\t//SubItems[1] = new ListViewSubItem(this, value ? \"V\" : \"N\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic Editor(String mapFilePath = null) {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\t#region Image Load\r\n\r\n\t\t\tTuple<Image, String>[] images = GV.Content.LoadImages(); // Get images\r\n\t\t\tGV.LevelEditor.textures = new Dictionary<String, Tuple<Image, String>>();\r\n\r\n\t\t\tforeach (Tuple<Image, String> tuple in images) {\r\n\t\t\t\tstring key = tuple.Item2.Replace(GV.hollowAether.Content.RootDirectory, \"\");\r\n\t\t\t\tkey = key.Substring(key.IndexOf('\\\\') + 1); // Remove Holder Folder From Key\r\n\t\t\t\tGV.LevelEditor.textures[IOMan.RemoveExtension(key).ToLower()] = tuple; \r\n\t\t\t}\r\n\t\t\t#endregion\r\n\r\n\t\t\t//Zone.keepBlocks\t\t\t\t = true;\r\n\t\t\t//Zone.dontExecuteBlockStatements = true;\r\n\t\t\tZone.StoreAssetTrace = true;\r\n\r\n\t\t\tmapFilePath = (String.IsNullOrEmpty(mapFilePath)) ? defaultMapPath : mapFilePath;\r\n\t\t\t// If map path passed as argument, set that as map, otherwise use default path\r\n\r\n\t\t\tif (IOMan.FileExists(mapFilePath)) LoadMapOrZoneFile(mapFilePath); else {\r\n\t\t\t\tMessageBox.Show($\"Map '{mapFilePath}' Not Found\", \"Map Not Found\", 0, MessageBoxIcon.Warning);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void Editor_Load(object sender, EventArgs e) {\r\n\t\t\tGV.LevelEditor.tileMap = new LE.TileMap();\r\n\r\n\t\t\tGV.LevelEditor.tileMap.FormClosing += (s, e2) => {\r\n\t\t\t\te2.Cancel = true; // Cancel form disposal\r\n\t\t\t\tGV.LevelEditor.tileMap.Hide(); // Hide\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate void Editor_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\tCheckSave();\r\n\t\t}\r\n\r\n\t\t#region EventHandler\r\n\t\tprivate void LEKeyDown(object sender, KeyEventArgs e) {\r\n\t\t\tif (e.KeyCode == Keys.Escape && CheckSave())\r\n\t\t\t\tApplication.Exit(); // Exit on escape after save\r\n\t\t}\r\n\r\n\t\tprivate void Editor_DragEnter(object sender, DragEventArgs e) {\r\n\t\t\tif (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;\r\n\t\t}\r\n\r\n\t\tprivate void Editor_DragDrop(object sender, DragEventArgs e) {\r\n\t\t\tstring[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\r\n\t\t\tif (files.Length > 1 || files.Length <= 0) return; // go back\r\n\t\t\tLoadMapOrZoneFile(files[0]); // Loads Map Or Zone File\r\n\t\t}\r\n\r\n\t\tprivate void zoneViewList_SelectedIndexChanged(object sender, EventArgs e) {\r\n\t\t\tif (zoneViewList.FocusedItem != null && !String.IsNullOrWhiteSpace(zoneViewList.FocusedItem.Text)) {\r\n\t\t\t\tcurrentPositionTextBox.Text = (zoneViewList.FocusedItem as ZoneListViewItem).position.ToString();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void zoneViewList_MouseDoubleClick(object sender, MouseEventArgs e) {\r\n\t\t\tif (e.Button == MouseButtons.Left && zoneViewList.FocusedItem != null) {\r\n\t\t\t\tZoneListViewItem item = (ZoneListViewItem)zoneViewList.FocusedItem;\r\n\r\n\t\t\t\tbool recreateEditor = zoneEditor == null || zoneEditor.IsDisposed;\r\n\r\n\t\t\t\tif (recreateEditor) zoneEditor = new LE.ZoneEditor(item.zoneArgs.ToInstance(true));\r\n\t\t\t\telse\t\t\t\tzoneEditor.Initialize(item.zoneArgs.ToInstance(true));\r\n\r\n\t\t\t\tzoneEditor.Show(); // Display newly made or existing form instance\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void zoneViewList_KeyDown(object sender, KeyEventArgs e) {\r\n\t\t\tif (e.KeyCode == Keys.Enter) // If player has clicked enter while zone is focused\r\n\t\t\t\tzoneViewList_MouseDoubleClick(sender, new MouseEventArgs(MouseButtons.Left, 1, -1, -1, 0));\r\n\t\t}\r\n\r\n\t\tprivate void zoneViewList_MouseClick(object sender, MouseEventArgs e) {\r\n\t\t\tif (e.Button != MouseButtons.Right) return; // Skip 4-ward\r\n\r\n\t\t\tif (zoneViewList.FocusedItem.Bounds.Contains(e.Location)) {\r\n\t\t\t\tlistViewContext.Show(Cursor.Position);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void deleteToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tif (zoneViewList.Focused) {\r\n\t\t\t\tString focusedPath = zoneViewList.FocusedItem.SubItems[0].Text;\r\n\t\t\t\tVector2 removalIndex = map.GetZoneIndexFromFilePath(focusedPath);\r\n\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t$\"Would you like to delete from the file-system as well\",\r\n\t\t\t\t\t\"Please Confirm\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (result != DialogResult.Cancel) {\r\n\t\t\t\t\tif (result == DialogResult.Yes) {\r\n\t\t\t\t\t\tstring path = Zone.GetRelativeFilePath(map[removalIndex].path);\r\n\t\t\t\t\t\tif (IOMan.FileExists(path)) System.IO.File.Delete(path); // Delete\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tzoneViewList.Items.Remove(zoneViewList.FocusedItem); // Delete from accessible display\r\n\t\t\t\t\tmap.DeleteZone(removalIndex); // Delete from current map instance to ensure it no longer exists\r\n\t\t\t\t\tmapChanged = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void addZoneButton_Click(object sender, EventArgs e) { newZoneTSMenuItem_Click(sender, e); }\r\n\r\n\t\t#region ToolStripEventHandlers\r\n\t\tprivate void newMapTSMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tif (mapLoaded) {\r\n\t\t\t\tDialogResult res = MessageBox.Show(\r\n\t\t\t\t\t\"Creating A New Map Will Remove The Current Map\",\r\n\t\t\t\t\t\"Map Creation Warning\", MessageBoxButtons.OKCancel\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (res == DialogResult.Cancel) return; else CheckSave(); // Save any changes\r\n\t\t\t}\r\n\r\n\t\t\tFolderBrowserDialog dialog = new FolderBrowserDialog();\r\n\t\t\tDialogResult result\t = dialog.ShowDialog(); // Show\r\n\t\t\t\r\n\t\t\t// Set Initial Zone Here\r\n\r\n\t\t\tif (result == DialogResult.OK) {\r\n\t\t\t\tString path = dialog.SelectedPath; // Path chosen by user\r\n\t\t\t\tIOMan.CheckConstruct(IOMan.Join(path, \"Zones\"));\r\n\t\t\t\tMap.CreateEmptyMap(IOMan.Join(path, \"Map.Map\")); // generate\r\n\t\t\t\tLoadMap(IOMan.Join(path, \"Map.Map\"), true); // Load map over existing map\r\n\t\t\t}\r\n\r\n\t\t\tdialog.Dispose(); // Free any un-necessary existing memory\r\n\t\t}\r\n\r\n\t\tprivate void animationsToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tLevelEditor.AnimationView view = new LE.AnimationView();\r\n\t\t\tview.ShowDialog();\r\n\t\t}\r\n\r\n\t\tprivate void newZoneTSMenuItem_Click(object sender, EventArgs e) { CreateZone(); }\r\n\t\t\r\n\t\tprivate void saveToolStripMenuItem_Click(object sender, EventArgs e) { Save(); }\r\n\r\n\t\tprivate void saveAsTSMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tusing (FolderBrowserDialog browser = new FolderBrowserDialog() { ShowNewFolderButton = true }) {\r\n\t\t\t\tDialogResult pathResult = browser.ShowDialog(); // Display folder browser form as a dialog to retrieve desired target path \r\n\r\n\t\t\t\tif (pathResult == DialogResult.OK) {\r\n\t\t\t\t\tIOMan.WriteEncryptedFile(IOMan.Join(browser.SelectedPath, \"Map.map\"), map.ToFileContents(), GV.Encryption.oneTimePad);\r\n\r\n\t\t\t\t\tbool copyZones = MessageBox.Show(\"Would you like to copy the zones in the map?\", \"Save As\", MessageBoxButtons.YesNo) == DialogResult.Yes;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (copyZones) {\r\n\t\t\t\t\t\tforeach (Vector2 key in map.ZoneIndexes) {\r\n\t\t\t\t\t\t\tMap.ZoneArgs args = map[key]; // Get and store zone args for key\r\n\t\t\t\t\t\t\tString actualPath = IOMan.Join(IOMan.GetDirectoryName(map.FilePath), args.path);\r\n\t\t\t\t\t\t\tString targetPath = IOMan.Join(browser.SelectedPath, args.path);\r\n\r\n\t\t\t\t\t\t\tIOMan.SequenceConstruct(IOMan.GetDirectoryName(targetPath));\r\n\t\t\t\t\r\n\t\t\t\t\t\t\tSystem.IO.File.Copy(actualPath, targetPath); // Copy file\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void loadTSMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tOpenFileDialog dialog = new OpenFileDialog() {\r\n\t\t\t\tFilter = \"Map files (*.MAP)|*.map|Zone files (*.ZNE)|*.ZNE|All files (*.*)|*.*\",\r\n\t\t\t\tCheckFileExists = true, Title = \"Select Map Or Zone File\", Multiselect = false,\r\n\t\t\t\tInitialDirectory = mapZoneStorePath // Default search path is within CWD\r\n\t\t\t};\r\n\r\n\t\t\tif (dialog.ShowDialog() == DialogResult.OK) {\r\n\t\t\t\tLoadMapOrZoneFile(dialog.FileName); // Load map/zone file\r\n\t\t\t\tdialog.Dispose(); // Free up dialog memory resources\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void modifyToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tif (zoneViewList.Focused) {\r\n\t\t\t\tvar item = zoneViewList.FocusedItem as ZoneListViewItem;\r\n\r\n\t\t\t\tLE.ZoneFeatures.ZoneDetails details = LE.ZoneFeatures.Get(\r\n\t\t\t\t\titem.ZonePath, item.position, item.ZoneVisible, false\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (details.succeeded) {\r\n\t\t\t\t\tif (item.position != details.position) {\r\n\t\t\t\t\t\tcurrentPositionTextBox.Text = details.position.ToString();\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\titem.ZonePath\t = details.filePath;\r\n\t\t\t\t\titem.ZoneVisible = details.visible;\r\n\t\t\t\t\titem.position\t = details.position;\r\n\r\n\t\t\t\t\tmapChanged = true; // Prompt save\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void modifyToolStripMenuItem1_Click(object sender, EventArgs e) {\r\n\t\t\tif (!zoneViewList.Focused) { MessageBox.Show($\"No Zone To Modify Has Been Focused\"); } else {\r\n\t\t\t\tmodifyToolStripMenuItem_Click(sender, e); // Call existing modification event handler\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void exitTSMenuItem_Click(object sender, EventArgs e) { Application.Exit(); }\r\n\r\n\t\tprivate void helpTSMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\t(new LE.Help()).ShowDialog(); // Show help dialog\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\t#region NotEventHandlers\r\n\t\t/// <summary>Checks whether or not to save & then prompts user</summary>\r\n\t\t/// <returns>Boolean indicating whether or not to exit</returns>\r\n\t\tprivate bool CheckSave() {\r\n\t\t\tif (!mapChanged) { return true; } else {\r\n\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\"Editor Canvas Has Changed, Would You Like To Save\",\r\n\t\t\t\t\t\"Warning: Changes Haven't Been Saved\",\r\n\t\t\t\t\tMessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning\r\n\t\t\t\t); // Ask user and convert input to string\r\n\r\n\t\t\t\tif (result == DialogResult.Yes) { Save(); return true; } else {\r\n\t\t\t\t\treturn false; // Don't save, O.K. to exit\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Saves anything that's changed</summary>\r\n\t\tprivate void Save() {\r\n\t\t\tIOMan.WriteEncryptedFile(map.FilePath, map.ToFileContents(), GV.Encryption.oneTimePad);\r\n\t\t\tmapChanged = false;\t// Allow closing of form because map has been saved.\r\n\t\t}\r\n\r\n\t\tprivate void LoadMapOrZoneFile(String path) {\r\n\t\t\tString headerString = IOMan.ReadEncryptedFile(path, GV.Encryption.oneTimePad).Split('\\n')[0];\r\n\t\t\tbool isMap\t\t\t= Parser.HeaderCheck(headerString, Map.MAP_FILE_HEADER);\r\n\t\t\tbool isZone\t\t\t= Parser.HeaderCheck(headerString, Zone.ZONE_FILE_HEADER);\r\n\r\n\t\t\tif (isMap) LoadMap(path); else if (isZone) AddZoneToMap(path); else {\r\n\t\t\t\tString displayString = (headerString.Trim().Length == 0) ? \r\n\t\t\t\t\t$\"Given File '{path}' Is Empty\" : $\"Given File '{path}' Is Not Of Type Map Or Zone\";\r\n\r\n\t\t\t\tMessageBox.Show(displayString, \"Incorrect File Format\", MessageBoxButtons.OK); // Display error to user and skip loading\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Method called to load a map</summary>\r\n\t\t/// <param name=\"fpath\">Path to map file</param>\r\n\t\tprivate void LoadMap(String fpath, bool skipInitZoneSet=true) {\r\n\t\t\tif (mapLoaded) {\r\n\t\t\t\tDialogResult res = MessageBox.Show(\r\n\t\t\t\t\t\"Loading A New Map Will Remove The Current Map\",\r\n\t\t\t\t\t\"Map Load Warning\", MessageBoxButtons.OKCancel\r\n\t\t\t\t);\r\n\r\n\t\t\t\tif (res == DialogResult.Cancel) return; else CheckSave();\r\n\t\t\t}\r\n\r\n\t\t\tGV.MapZone.ClearFlags(); // Clear any stored map flags\r\n\t\t\tzoneViewList.Items.Clear(); // Clear any displayed zones\r\n\t\t\tmap = new Map(fpath); // Set global map to new instance\r\n\t\t\tmap.Initialize(!skipInitZoneSet); // Parse new map file instance \r\n\t\t\tMapLoaded(fpath); // Map has been loaded\r\n\t\t}\r\n\r\n\t\tprivate void CreateZone() {\r\n\t\t\tif (!mapLoaded) MessageBox.Show($\"No Map To Load Zone Into\", \"Error\", MessageBoxButtons.OK); else {\r\n\t\t\t\tLE.ZoneFeatures.ZoneDetails details = LE.ZoneFeatures.Get(); // Get Zone Details\r\n\r\n\t\t\t\tif (details.succeeded) {\r\n\t\t\t\t\tString path = IOMan.Join(IOMan.GetDirectoryName(map.FilePath), details.filePath);\r\n\r\n\t\t\t\t\tif (IOMan.FileExists(path)) {\r\n\t\t\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\t\t\"The given file already exists, would you like to load it\",\r\n\t\t\t\t\t\t\t\"File Exists Error\", MessageBoxButtons.YesNo\r\n\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\tif (result == DialogResult.No) return; \r\n\t\t\t\t\t} else Zone.CreateEmptyZone(path);\r\n\r\n\t\t\t\t\tAddZoneToMap(path, details.position, details.visible);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AddZoneToMap(String fpath) {\r\n\t\t\tif (!mapLoaded) MessageBox.Show($\"No Map To Load Zone Into\", \"Error\", MessageBoxButtons.OK); else {\r\n\t\t\t\tif (map.ContainsZone(fpath)) MessageBox.Show(\"Zone Already In Editor\", \"Error\", MessageBoxButtons.OK); else {\r\n\t\t\t\t\tLE.ZoneFeatures.ZoneDetails details = LE.ZoneFeatures.Get(fpath); // Get new zone details\r\n\r\n\t\t\t\t\tif (details.succeeded) {\r\n\t\t\t\t\t\tif (map.ContainsZone(details.position)) // Desired position already exists\r\n\t\t\t\t\t\t\tMessageBox.Show($\"Zone at given position already exists\", \"Error\", MessageBoxButtons.OK);\r\n\t\t\t\t\t\telse AddZoneToMap(fpath, details.position, details.visible);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AddZoneToMap(String fpath, Vector2 index, bool visible) {\r\n\t\t\tif (!mapLoaded) MessageBox.Show($\"No Map To Load Zone Into\", \"Error\", MessageBoxButtons.OK); else {\r\n\t\t\t\tbool zoneExists = map.ContainsZone(fpath), indexExists = map.ZoneIndexes.Contains(index);\r\n\r\n\t\t\t\tif (zoneExists || indexExists) {\r\n\t\t\t\t\tString errorString = zoneExists ? \"Zone Already In Editor\" : \"Given index already exists in map\";\r\n\t\t\t\t\tMessageBox.Show(errorString, \"Error\", MessageBoxButtons.OK); // Display error to editor user\r\n\t\t\t\t} else {\r\n\t\t\t\t\tString path = IOMan.GetRelativeFilePath(fpath, IOMan.GetDirectoryName(map.FilePath));\r\n\t\t\t\t\tmap.AddZone(index, path, visible); // Add zone to current map instance as new zone\r\n\t\t\t\t\tzoneViewList.Items.Add(new ZoneListViewItem(index, new Map.ZoneArgs(path, visible)));\r\n\r\n\t\t\t\t\tmapChanged = true; // Press user to save changes upon closing of form\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Things To Do When Map Has Been Loaded</summary>\r\n\t\tprivate void MapLoaded(String mapPath) {\r\n\t\t\tmapLabelTextBox.Text = mapPath;\r\n\t\t\tzoneViewList.Enabled = true;\r\n\t\t\taddZoneButton.Enabled = true;\r\n\t\t\tmapLoaded\t\t\t = true;\r\n\r\n\t\t\tforeach (Vector2 zone in map.ZoneIndexes) {\r\n\t\t\t\tzoneViewList.Items.Add(new ZoneListViewItem(zone, map[zone]));\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region PathDefinitions\r\n\r\n\t\t#region Directories\r\n\t\tpublic static String levelEditorBasePath = @\"Assets\\LevelBuilder\";\r\n\t\tpublic static String textureBasePath = IOMan.Join(levelEditorBasePath, \"Textures\");\r\n\t\tpublic static String saveBasePath = IOMan.Join(levelEditorBasePath, \"Save\");\r\n\t\tpublic static String mapZoneStorePath = IOMan.Join(levelEditorBasePath, \"Store\");\r\n\t\t//public static String animationStorePath = IOMan.Join(mapZoneStorePath, \"Animations\");\r\n\t\tpublic static String defaultMapPath = IOMan.Join(levelEditorBasePath, \"Map.map\");\r\n\t\t#endregion\r\n\r\n\t\t#region Files\r\n\t\tpublic static String saveFilePath = IOMan.Join(saveBasePath, \"Editor.SVE\");\r\n\t\t#endregion\r\n\r\n\t\t#endregion\r\n\r\n\t\tprivate LE.ZoneEditor zoneEditor;\r\n\t\tprivate bool mapLoaded\t\t\t = false;\r\n\t\tprivate bool mapChanged\t\t\t = false;\r\n\r\n\t\tprivate Map map { get { return GV.MonoGameImplement.map; } set { GV.MonoGameImplement.map = value; } }\r\n\r\n\t\tprivate void setStartZoneToolStripMenuItem_Click(object sender, EventArgs e) {\r\n\t\t\tVector2? value = SetInitialZone.Get(map.GetStartZoneIndexOrEmpty());\r\n\r\n\t\t\tif (value.HasValue) {\r\n\t\t\t\tif (!map.ZoneIndexes.Contains(value.Value)) {\r\n\t\t\t\t\tDialogResult result = MessageBox.Show(\r\n\t\t\t\t\t\t\"Desired Zone Doesn't Exist Yet. Would You Like To Continue.\",\r\n\t\t\t\t\t\t\"\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tif (result != DialogResult.Yes) return; // Input = No || Input = Cancel\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmap.SetStartZone(value.Value); // Set start zone to argument index\r\n\t\t\t\tmapChanged = true; // Query user to save before closing editor\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6866438388824463, "alphanum_fraction": 0.6969178318977356, "avg_line_length": 37.19462966918945, "blob_id": "6dc35ecb6a7d52a279a0192209a7ed38c9346ceb", "content_id": "f596931eafdf9b79ddcabd78bb846a9c93b86910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5842, "license_type": "no_license", "max_line_length": 144, "num_lines": 149, "path": "/HollowAether/Lib/Global/GameWindow/PlayerDeceased.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic static class PlayerDeceased {\r\n\t\t//static PlayerDeceased() { Reset(); }\r\n\r\n\t\tpublic static void Draw() {\r\n\t\t\tGameRunning.Draw(); // Set as backdrop\r\n\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false);\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(\r\n\t\t\t\tGV.MonoGameImplement.textures[overlayTexture],\r\n\t\t\t\tnew Rectangle(0, 0, GV.Variables.windowWidth, GV.Variables.windowHeight),\r\n\t\t\t\tColor.White * 0.75f\r\n\t\t\t);\r\n\r\n\t\t\tgameOverHeader.Draw(); // Draw header to screen\r\n\r\n\t\t\tif (titleText != null) titleText.Draw();\r\n\r\n\t\t\tif (buttons != null) {\r\n\t\t\t\tforeach (Button button in buttons)\r\n\t\t\t\t\tbutton.Draw(); // Draw button\r\n\t\t\t}\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic static void Update() {\r\n\t\t\tgameOverHeader.Update();\r\n\r\n\t\t\tif (titleText != null) titleText.Update();\r\n\r\n\t\t\tif (buttons != null) UpdateButtons();\r\n\t\t}\r\n\r\n\t\tprivate static void UpdateButtons() {\r\n\t\t\tvar controlState = GV.PeripheralIO.currentControlState; // Store current input control state\r\n\t\t\tbool altPressed = GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.LeftAlt, Keys.RightAlt);\r\n\r\n\t\t\tif (inputTimeout > 0) {\r\n\t\t\t\tif (!controlState.GamepadNotPressed() && controlState.KeyboardNotPressed())\r\n\t\t\t\t\tinputTimeout = 0; // Erase timeout if keypress removed, else continue it\r\n\t\t\t\telse inputTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t} else if (!altPressed) { // Skip any input checks if alt is pressed\r\n\t\t\t\tbool previousButton = controlState.Left || controlState.Up, nextButton = controlState.Right || controlState.Down;\r\n\t\t\t\tbool enterPressed = GV.PeripheralIO.currentKBState.IsKeyDown(Keys.Enter); // Chose to accept command/click-button\r\n\r\n\t\t\t\tif (previousButton ^ nextButton) {\r\n\t\t\t\t\tif (previousButton) buttons.MoveToPreviousButton();\r\n\t\t\t\t\telse\t\t\t\tbuttons.MoveToNextButton();\r\n\r\n\t\t\t\t\tinputTimeout = 300; // Don't accept input for 300 seconds \r\n\t\t\t\t} else if (!(previousButton || nextButton) && (controlState.Jump || enterPressed)) {\r\n\t\t\t\t\tswitch (buttons.ActiveButtonIndex) {\r\n\t\t\t\t\t\tcase 0: // Retry from last save\r\n\t\t\t\t\t\t\tGV.MonoGameImplement.gameState = GameState.GameRunning;\r\n\t\t\t\t\t\t\tGameRunning.LoadSave(GV.MonoGameImplement.saveIndex);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 1: // Go to home screen\r\n\t\t\t\t\t\t\tGV.MonoGameImplement.saveIndex = -1; // Invalidate\r\n\t\t\t\t\t\t\tGV.MonoGameImplement.gameState = GameState.Home;\r\n\t\t\t\t\t\t\tHome.Reset(); // Reset new game state\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase 2: // Exit game\r\n\t\t\t\t\t\t\tGV.hollowAether.god.EndGame();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tinputTimeout = 300; // Don't accept input for 300 seconds\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() {\r\n\t\t\ttitleText = null; buttons = null; // Delete (allocate for deletion) existing unecessary class members\r\n\r\n\t\t\tCreatePushableText(ref gameOverHeader, \"Game Over\", DEFAULT_HEADER_FONT_ID, Color.Red, GV.Variables.windowHeight / 24, 3);\r\n\r\n\t\t\tgameOverHeader.PushPack.PushCompleted += (self, args) => {\r\n\t\t\t\tfloat verticalPosition = gameOverHeader.Position.Y + gameOverHeader.Size.Y + 24; // new\r\n\t\t\t\tCreatePushableText(ref titleText, DeathTitle, DEFAULT_TITLE_FONT_ID, Color.Yellow, verticalPosition, 2);\r\n\r\n\t\t\t\ttitleText.PushPack.PushCompleted += (self2, args2) => {\r\n\t\t\t\t\tString[] buttonStrings = { \"Retry\", \"Return To Home\", \"Exit Game\" };\r\n\t\t\t\t\tPoint buttonSize = new Point(64*6, 32*3); // Set button dimensions\r\n\r\n\t\t\t\t\tVector2 sequentialOffset = new Vector2(0, buttonSize.Y * 1.15f); // Value to offset sprite by for each button\r\n\r\n\t\t\t\t\tVector2 position = new Vector2((GV.Variables.windowWidth - buttonSize.X) / 2, titleText.Position.Y + titleText.Size.Y);\r\n\t\t\t\t\t// Initial position is centered and directly below title text position. Add offsets to this as needed including initial\r\n\r\n\t\t\t\t\tposition.Y += 0.15f * buttonSize.Y; // Give initial offset to sprite\r\n\r\n\t\t\t\t\tButton[] _buttons = new Button[buttonStrings.Length]; // Create array to hold any generated buttons\r\n\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(0, 3)) {\r\n\t\t\t\t\t\t_buttons[X] = new TextButton(position, buttonStrings[X], buttonSize.X, buttonSize.Y);\r\n\t\t\t\t\t\tposition += sequentialOffset; // Add offset to sprite position before creating new button\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\tbuttons = new ButtonList(0, 3, _buttons); // Store new buttons to local class\r\n\t\t\t\t};\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tprivate static void CreatePushableText(ref PushableText address, String text, String font, Color color, float targetYPosition, float over=3) {\r\n\t\t\tVector2 size = GV.MonoGameImplement.fonts[font].MeasureString(text); // Size of text\r\n\t\t\tVector2 position = new Vector2((GV.Variables.windowWidth - size.X) / 2, -size.Y); // Center\r\n\t\t\taddress = new PushableText(position, text, color, font); // Set initial position\r\n\t\t\taddress.PushTo(new Vector2(position.X, targetYPosition), over); // Push to target position\r\n\t\t}\r\n\r\n\t\tpublic static void FullScreenReset(bool isFullScreen) {\r\n\t\t\tif (GV.MonoGameImplement.gameState == GameState.PlayerDeceased)\r\n\t\t\t\tReset(); // Reset only when current game state is valid\r\n\t\t}\r\n\r\n\t\tpublic static String DeathTitle { get; } = \"Human Is Dead. Mismatch.\";\r\n\r\n\t\tprivate static PushableText titleText, gameOverHeader;\r\n\r\n\t\tprivate static ButtonList buttons;\r\n\r\n\t\tprivate static int inputTimeout = 0;\r\n\r\n\t\tpublic const String DEFAULT_TITLE_FONT_ID = @\"playerdeadtitle\";\r\n\r\n\t\tpublic const String DEFAULT_HEADER_FONT_ID = @\"playerdeadheader\";\r\n\r\n\t\tprivate static String overlayTexture = @\"backgrounds\\windows\\playerdeadoverlay\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6650873422622681, "alphanum_fraction": 0.6843352317810059, "avg_line_length": 32.11111068725586, "blob_id": "b50a6cba17f7e87cf826801f3c775ec0f39801c0", "content_id": "7b8bb90ffa2512db2edc159da5fa7bb79cb84348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3379, "license_type": "no_license", "max_line_length": 113, "num_lines": 99, "path": "/HollowAether/Lib/GAssets/Items/Points/BurstPoint.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic sealed class BurstPoint : TreasureItem {\r\n\t\tpublic enum PointSpan { Small, Medium, Large }\r\n\r\n\t\tpublic BurstPoint(Vector2 position, PointSpan _span) : base(position, spriteWidth, spriteHeight, 10000, true) {\r\n\t\t\tspan = _span; // Store span to help create animation\r\n\t\t\tInitialize(\"cs\\\\npcsym\"); // Initialise with necesarry texture\r\n\t\t\tInitializeVolatility(VolatilityType.Timeout, 50000); // Exists for 5 secs\r\n\t\t\tValue = GetBurstPointValue(); // Random generate value\r\n\t\t}\r\n\r\n\t\tPointSpan span;\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Also updates elapsed time\r\n\r\n\t\t\tif (GV.MonoGameImplement.Player.Intersects(boundary)) {\r\n\t\t\t\tInteract(); // When collided with player, interact\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic override void Interact() {\r\n\t\t\tif (Interacted || !CanInteract) return; // Skip\r\n\t\t\tGameWindow.GameRunning.InvokeBurstPointAcquired(this);\r\n\t\t\tbase.Interact(); // Allocate to delete & Mark interacted\r\n\t\t}\r\n\r\n\t\tprivate static int GetBurstPointValue() {\r\n\t\t\tdouble chance = GV.Variables.random.NextDouble(); // Value between 1.0 & 0.0\r\n\r\n\t\t\tif (chance < 1 / MAX_POINT_VALUE) return 1; else {\r\n\t\t\t\tforeach (int X in Enumerable.Range(MIN_POINT_VALUE, MAX_POINT_VALUE))\r\n\t\t\t\t\tif (chance > 1 / X) return X; // Chance becomes less likely as X bigger\r\n\t\t\t}\r\n\r\n\t\t\treturn 1; // Should be impossible, but just in case \r\n\t\t}\r\n\r\n\t\tprotected override void VerticalDownwardBoundaryFix() {\r\n\t\t\tbase.VerticalDownwardBoundaryFix();\r\n\t\t}\r\n\r\n\t\tprotected override void LinearCollisionHandler() {\r\n\t\t\tbase.LinearCollisionHandler();\r\n\r\n\t\t\t/*int currentSequence = Convert.ToInt32(SequenceKey); // Store as frame int\r\n\t\t\tint next = (currentSequence + 1 < FRAME_COUNT) ? currentSequence + 1 : 0;\r\n\t\t\tAnimation.SetAnimationSequence(next.ToString()); // Next frame in sequence*/\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\t/*foreach (int X in Enumerable.Range(0, FRAME_COUNT)) {\r\n\t\t\t\tFrame sequenceFrame = new Frame(X, 1 + (int)span, 32, 32);\r\n\t\t\t\tAnimation[X.ToString()] = new AnimationSequence(0, sequenceFrame);\r\n\t\t\t}\r\n\r\n\t\t\tAnimation.SetAnimationSequence(GV.Variables.random.Next(0, FRAME_COUNT).ToString());*/\r\n\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = AnimationSequence.FromRange(\r\n\t\t\t\t32, 32, 0, 1 + (int)span, 5, 32, 32, 25, true, 1\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tprivate const int FRAME_COUNT = 5;\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tint width; //IBRectangle mainBoundary;\r\n\r\n\t\t\tswitch (span) {\r\n\t\t\t\tcase PointSpan.Large: width = 26; break;\r\n\t\t\t\tcase PointSpan.Medium: width = 17; break;\r\n\t\t\t\tcase PointSpan.Small: width = 13; break;\r\n\t\t\t\tdefault: width = 00; break;\r\n\t\t\t}\r\n\r\n\t\t\twidth = (Width - width) / 2;\r\n\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect,\r\n\t\t\t\tnew IBRectangle(Position.X + width, Position.Y + width, Width - (2 * width), Height - (2 * width))\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\tpublic int Value { get; private set; }\r\n\r\n\t\tpublic const int spriteWidth = 32, spriteHeight = 32;\r\n\r\n\t\tprivate const int MIN_POINT_VALUE = 1, MAX_POINT_VALUE=5;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6511602997779846, "alphanum_fraction": 0.6548130512237549, "avg_line_length": 39.73991012573242, "blob_id": "73f00f8afbbd0e52e80861b9940e5b7b1bd26ed4", "content_id": "966d4fd32e532551e52fabb3cd951cb38fe41af6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 9310, "license_type": "no_license", "max_line_length": 115, "num_lines": 223, "path": "/HollowAether/Lib/Global/GlobalVars/PeripheralIO.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class PeripheralIO {\r\n\t\t\tpublic static bool ImplementWaitForInputToBeRemoved(ref bool wait) {\r\n\t\t\t\tif (!wait) return false; else {\r\n\t\t\t\t\tif (currentControlState.GamepadAndKeyboardNotPressed())\r\n\t\t\t\t\t\twait = false; // Input has been removed, stop waiting \r\n\r\n\t\t\t\t\treturn true; // True when u want caller to also return\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static class Controls {\r\n\t\t\t\t#region KeyBoardControls \r\n\t\t\t\tpublic static readonly Keys[] jumpKB = { Keys.Space, Keys.Up };\r\n\t\t\t\tpublic static readonly Keys[] interactKB = { Keys.Enter };\r\n\t\t\t\tpublic static readonly Keys[] dashKB = { Keys.Q };\r\n\t\t\t\tpublic static readonly Keys[] leftKB = { Keys.Left, Keys.A };\r\n\t\t\t\tpublic static readonly Keys[] rightKB = { Keys.Right, Keys.D };\r\n\t\t\t\tpublic static readonly Keys[] downKB = { Keys.Down, Keys.S };\r\n\t\t\t\tpublic static readonly Keys[] upKB = { Keys.Up, Keys.W };\r\n\t\t\t\tpublic static readonly Keys[] throwKB = { Keys.X };\r\n\t\t\t\tpublic static readonly Keys[] attackKB = { Keys.Z };\r\n\t\t\t\tpublic static readonly Keys[] weaponNextKB = { Keys.E };\r\n\t\t\t\tpublic static readonly Keys[] pauseGameKB = { Keys.P\t\t\t\t };\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\t#region GamePadControls \r\n\t\t\t\tpublic static readonly Buttons[] jumpGP = { Buttons.A };\r\n\t\t\t\tpublic static readonly Buttons[] interactGP = { Buttons.Y };\r\n\t\t\t\tpublic static readonly Buttons[] throwGP = { Buttons.RightShoulder };\r\n\t\t\t\tpublic static readonly Buttons[] dashGP = { /*Left Trigger &*/ Buttons.X };\r\n\t\t\t\tpublic static readonly Buttons[] weaponNextGP = { Buttons.LeftShoulder };\r\n\t\t\t\tpublic static readonly Buttons[] pauseGameGP = { Buttons.Start, Buttons.Back };\r\n\r\n\t\t\t\t//public static Buttons[] leftGP = { /*Left ThumbStick*/ };\r\n\t\t\t\t//public static Buttons[] rightGP = { /*Left ThumbStick*/ };\r\n\t\t\t\t//public static Buttons[] downGP = { /*Left ThumbStick*/ };\r\n\t\t\t\t//public static Buttons[] upGP = { /*Left ThumbStick*/ };\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\r\n\t\t\tpublic struct ControlState {\r\n\t\t\t\tpublic struct ControlsPressed {\r\n\t\t\t\t\tpublic override string ToString() {\r\n\t\t\t\t\t\treturn $\"GS(J:{Jump}, I:{Interact}, D:{Dash}, L:{Left}, R:{Right}, U:{Up}, D:{Down}), A:{Attack}, T:{Throw}\";\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpublic bool NotPressed() {\r\n\t\t\t\t\t\treturn !(Jump || Interact || Dash || Attack || Throw || Left || Right || Up || Down || Pause);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpublic bool Jump, Interact, Dash, Left, Right, Up, Down, Throw, Attack, WeaponNext, Pause;\r\n\r\n\t\t\t\t\tpublic static ControlsPressed Empty {\r\n\t\t\t\t\t\tget { return new ControlsPressed(); }\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic void Update() {\r\n\t\t\t\t\tKeyboardState KB = currentKBState;\r\n\t\t\t\t\tGamePadState GP = currentGPState;\r\n\r\n\t\t\t\t\tKeyboard = new ControlsPressed() {\r\n\t\t\t\t\t\tJump = CheckMultipleKeys(true, KB, Controls.jumpKB),\r\n\t\t\t\t\t\tInteract = CheckMultipleKeys(true, KB, Controls.interactKB),\r\n\t\t\t\t\t\tDash = CheckMultipleKeys(true, KB, Controls.dashKB),\r\n\t\t\t\t\t\tLeft = CheckMultipleKeys(true, KB, Controls.leftKB),\r\n\t\t\t\t\t\tRight = CheckMultipleKeys(true, KB, Controls.rightKB),\r\n\t\t\t\t\t\tUp = CheckMultipleKeys(true, KB, Controls.upKB),\r\n\t\t\t\t\t\tDown = CheckMultipleKeys(true, KB, Controls.downKB),\r\n\t\t\t\t\t\tAttack = CheckMultipleKeys(true, KB, Controls.attackKB),\r\n\t\t\t\t\t\tThrow = CheckMultipleKeys(true, KB, Controls.throwKB),\r\n\t\t\t\t\t\tWeaponNext = CheckMultipleKeys(true, KB, Controls.weaponNextKB),\r\n\t\t\t\t\t\tPause = CheckMultipleKeys(true, KB, Controls.pauseGameKB)\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\tGamepad = new ControlsPressed() {\r\n\t\t\t\t\t\tJump = CheckMultipleButtons(true, GP, Controls.jumpGP),\r\n\t\t\t\t\t\tInteract = CheckMultipleButtons(true, GP, Controls.interactGP),\r\n\t\t\t\t\t\tDash = TriggerPressed(true, GP) || CheckMultipleButtons(true, GP, Controls.dashGP),\r\n\t\t\t\t\t\tLeft = GamePadThumstickPointingLeft(true, GP),\r\n\t\t\t\t\t\tRight = GamePadThumstickPointingRight(true, GP),\r\n\t\t\t\t\t\tUp = GamePadThumstickPointingUp(true, GP),\r\n\t\t\t\t\t\tDown = GamePadThumstickPointingDown(true, GP),\r\n\t\t\t\t\t\tAttack = TriggerPressed(false, GP),\r\n\t\t\t\t\t\tThrow = CheckMultipleButtons(true, GP, Controls.throwGP),\r\n\t\t\t\t\t\tWeaponNext = CheckMultipleButtons(true, GP, Controls.weaponNextGP),\r\n\t\t\t\t\t\tPause = CheckMultipleButtons(true, GP, Controls.pauseGameGP)\r\n\t\t\t\t\t};\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpublic bool KeyboardNotPressed() { return Keyboard.NotPressed(); }\r\n\r\n\t\t\t\tpublic bool GamepadNotPressed() { return Gamepad.NotPressed(); }\r\n\r\n\t\t\t\tpublic bool GamepadAndKeyboardNotPressed() { return GamepadNotPressed() && KeyboardNotPressed(); }\r\n\r\n\t\t\t\tpublic bool Left { get { return Keyboard.Left || Gamepad.Left; } }\r\n\r\n\t\t\t\tpublic bool Right { get { return Keyboard.Right || Gamepad.Right; } }\r\n\r\n\t\t\t\tpublic bool Up { get { return Keyboard.Up || Gamepad.Up; } }\r\n\r\n\t\t\t\tpublic bool Down { get { return Keyboard.Down || Gamepad.Down; } }\r\n\r\n\t\t\t\tpublic bool Jump { get { return Keyboard.Jump || Gamepad.Jump; } }\r\n\r\n\t\t\t\tpublic bool Interact { get { return Keyboard.Interact || Gamepad.Interact; } }\r\n\r\n\t\t\t\tpublic bool Dash { get { return Keyboard.Dash || Gamepad.Dash; } }\r\n\r\n\t\t\t\tpublic bool Attack { get { return Keyboard.Attack || Gamepad.Attack; } }\r\n\r\n\t\t\t\tpublic bool Throw { get { return Keyboard.Throw || Gamepad.Throw; } }\r\n\r\n\t\t\t\tpublic bool WeaponNext { get { return Keyboard.WeaponNext || Gamepad.WeaponNext; } }\r\n\r\n\t\t\t\tpublic bool Pause { get { return Keyboard.Pause || Gamepad.Pause; } }\r\n\r\n\t\t\t\tpublic ControlsPressed Keyboard, Gamepad;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool TriggerPressed(bool leftTrigger, GamePadState? state = null) {\r\n\t\t\t\tGamePadTriggers triggers = (state.HasValue ? state.Value : currentGPState).Triggers;\r\n\t\t\t\treturn (leftTrigger ? triggers.Left : triggers.Right) > 0.25; // Button Tolerance = 0.5\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Vector2 GetThumbStickDisplacement(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\tGamePadThumbSticks GPTS = (state.HasValue ? state.Value : currentGPState).ThumbSticks;\r\n\t\t\t\treturn (leftTS) ? GPTS.Left : GPTS.Right; // Get left or right thumbstick indicator\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool[] ThumbstickPointing(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\tVector2 s = GetThumbStickDisplacement(leftTS, state); // displacement\r\n\r\n\t\t\t\treturn new bool[] { s.Y > 0.25, s.X > 0.25, s.Y < -0.25, s.X < -0.25 };\r\n\t\t\t\t// Top, Right, Bottom, Left -> Clockwise rotation of TS with tolerance 0.25\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool GamePadThumstickPointingLeft(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\treturn GetThumbStickDisplacement(leftTS, state).X < -0.25;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool GamePadThumstickPointingRight(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\treturn GetThumbStickDisplacement(leftTS, state).X > 0.25;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool GamePadThumstickPointingUp(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\treturn GetThumbStickDisplacement(leftTS, state).Y > 0.25;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool GamePadThumstickPointingDown(bool leftTS, GamePadState? state = null) {\r\n\t\t\t\treturn GetThumbStickDisplacement(leftTS, state).Y < -0.25;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tpublic static bool CheckMultipleKeys(bool ORCheck = true, KeyboardState? kb = null, params Keys[] keys) {\r\n\t\t\t\tKeyboardState keyboard = (kb.HasValue) ? kb.Value : currentKBState; // default = current\r\n\r\n\t\t\t\tforeach (Keys key in keys) {\r\n\t\t\t\t\tif (keyboard.IsKeyDown(key)) { if (ORCheck) return true; } \r\n\t\t\t\t\telse\t\t\t\t\t { if (!ORCheck) return false; }\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn !ORCheck;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool CheckMultipleButtons(bool ORCheck, GamePadState? gp = null, params Buttons[] buttons) {\r\n\t\t\t\tGamePadState gamepad = (gp.HasValue) ? gp.Value : currentGPState; // default = current\r\n\r\n\t\t\t\tforeach (Buttons button in buttons) {\r\n\t\t\t\t\tif (gamepad.IsButtonDown(button)) { if (ORCheck) return true; } \r\n\t\t\t\t\telse\t\t\t\t\t\t\t { if (!ORCheck) return false; }\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn !ORCheck;\r\n\t\t\t}\r\n\r\n\t\t\tpublic static bool gamePadConnected { get { return currentGPState.IsConnected; } }\r\n\r\n\t\t\tpublic static KeyboardState previousKBState, currentKBState;\r\n\t\t\tpublic static GamePadState previousGPState, currentGPState;\r\n\r\n\t\t\tpublic static ControlState previousControlState = new ControlState() {\r\n\t\t\t\tKeyboard = ControlState.ControlsPressed.Empty,\r\n\t\t\t\tGamepad = ControlState.ControlsPressed.Empty,\r\n\t\t\t};\r\n\r\n\t\t\tpublic static ControlState currentControlState = new ControlState() {\r\n\t\t\t\tKeyboard = ControlState.ControlsPressed.Empty,\r\n\t\t\t\tGamepad = ControlState.ControlsPressed.Empty,\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7480748295783997, "alphanum_fraction": 0.7480748295783997, "avg_line_length": 28.299999237060547, "blob_id": "014f897d5f1388822404516b9d70419c6658019d", "content_id": "7d3db761757ab8bf8fda14bae4af6e12f605faaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 911, "license_type": "no_license", "max_line_length": 84, "num_lines": 30, "path": "/HollowAether/Lib/Interfaces/ICollideable.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.GAssets;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\t/// <summary> Interface for any class which can be collided with </summary>\r\n\tpublic interface ICollideable {\r\n\t\t/// <summary>Checks whether object collides with another object</summary>\r\n\t\t/// <param name=\"target\">Target monogame object which can be collided with</param>\r\n\t\t/// <returns>Boolean indicating sucesfull collision between targets</returns>\r\n\t\tbool Intersects(IMonoGameObject target);\r\n\t\t\r\n\t\tbool Intersects(IBoundaryContainer boundary);\r\n\t\t\r\n\t\tIMonoGameObject[] CompoundIntersects(params Type[] matchableTypes);\r\n\r\n\t\t//void BuildBoundary();\r\n\r\n\t\t//BoundaryContainer GetBoundary();\r\n\t\tIBoundaryContainer Boundary { get; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6470988988876343, "alphanum_fraction": 0.6633722186088562, "avg_line_length": 39.62765884399414, "blob_id": "468c81b992fd2d6c64e916b41b5ad0dfd7d417df", "content_id": "4ef8b92e055b7a5ff04c7bcfd41a185686a7e71e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11747, "license_type": "no_license", "max_line_length": 131, "num_lines": 282, "path": "/HollowAether/Lib/GAssets/Boundary/Shapes/IBTriangle.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\n#endregion\r\n\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary> Custom Built Triangle Class, for use in TriBBox Class </summary>\r\n\tpublic partial class IBTriangle : IBoundary {\r\n\t\t/// <summary> Class containing general triangle intersection Methods, forming backbone\r\n\t\t/// of class; takes advantage of mathematical Check Sides with Dot Product algorithm </summary>\r\n\t\t/// <remarks>Note that the bulk of the class is allocated to vector intersection checks</remarks>\r\n\t\tpublic class TriangleBackbone {\r\n\t\t\tpublic TriangleBackbone(Vector2 A, Vector2 B, Vector2 C) {\r\n\t\t\t\tventrices = new Vector2[] { A, B, C }; // Store vector points of triangle\r\n\t\t\t\tContainer = GlobalVars.Physics.GetContainerRectFromVectors(A, B, C);\r\n\t\t\t}\r\n\r\n\t\t\tprivate float Side(int VectorIndex1, int VectorIndex2, Vector2 point) {\r\n\t\t\t\tVector2 A = this[VectorIndex1], B = this[VectorIndex2]; // Desired vectors for size calculation\r\n\r\n\t\t\t\treturn (B.Y - A.Y) * (point.X - A.X) + (-B.X + A.X) * (point.Y - A.Y); // Return dot product\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tprivate float SquarePointToSegmentDistance(int VectorIndex1, int VectorIndex2, Vector2 point) {\r\n\t\t\t\tFunc<Vector2, Vector2, Vector2, float> CalculateSquareLength = (v1, v2, v3) => {\r\n\t\t\t\t\treturn (v1.X - v3.X) * (v2.X - v3.X) + (v1.Y - v3.Y) * (v2.Y - v3.Y);\r\n\t\t\t\t}; // Lambda Function to simplify SquareLength Calculations\r\n\r\n\t\t\t\tVector2 A = this[VectorIndex1], B = this[VectorIndex2]; // Store vector instances used by method\r\n\r\n\t\t\t\tfloat A_B_SquareLength = CalculateSquareLength(B, B, A); // Square Length from Point A to Point B\r\n\r\n\t\t\t\tfloat dotProduct = CalculateSquareLength(point, B, A) / A_B_SquareLength;\r\n\r\n\t\t\t\tif\t\t(dotProduct < 0) return CalculateSquareLength(point, point, A);\r\n\t\t\t\telse if (dotProduct > 1) return CalculateSquareLength(point, point, B);\r\n\t\t\t\telse return CalculateSquareLength(A, A, point) - dotProduct * dotProduct * A_B_SquareLength;\r\n\t\t\t}\r\n\r\n\t\t\t/// <summary> Determines if given point lies within a Triangle </summary>\r\n\t\t\t/// <param name=\"intVect\">Intersection Vector</param>\r\n\t\t\t/// <returns>Boolean indicating intersection</returns>\r\n\t\t\tpublic bool NaivePointIntersectionCheck(Vector2 intVect) {\r\n\t\t\t\t// Stores whether this.side >= 0 for index pairs (0, 1) && (1, 2) && (2, 0) in respective order\r\n\t\t\t\tvar checks = (from X in Enumerable.Range(0, 3) select Side(X, (X + 1 < 3) ? X + 1 : 0, intVect) >= 0).ToArray();\r\n\r\n\t\t\t\treturn checks.Aggregate((a, b) => a && b); // returns true only if all 3 sides evaluate to >= 0. Else false\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tpublic bool TriBoundaryBoxIntersectionCheck(Vector2 point) { return Container.Contains(point); }\r\n\r\n\t\t\tpublic bool Intersects(Vector2 point) { // Compound intersection check with Vector point\r\n\t\t\t\tif (!TriBoundaryBoxIntersectionCheck(point)) return false; /* Prevents Pointless CPU Waste */ else {\r\n\t\t\t\t\treturn NaivePointIntersectionCheck(point) // If point is whithin triangle\r\n\t\t\t\t\t\t|| SquarePointToSegmentDistance(0, 1, point) <= EPSILON_SQRD // Or lies on edge\r\n\t\t\t\t\t\t|| SquarePointToSegmentDistance(1, 2, point) <= EPSILON_SQRD // Of any of the\r\n\t\t\t\t\t\t|| SquarePointToSegmentDistance(2, 0, point) <= EPSILON_SQRD; // Triangles Lines\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/// <param name=\"A1\">Line 01 Start Point</param> <param name=\"A2\">Line 01 End Point</param>\r\n\t\t\t/// <param name=\"B1\">Line 02 Start Point</param> <param name=\"B2\">Line 02 End Point</param>\r\n\t\t\t/// <remarks>from http://stackoverflow.com/questions/14480124/how-do-i-detect-triangle-and-rectangle-intersection </remarks>\r\n\t\t\tpublic bool LineIntersects(Vector2 A1, Vector2 A2, Vector2 B1, Vector2 B2) {\r\n\t\t\t\tFunc<Vector2, Vector2, float, float> DotPerp = (vect1, vect2, denom) => {\r\n\t\t\t\t\treturn ((vect1.X * vect2.Y) - (vect1.Y * vect2.X)) / denom;\r\n\t\t\t\t};\r\n\r\n\t\t\t\tVector2[] BCD = new Vector2[] { A2 - A1, B1 - A1, B2 - B1 };\r\n\r\n\t\t\t\tfloat BDPerp = DotPerp(BCD[0], BCD[2], 1); // Whether vectors are perpendicular\r\n\r\n\t\t\t\tif (BDPerp == 0) { return false; } /* Parallel hence INFINITE Intersection points */ else {\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(1, 2)) {\r\n\t\t\t\t\t\tfloat TU = DotPerp(BCD[(X + 1 < 3) ? X : 1], BCD[(X + 1 < 3) ? X + 1 : 0], BDPerp);\r\n\t\t\t\t\t\tif (TU < 0 || TU > 1) { return false; } // No intersection between lines has occured\r\n\t\t\t\t\t};\r\n\r\n\t\t\t\t\treturn true; // If all checks have succesfully finished, then collision has occured\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic bool LineIntersects(Line A, Line B) { return LineIntersects(A.pointA, A.pointB, B.pointA, B.pointB); }\r\n\r\n\t\t\tpublic void Offset(Vector2 offset) {\r\n\t\t\t\tforeach (int X in Enumerable.Range(0, ventrices.Length))\r\n\t\t\t\t\tventrices[X] += offset; // Push each vertex\r\n\r\n\t\t\t\tContainer.Offset(offset); // Offset container rectangle\r\n\t\t\t}\r\n\r\n\t\t\tpublic Rectangle Container { get; private set; }\r\n\r\n\t\t\tpublic Vector2 this[int index] { get { return ventrices[index]; } set { ventrices[index] = value; } }\r\n\r\n\t\t\tpublic Vector2[] ventrices; // Get all vertxes stored by triangle\r\n\r\n\t\t\tpublic static float EPSILON = 0.001f, EPSILON_SQRD = EPSILON * EPSILON;\r\n\t\t}\r\n\r\n\t\t/// <summary>Paramterless Constructor, must call Initialize</summary>\r\n\t\tprotected IBTriangle() { }\r\n\t\t\r\n\t\tpublic IBTriangle(Vector2 A, Vector2 B, Vector2 C) { this.Initialize(A, B, C); }\r\n\r\n\t\t/// <summary> Constructor Taking Various Integers To Form Vectorial Points for Triangle </summary>\r\n\t\t/// <param name=\"X1\">X Value of Point A in Triangle</param> <param name=\"Y1\">Y Value of Point A in Triangle</param>\r\n\t\t/// <param name=\"X2\">X Value of Point B in Triangle</param> <param name=\"Y2\">Y Value of Point B in Triangle</param>\r\n\t\t/// <param name=\"X3\">X Value of Point C in Triangle</param> <param name=\"Y3\">Y Value of Point C in Triangle</param>\r\n\t\tpublic IBTriangle(int X1, int Y1, int X2, int Y2, int X3, int Y3) \r\n\t\t\t: this(new Vector2(X1, Y1), new Vector2(X2, Y2), new Vector2(X3, Y3)) { }\r\n\t\t\r\n\t\tprotected void Initialize(Vector2 A, Vector2 B, Vector2 C) {\r\n\t\t\tbackBone = new TriangleBackbone(A, B, C);\r\n\t\t}\r\n\t\t\r\n\t\tpublic void Offset(Vector2 offset) { backBone.Offset(offset); }\r\n\r\n\t\tpublic void Offset(float X = 0, float Y = 0) { Offset(new Vector2(X, Y)); }\r\n\r\n\t\tpublic void Draw(Color? color = null, int lineThickness = 1) {\r\n\t\t\tforeach (Line line in GV.Convert.TriangleTo3Lines(this)) {\r\n\t\t\t\tGV.DrawMethods.DrawLine(line.pointA, line.pointB, color, lineThickness);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic static IBTriangle operator +(IBTriangle tri, Vector2 vect) {\r\n\t\t\tvar sum = new IBTriangle(tri[0], tri[1], tri[2]);\r\n\t\t\tsum.Offset(vect); return sum;\r\n\t\t}\r\n\t\t\r\n\t\tpublic static IBTriangle operator +(IBTriangle tri, int value) {\r\n\t\t\tvar sum = new IBTriangle(tri[0], tri[1], tri[2]);\r\n\t\t\tsum.Offset(new Vector2(value)); return sum;\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn String.Format(\"TRIANGLE : A {0} | B {1} | C {2}\", this[0], this[1], this[2]);\r\n\t\t}\r\n\t\t\r\n\t\tpublic Vector2 this[int index] { get { return backBone.ventrices[index]; } }\r\n\r\n\t\tpublic Vector2[] Ventrices { get { return backBone.ventrices; } } // Ventrices\r\n\t\t\r\n\t\tpublic IBRectangle Container { get { return backBone.Container; } }\r\n\r\n\t\tpublic TriangleBackbone backBone; // TriangleClass Backbone Declaration\r\n\t}\r\n\r\n\t/// <summary>Variation of triangle class which is exclusively right angled</summary>\r\n\tpublic class IBRightAngledTriangle : IBTriangle {\r\n\t\t/// <summary>Enumeration storing various right angled triangle types</summary>\r\n\t\tpublic enum BlockType {\r\n\t\t\t/// <summary>Type = ◢</summary>\r\n\t\t\tA,\r\n\t\t\t/// <summary>Type = ◣</summary>\r\n\t\t\tB,\r\n\t\t\t/// <summary>Type = ◥</summary>\r\n\t\t\tC,\r\n\t\t\t/// <summary>Type = ◤</summary>\r\n\t\t\tD\r\n\t\t}\r\n\r\n\t\t/// <summary>Default Right Angled Triangle Constructor</summary>\r\n\t\t/// <param name=\"position\">Top left position of triangle</param>\r\n\t\t/// <param name=\"width\">Width of triangle</param>\r\n\t\t/// <param name=\"height\">Height of triangle</param>\r\n\t\t/// <param name=\"_type\">BlockType of given right angled triangle</param>\r\n\t\tpublic IBRightAngledTriangle(Vector2 position, int width, int height, BlockType _type) : base() {\r\n\t\t\t#region AllignmentSet\r\n\t\t\tswitch (_type) {\r\n\t\t\t\tcase BlockType.A:\r\n\t\t\t\tdefault:\r\n\t\t\t\t\t_rightAllignment = true;\r\n\t\t\t\t\t_topAllignment = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase BlockType.B:\r\n\t\t\t\t\t_rightAllignment = false;\r\n\t\t\t\t\t_topAllignment = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase BlockType.C:\r\n\t\t\t\t\t_rightAllignment = true;\r\n\t\t\t\t\t_topAllignment = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase BlockType.D:\r\n\t\t\t\t\t_rightAllignment = false;\r\n\t\t\t\t\t_topAllignment = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t#endregion\r\n\t\t\tBuildBoundary(position, width, height);\r\n\t\t}\r\n\r\n\t\t/// <summary>Alternative Right Angled Triangle Constructor</summary>\r\n\t\t/// <param name=\"position\">Top left position of triangle</param>\r\n\t\t/// <param name=\"width\">Width of triangle</param>\r\n\t\t/// <param name=\"height\">Height of triangle</param>\r\n\t\t/// <param name=\"rightAllign\">Whether to allign the triangle to the right or not</param>\r\n\t\t/// <param name=\"topAllign\">Whether to allign the triangle to the top or not</param>\r\n\t\tpublic IBRightAngledTriangle(Vector2 position, int width, int height, bool rightAllign = true, bool topAllign = false) : base() {\r\n\t\t\t#region AllignmentSet\r\n\t\t\t_rightAllignment = rightAllign;\r\n\t\t\t_topAllignment = topAllign;\r\n\t\t\t#endregion\r\n\t\t\tBuildBoundary(position, width, height);\r\n\t\t}\r\n\r\n\t\t/// <summary>Calculates three vectors needed for given allignment</summary>\r\n\t\t/// <param name=\"position\">Top Left corner of triangle</param>\r\n\t\t/// <param name=\"width\">Width of triangle</param> \r\n\t\t/// <param name=\"height\">Height of triangle</param>\r\n\t\tprivate void BuildBoundary(Vector2 position, int width, int height) {\r\n\t\t\tVector2 A, B, C; // Vectorial positions of triangle axes\r\n\r\n\t\t\tif (rightAllignment && bottomAllignment) {\r\n\t\t\t\tA = position + new Vector2(width, height);\r\n\t\t\t\tB = position + new Vector2(0, height);\r\n\t\t\t\tC = position + new Vector2(width, 0);\r\n\r\n\t\t\t\ttype = BlockType.A;\r\n\t\t\t} else {\r\n\t\t\t\tA = position; // Set A to top left corner of sprite :)\r\n\r\n\t\t\t\tif (leftAllignment && topAllignment) {\r\n\t\t\t\t\tB = position + new Vector2(width, 0);\r\n\t\t\t\t\tC = position + new Vector2(0, height);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tB = position + new Vector2(width, height);\r\n\r\n\t\t\t\t\tif (leftAllignment && bottomAllignment) {\r\n\t\t\t\t\t\tC = position + new Vector2(0, height);\r\n\t\t\t\t\t} else { // (rightAllignment && topAllignment)\r\n\t\t\t\t\t\tC = position + new Vector2(width, 0);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tthis.Initialize(A, B, C);\r\n\t\t}\r\n\r\n\t\tpublic static BlockType AllignmentsToBlockType(bool rightAllign, bool topAllign) {\r\n\t\t\tif (rightAllign && !topAllign) {\r\n\t\t\t\treturn BlockType.A;\r\n\t\t\t} else if (!rightAllign && !topAllign) {\r\n\t\t\t\treturn BlockType.B;\r\n\t\t\t} else if (rightAllign && topAllign) {\r\n\t\t\t\treturn BlockType.C;\r\n\t\t\t} else { // !rightAllign && topAllign\r\n\t\t\t\treturn BlockType.D;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>What type of right angle this is</summary>\r\n\t\tpublic BlockType type;\r\n\r\n\t\t#region PrivateAllignmentVars\r\n\t\tprivate bool _rightAllignment;\r\n\t\tprivate bool _topAllignment;\r\n\t\t#endregion\r\n\r\n\t\t#region AllignmentAttributes\r\n\t\t/// <summary>Whether triangle is alligned to the right</summary>\r\n\t\tpublic bool rightAllignment { get { return _rightAllignment; } }\r\n\t\t/// <summary>Whether triangle is alligned to the left</summary>\r\n\t\tpublic bool leftAllignment { get { return !_rightAllignment; } }\r\n\t\t/// <summary>Wheter triangle is alligned to the top</summary>\r\n\t\tpublic bool topAllignment { get { return _topAllignment; } }\r\n\t\t/// <summary>Whether triangle is alligned to the bottom</summary>\r\n\t\tpublic bool bottomAllignment { get { return !_topAllignment; } }\r\n\t\t#endregion\r\n\t}\r\n}" }, { "alpha_fraction": 0.6898203492164612, "alphanum_fraction": 0.6994011998176575, "avg_line_length": 26.305084228515625, "blob_id": "2fca1ac9d0d8ab08330eaf40030f6e4531d44877", "content_id": "dffeeb13f7c30d2053964cc5a1d6a9eb4a0b8a76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 148, "num_lines": 59, "path": "/HollowAether/Lib/Global/GameWindow/GameWindowAssets/TextButton.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic sealed class TextButton : Button {\r\n\t\tpublic TextButton(Vector2 position, String buttonText, int width=SPRITE_WIDTH, int height=SPRITE_HEIGHT, String fontName=DEFAULT_FONT_ID) \r\n\t\t\t: base(position, width, height) {\r\n\t\t\tfontID = fontName;\r\n\t\t\tSetText(buttonText);\r\n\t\t}\r\n\r\n\t\tpublic void SetText(String text) {\r\n\t\t\tVector2 size = font.MeasureString(text);\r\n\r\n\t\t\ttextPosition = new Vector2(\r\n\t\t\t\tPosition.X + (0.5f * (Width - size.X)),\r\n\t\t\t\tPosition.Y + (0.5f * (Height - size.Y))\r\n\t\t\t);\r\n\r\n\t\t\tbuttonText = text; // Store buttons text\r\n\t\t}\r\n\r\n\t\tpublic override void Initialize(string textureKey) {\r\n\t\t\tbase.Initialize(textureKey);\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t}\r\n\r\n\t\tpublic override void Draw() {\r\n\t\t\tbase.Draw();\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(font, buttonText, textPosition, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, Layer+0.001f);\r\n\t\t}\r\n\t\t\r\n\t\tprivate SpriteFont font { get { return GV.MonoGameImplement.fonts[fontID]; } }\r\n\t\tprivate String fontID;\r\n\t\tprivate string buttonText;\r\n\t\tprivate Vector2 textPosition;\r\n\t\tpublic const String DEFAULT_FONT_ID = \"homescreen\";\r\n\r\n\t\tpublic new Vector2 Position { get { return base.Position; } set {\r\n\t\t\t\tbase.Position = value;\r\n\t\t\t\tSetText(buttonText);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.715684711933136, "alphanum_fraction": 0.7172901034355164, "avg_line_length": 30.44270896911621, "blob_id": "a044f487f24ccc2c24147611ede9ee14ff00f6c4", "content_id": "c59c8c2fcead196d356dc7b1d8b4dc8654b53cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6231, "license_type": "no_license", "max_line_length": 114, "num_lines": 192, "path": "/HollowAether/Lib/GAssets/Boundary/Container/Labelled.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing HollowAether.Lib.GAssets.Boundary;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic struct LabelledBoundaryContainer : ILabelledBoundaryContainer {\r\n\t\tpublic LabelledBoundaryContainer(Rectangle spriteRect, params Tuple<String, IBoundary>[] boundaries) {\r\n\t\t\tlabelBoundaryCollection = new Dictionary<String, IBoundary>();\r\n\t\t\tinitialDimensions = _container = Rectangle.Empty;\r\n\t\t\t_deltaPositions = DeltaPositions.Empty;\r\n\t\t\tSpriteRect = spriteRect;\r\n\r\n\t\t\t// This has been assigned to now.\r\n\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t\tBuildDeltaPositions(spriteRect);\r\n\t\t}\r\n\r\n\t\tpublic void BuildDeltaPositions(Rectangle? spriteRect) {\r\n\t\t\t_deltaPositions = (spriteRect.HasValue) ? BoundaryShared.GetDeltaPositions(spriteRect.Value, Container)\r\n\t\t\t\t: _deltaPositions = DeltaPositions.Empty; // If has value build, otherwise create empty positions\r\n\t\t}\r\n\r\n\t\tpublic void Add(IBoundary boundary) {\r\n\t\t\tAdd(String.Empty, boundary);\r\n\t\t}\r\n\r\n\t\tpublic void Add(String name, IBoundary boundary) {\r\n\t\t\tlabelBoundaryCollection[name] = boundary;\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t\tBuildDeltaPositions(SpriteRect);\r\n\t\t}\r\n\r\n\t\tpublic void RemoveBoundary(String name) {\r\n\t\t\tlabelBoundaryCollection.Remove(name);\r\n\t\t\t_container = GetBoundaryArea();\r\n\t\t\tBuildDeltaPositions(SpriteRect);\r\n\t\t}\r\n\r\n\t\tpublic void RemoveBoundary(IBoundary other) {\r\n\t\t\tRemoveBoundary(GlobalVars.CollectionManipulator.DictionaryGetKeyFromValue(labelBoundaryCollection, other));\r\n\t\t}\r\n\r\n\t\tpublic void Offset(float X=0f, float Y=0f) {\r\n\t\t\tforeach (String key in labelBoundaryCollection.Keys)\r\n\t\t\t\tlabelBoundaryCollection[key].Offset(X, Y);\r\n\r\n\t\t\t_container.Offset(X, Y);\r\n\t\t}\r\n\r\n\t\tpublic void Offset(Vector2 offset) {\r\n\t\t\tOffset(offset.X, offset.Y);\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundaryContainer other) {\r\n\t\t\tif (!other.Container.Intersects(this._container))\r\n\t\t\t\treturn false; // prevent CPU waste\r\n\r\n\t\t\tforeach (IBoundary tarBoundary in other.Boundaries) {\r\n\t\t\t\tif (Intersects(tarBoundary, true)) return true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundaryContainer other, Vector2? offset) {\r\n\t\t\tif (offset.HasValue) Offset(offset.Value);\r\n\t\t\tbool success = Intersects(other);\r\n\t\t\tif (offset.HasValue) Offset(-offset.Value);\r\n\r\n\t\t\treturn success; // return successful collision after offset\r\n\t\t}\r\n\r\n\t\tpublic bool Intersects(IBoundary boundary, bool checkContainerCollision=true) {\r\n\t\t\tif (checkContainerCollision) {\r\n\t\t\t\tif (!boundary.Container.Intersects(this._container))\r\n\t\t\t\t\treturn false; // prevent CPU waste\r\n\t\t\t\t// else Ignore returning and carry on \r\n\t\t\t}\r\n\r\n\t\t\tforeach (IBoundary selfBoundary in Boundaries) {\r\n\t\t\t\tif (selfBoundary.Intersects(boundary))\r\n\t\t\t\t\treturn true; // first collision return\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic IBoundaryContainer GetCopy(Vector2? offset) {\r\n\t\t\tLabelledBoundaryContainer newContainer = this;\r\n\r\n\t\t\tif (offset.HasValue)\r\n\t\t\t\tnewContainer.Offset(offset.Value);\r\n\r\n\t\t\treturn newContainer;\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle GetBoundaryArea() {\r\n\t\t\treturn BoundaryShared.GetBoundaryArea(this);\r\n\t\t}\r\n\r\n\t\tpublic IntersectingPositions GetNonIntersectingPositions(IBoundaryContainer other) {\r\n\t\t\tIntersectingPositions positions = IntersectingPositions.Empty;\r\n\r\n\t\t\tforeach (IBoundary b in Boundaries) {\r\n\t\t\t\tforeach (IBoundary b2 in other.Boundaries) {\r\n\t\t\t\t\tif (!b.Intersects(b2)) continue; // No intersection, skip 4ward\r\n\t\t\t\t\tpositions.Set(CollisionCalculators.CalculateCollision(b, b2));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpositions -= new IntersectingPositions() {\r\n\t\t\t\t{Direction.Top, Container.Height + DeltaPositions.height },\r\n\t\t\t\t{Direction.Bottom, DeltaPositions.height },\r\n\t\t\t\t{Direction.Left, Container.Width + DeltaPositions.right },\r\n\t\t\t\t{Direction.Right, DeltaPositions.left },\r\n\t\t\t};\r\n\r\n\t\t\treturn positions;\r\n\t\t}\r\n\r\n\t\tpublic IntersectingPositions GetNonIntersectingPositions(IBoundaryContainer other, params String[] boundaries) {\r\n\t\t\tif (boundaries.Length == 0) return GetNonIntersectingPositions(other);\r\n\t\t\tIntersectingPositions positions = IntersectingPositions.Empty;\r\n\r\n\r\n\t\t\tforeach (String boundaryKey in boundaries) {\r\n\t\t\t\tif (!labelBoundaryCollection.ContainsKey(boundaryKey))\r\n\t\t\t\t\tthrow new HollowAetherException($\"Boundary Key {boundaryKey} not found\");\r\n\r\n\t\t\t\tforeach (IBoundary boundary in other) {\r\n\t\t\t\t\tpositions.Set(CollisionCalculators.CalculateCollision(boundary, this[boundaryKey]));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpositions -= new IntersectingPositions() {\r\n\t\t\t\t{Direction.Top, Container.Height + DeltaPositions.height },\r\n\t\t\t\t{Direction.Bottom, DeltaPositions.height },\r\n\t\t\t\t{Direction.Left, Container.Width + DeltaPositions.right },\r\n\t\t\t\t{Direction.Right, DeltaPositions.left },\r\n\t\t\t};\r\n\r\n\t\t\treturn positions;\r\n\t\t}\r\n\r\n\t\tpublic String[] GetIntersectingBoundaryLabels(IBoundaryContainer other) {\r\n\t\t\tHashSet<String> labels = new HashSet<String>();\r\n\r\n\t\t\tforeach (String key in this.labelBoundaryCollection.Keys) {\r\n\t\t\t\tforeach (IBoundary boundary in other) {\r\n\t\t\t\t\tif (this[key].Intersects(boundary))\r\n\t\t\t\t\t\tlabels.Add(key);\r\n\r\n\t\t\t\t\tif (labels.Count == Boundaries.Count())\r\n\t\t\t\t\t\treturn labels.ToArray();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn labels.ToArray();\r\n\t\t}\r\n\r\n\t\tIEnumerator IEnumerable.GetEnumerator() {\r\n\t\t\treturn GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IEnumerator<IBoundary> GetEnumerator() {\r\n\t\t\treturn Boundaries.Cast<IBoundary>().GetEnumerator();\r\n\t\t}\r\n\r\n\t\tpublic IBoundary this[String label] {\r\n\t\t\tget { return labelBoundaryCollection[label]; }\r\n\t\t\tset { labelBoundaryCollection[label] = value; }\r\n\t\t}\r\n\r\n\t\tpublic IBRectangle Container { get { return _container; } }\r\n\t\tpublic IBoundary[] Boundaries { get { return labelBoundaryCollection.Values.ToArray(); } }\r\n\t\tpublic DeltaPositions DeltaPositions { get { return _deltaPositions; } }\r\n\r\n\t\tprivate IBRectangle _container;\r\n\t\tpublic IBRectangle initialDimensions; // for collision purpose;\r\n\t\tprivate DeltaPositions _deltaPositions; // Changes between delta\r\n\t\tDictionary<String, IBoundary> labelBoundaryCollection;\r\n\t\tpublic Rectangle SpriteRect { get; private set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7685873508453369, "alphanum_fraction": 0.7685873508453369, "avg_line_length": 41.040000915527344, "blob_id": "f43f924308ad9b4eea47fdcebb77c6ddce6ae37c", "content_id": "a602541cb97e8da82d278d6c7cfb673c85d2e56a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 100, "num_lines": 50, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/GameEntityExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nusing System.Runtime.Serialization;\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tpublic class EntityException : HollowAetherException {\r\n\t\tpublic EntityException() : base() { }\r\n\r\n\t\tpublic EntityException(String msg) : base(msg) { }\r\n\r\n\t\tpublic EntityException(String msg, Exception inner) : base(msg, inner) { }\r\n\r\n\t\tpublic EntityException(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t}\r\n\r\n\tpublic class EntityAttributeInvalidTypeAssignmentException : EntityException {\r\n\t\tpublic EntityAttributeInvalidTypeAssignmentException(Type arg, Type desired)\r\n\t\t: base($\"Cannot Assign Value Of Type '{arg}' To Entity Attribute Of Type {desired}\") { }\r\n\t\tpublic EntityAttributeInvalidTypeAssignmentException(Type arg, Type desired, Exception inner)\r\n\t\t: base($\"Cannot Assign Value Of Type '{arg}' To Entity Attribute Of Type {desired}\", inner) { }\r\n\t}\r\n\r\n\tpublic class EntityAttributeReadOnlyAssignmentAttemptException : EntityException {\r\n\t\tpublic EntityAttributeReadOnlyAssignmentAttemptException() \r\n\t\t\t: base($\"Cannot Assign Value For Read Only Entity Attribute\") { }\r\n\t\tpublic EntityAttributeReadOnlyAssignmentAttemptException(Exception inner) \r\n\t\t\t: base($\"Cannot Assign Value For Read Only Entity Attribute\", inner) { }\r\n\t}\r\n\r\n\tpublic class EntityAttributeReadOnlyDeletionException : EntityException {\r\n\t\tpublic EntityAttributeReadOnlyDeletionException()\r\n\t\t\t: base($\"Cannot Delete A Read Only Entity Attributes Value\") { }\r\n\t\tpublic EntityAttributeReadOnlyDeletionException(Exception inner)\r\n\t\t\t: base($\"Cannot Delete A Read Only Entity Attributes Value\", inner) { }\r\n\t}\r\n\r\n\tpublic class EntityAttributeUnassignedValueRetrievalException : EntityException {\r\n\t\tpublic EntityAttributeUnassignedValueRetrievalException()\r\n\t\t\t: base($\"Cannot Get Unassigned Entity Attribute\") { }\r\n\t\tpublic EntityAttributeUnassignedValueRetrievalException(Exception inner)\r\n\t\t\t: base($\"Cannot Get Unassigned Entity Attribute\", inner) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7352454662322998, "alphanum_fraction": 0.7385548949241638, "avg_line_length": 33.54901885986328, "blob_id": "35cea57694ed67f78549eca9c3eb6c1fac69968c", "content_id": "59648afe39cbfe144273ac05a9d457a3e6697916", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1815, "license_type": "no_license", "max_line_length": 131, "num_lines": 51, "path": "/HollowAether/Lib/Global/GlobalVars/Physics.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class Physics {\r\n\t\t\tpublic static float GetJumpVelocity(float gravity, float maxJumpHeight) {\r\n\t\t\t\treturn (float)Math.Sqrt(2 * gravity * maxJumpHeight);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static float CalculateGravity(float maxJumpHeight, float timeToApex) {\r\n\t\t\t\treturn 2 * maxJumpHeight / (float)Math.Pow(timeToApex, 2);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static float GetEarlyJumpEndVelocity(float currentVelocity, float gravity, float maxJumpHeight, float minJumpHeight) {\r\n\t\t\t\treturn (float)Math.Sqrt(Math.Pow(currentVelocity, 2) + (2 * gravity * (maxJumpHeight - minJumpHeight)));\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Rectangle GetContainerRectFromVectors(params Vector2[] points) {\r\n\t\t\t\tfloat[] xValues = (from V in points select V.X).ToArray(), yValues = (from V in points select V.Y).ToArray();\r\n\t\t\t\tfloat minX = xValues.Min(), maxX = xValues.Max(), minY = yValues.Min(), maxY = yValues.Max(); // Store points\r\n\r\n\t\t\t\treturn new Rectangle((int)Math.Round(minX), (int)Math.Round(minY), (int)Math.Round(maxX - minX), (int)Math.Round(maxY - minY));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7097752690315247, "alphanum_fraction": 0.7128077149391174, "avg_line_length": 39.540740966796875, "blob_id": "9a770dd8bf17e7246e90a5c2c6408a00e3f0155d", "content_id": "fa158b648d013e5cbfb8867adeb45b9b36d90f48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5608, "license_type": "no_license", "max_line_length": 122, "num_lines": 135, "path": "/HollowAether/Lib/InputOutput/Parsers/MapParser.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing IOMan = HollowAether.Lib.InputOutput.InputOutputManager;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing System.Text.RegularExpressions;\r\nusing HollowAether.Lib.MapZone;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tstatic class MapParser {\r\n\t\tpublic static void Parse(Map _map) {\r\n\t\t\tmap = _map; // Store reference to map\r\n\t\t\tString[] fContents = ReadMapFile();\r\n\t\t\t\r\n\t\t\tfor (lineIndex = 0; lineIndex < fContents.Length; lineIndex++) {\r\n\t\t\t\tString line = fContents[lineIndex]; // store to simplify access\r\n\r\n\t\t\t\tif (String.IsNullOrWhiteSpace(line)) continue; // skip when empty\r\n\r\n\t\t\t\tif (IsZoneDefinition(line)) ExecuteZoneDefintion(line);\r\n\t\t\t\telse if (IsStartZoneDefintion(line)) ExecuteStartZoneDefintion(line);\r\n\t\t\t\telse if (IsFlagDefintion(line)) ExecuteFlagDefintion(line);\r\n\t\t\t\telse throw new MapSyntaxException(map.FilePath, $\"Couldn't Interpret Line '{line}'\", lineIndex);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Opens Map File and reads contents + Performs necessary initial checks</summary>\r\n\t\t/// <returns>Stripped (by linebreak) contents of zone file with removed comments</returns>\r\n\t\tprivate static String[] ReadMapFile() {\r\n\t\t\tString mapContents; // Pointer to desired map contents\r\n\r\n\t\t\ttry { mapContents = IOMan.ReadEncryptedFile(map.FilePath, GV.Encryption.oneTimePad).Replace(\"\\r\", \"\"); } \r\n\t\t\tcatch { throw new MapFileCouldntBeReadException(map.FilePath); /* Couldn't read map file => throw exception */ }\r\n\r\n\t\t\tif (!Parser.HeaderCheck(mapContents, Map.MAP_FILE_HEADER)) throw new MapHeaderException(map.FilePath); // Header failed\r\n\r\n\t\t\tGV.Misc.RemoveComments(ref mapContents); // remove comment notations from file contents because they serve no revelence\r\n\r\n\t\t\treturn mapContents.Substring(Map.MAP_FILE_HEADER.Length, mapContents.Length - Map.MAP_FILE_HEADER.Length).Split('\\n');\r\n\t\t}\r\n\r\n\t\t#region LineCheckerMethods\r\n\t\tprivate static void ExecuteZoneDefintion(String line) {\r\n\t\t\tVector2 position = Vector2Parser(line); // Store new zone definition\r\n\r\n\t\t\tif (map.ContainsZone(position)) // If map already has a zone at the given zone index\r\n\t\t\t\tthrow new MapFileDefinesZoneAtSamePositionTwiceException(map.FilePath, position, lineIndex);\r\n\r\n\t\t\tchar visibilityIndicator = line.Substring(0, 1).ToUpper().ToCharArray()[0];\r\n\r\n\t\t\tif (!(new char[] { 'N', 'V', 'H' }).Contains(visibilityIndicator))\r\n\t\t\t\tthrow new MapUnknownVisibilityException(map.FilePath, visibilityIndicator.ToString(), lineIndex);\r\n\t\t\t\r\n\t\t\tmap.AddZone(position, SystemPathExtracter(line), visibilityIndicator != 'H');\r\n\t\t}\r\n\r\n\t\tprivate static void ExecuteStartZoneDefintion(String line) {\r\n\t\t\tmap.SetCurrentZone(Vector2Parser(line), true, false);\r\n\t\t}\r\n\r\n\t\tprivate static void ExecuteFlagDefintion(String line) {\r\n\t\t\tString flagName = BracketParser(line); // Extract contents of parentheses\r\n\r\n\t\t\tif (GV.MapZone.globalAssets.Keys.Contains(flagName)) // Flag exists already\r\n\t\t\t\tthrow new MapRepeatedFlagCreationException(map.FilePath, flagName, lineIndex);\r\n\r\n\t\t\tMatch hasValue = Regex.Match(line, @\"=([Ff]alse|[Tt]rue)\"); // If definition includes default value\r\n\r\n\t\t\tif (!hasValue.Success) GV.MapZone.globalAssets.Add(flagName, new FlagAsset(flagName));\r\n\t\t\telse GV.MapZone.globalAssets.Add(flagName, new FlagAsset(flagName, BooleanParser(hasValue.Value)));\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region LineCheckerMethods\r\n\t\t/// <summary>Checks if line is a zone definition</summary>\r\n\t\tprivate static bool IsZoneDefinition(String line) { // N-(Position) C:\\Path\\To\\Zone\r\n\t\t\treturn Regex.IsMatch(line, @\"\\w-\\(.+\\) [^ \\n\\r]+\\\\[^ \\n\\r]+\");\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks if line is a Start Zone definition</summary>\r\n\t\tprivate static bool IsStartZoneDefintion(String line) { // [StartZone(X: 000, Y: 000)]\r\n\t\t\treturn Regex.IsMatch(line, @\"\\[[Ss]tart[Zz]one.+\\]\");\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks if line is a Flag definition</summary>\r\n\t\tprivate static bool IsFlagDefintion(String line) { // [DefineFlag(FlagName)] || [DefineFlag(FlagName)=True]\r\n\t\t\treturn Regex.IsMatch(line, @\"\\[[Dd]efine[Ff]lag.+\\]\");\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t#region ParserWrapper\r\n\t\tprivate static Vector2 Vector2Parser(String line) {\r\n\t\t\ttry { return Parser.Vector2Parser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new MapLineConversionException(map.FilePath, line, \"Vector2\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static Boolean BooleanParser(String line) {\r\n\t\t\ttry { return Parser.BooleanParser(line); } catch (Exception e) {\r\n\t\t\t\tthrow new MapLineConversionException(map.FilePath, line, \"Boolean\", lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static String BracketParser(String line) {\r\n\t\t\ttry { return Parser.GetValueInParentheses(line); } catch (Exception e) {\r\n\t\t\t\tString message = $\"Couldn't Extract Contents of Parentheses In Line '{line}'\";\r\n\t\t\t\tthrow new MapSyntaxException(map.FilePath, message, lineIndex, e); // throw\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate static String SystemPathExtracter(String line) {\r\n\t\t\ttry { return Parser.SystemPathExtracter(line); } catch (Exception e) {\r\n\t\t\t\tString message = $\"Couldn't Find Path In Line '{line}'\";\r\n\t\t\t\tthrow new MapSyntaxException(map.FilePath, message, lineIndex, e);\r\n\t\t\t}\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\t/// <summary>Reference to map file</summary>\r\n\t\tprivate static Map map;\r\n\r\n\t\t/// <summary>Reference to line index</summary>\r\n\t\tprivate static int lineIndex;\r\n\t}\r\n}" }, { "alpha_fraction": 0.718898594379425, "alphanum_fraction": 0.7272186875343323, "avg_line_length": 47.009708404541016, "blob_id": "8b3df31ace140d66dd41dda0f12cc8a05483238f", "content_id": "efa99e0a7cbf96d5b5611f4a750e204a4df3ff5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5050, "license_type": "no_license", "max_line_length": 116, "num_lines": 103, "path": "/HollowAether/Lib/GAssets/Items/Points/TreasureItem.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Definition for coin like object. Can be used for dash points as well</summary>\r\n\tpublic abstract class TreasureItem : VolatileBodySprite, ITimeoutSupportedAutoInteractable {\r\n\t\t/// <param name=\"position\">Initial position for sprite</param>\r\n\t\t/// <param name=\"randMove\">Whether to let sprite have initial random velocity</param>\r\n\t\t/// <param name=\"width\">Width of sprite</param> <param name=\"height\">Height of sprite</param>\r\n\t\t/// <param name=\"texture\">Texture of sprite</param> <param name=\"timeout\">Time for sprite to exist</param>\r\n\t\tpublic TreasureItem(Vector2 position, int width, int height, int timeout, bool randMove=true)\r\n\t\t\t: base(position, width, height) {\r\n\t\t\tInitializeVolatility(VolatilityType.Timeout, timeout); // Exists for 5 secs\r\n\t\t\tif (randMove) CalculateMiscellaneousPush(); // Give coin horizontal velocity\r\n\t\t\tLayer = 0.65f;\r\n\t\t}\r\n\r\n\t\tprivate void CalculateMiscellaneousPush() {\r\n\t\t\tint randVelocity = GV.Variables.random.Next(MinRandMoveVelocity, MaxRandMoveVelocity); // Random velocity to move\r\n\t\t\tfloat angle = GV.BasicMath.DegreesToRadians(GV.Variables.random.Next(MinRandMoveAngle, MaxRandMoveAngle));\r\n\t\t\tinertialDirection = (GV.Variables.random.Next(0, 2) == 0) ? +1 : -1; // Direction coin moving is randomised\r\n\t\t\t\r\n\t\t\tvelocity.X = -inertialDirection * randVelocity * (float)Math.Cos(angle); // Set initial horizontal velocity \r\n\t\t\tvelocity.Y = randVelocity * -1 * (float)Math.Sin(angle); // Set initial vertical velocity\r\n\t\t\t// Y Velocity is always negative so coin always travels upwards at beginning/start of coins movement\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed time as well, important, must come first.\r\n\r\n\t\t\tImplementGravity(); // Implement change in displacement & velocity due to gravitational acceleration\r\n\t\t\tOffsetSpritePosition(XDisplacement); // Implement horizontal displacement due to initial velocity\r\n\t\t\tUpdateHorizontalVelocity(); // Implement inertial accelearation acting against initial velocity\r\n\r\n\t\t\tif ((Falling(1, 0) ^ Falling(-1, 0)) && HasIntersectedTypes(GV.MonoGameImplement.BlockTypes))\r\n\t\t\t\tLinearCollisionHandler(); // If falling on either side but still intersected then handle\r\n\r\n\t\t\tif (InteractionTimeout > 0) \r\n\t\t\t\tInteractionTimeout -= GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\telse if(InteractCondition()) Interact(); // If player collides with coin then interact if viable\r\n\t\t}\r\n\r\n\t\tpublic virtual bool InteractCondition() {\r\n\t\t\treturn CanInteract && !Interacted && GV.MonoGameImplement.Player.Intersects(boundary);\r\n\t\t}\r\n\r\n\t\tpublic virtual void Interact() {\r\n\t\t\tVolatilityManager.Delete(this); // Delete when interacted\r\n\t\t\tInteracted = true; // Has been interacted with\r\n\t\t}\r\n\r\n\t\tprivate void CheckHorizontalCollision() {\r\n\t\t\tif ((Falling(1, 0) ^ Falling(-1, 0)) && HasIntersectedTypes(GV.MonoGameImplement.BlockTypes))\r\n\t\t\t\tLinearCollisionHandler(); // If falling on either side but still intersected then handle\r\n\t\t}\r\n\r\n\t\tprotected virtual void LinearCollisionHandler() {\r\n\t\t\tDirection direction = (inertialDirection < 0) ? Direction.Left : Direction.Right; // Get direction moving\r\n\t\t\tvar collided = CompoundIntersects(GV.MonoGameImplement.BlockTypes).Cast<ICollideable>().ToArray();\r\n\t\t\tfloat? newXPos = LoopGetPositionFromDirection(collided, direction); // Get new viable player position\r\n\t\t\tif (newXPos.HasValue) SetPosition(X: newXPos.Value); // Set coin position to edge of intersected item\r\n\t\t\t\r\n\t\t\tvelocity.X = 0; // For now stop coin moving. Later on can add affect to bounce coin upon collision\r\n\t\t}\r\n\r\n\t\tpublic void UpdateHorizontalVelocity() {\r\n\t\t\tif ((inertialDirection == 1 && velocity.X < 0) || (inertialDirection == -1 && velocity.X > 0)) {\r\n\t\t\t\tfloat horizontalOffset = horizontalInertialAcceleration * inertialDirection * elapsedTime;\r\n\r\n\t\t\t\tif (GV.Misc.SignChangedFromAddition(velocity.X, horizontalOffset))\r\n\t\t\t\t\tvelocity.X = 0; // If sign has changed between additions\r\n\t\t\t\telse velocity.X += horizontalOffset; // Add change due to acceleration\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate int inertialDirection;\r\n\r\n\t\tprivate float horizontalInertialAcceleration = 5f; // For Misc Push\r\n\r\n\t\tpublic override Vector2 TerminalVelocity { get; protected set; } = new Vector2(200);\r\n\t\t\r\n\t\tpublic bool Interacted { get; protected set; } = false;\r\n\r\n\t\tpublic bool CanInteract { get; protected set; } = true;\r\n\r\n\t\tpublic int InteractionTimeout { get; set; } = 0;\r\n \r\n\t\tprotected virtual int MinRandMoveAngle { get; set; } = 30;\r\n\r\n\t\tprotected virtual int MaxRandMoveAngle { get; set; } = 85;\r\n\r\n\t\tprotected virtual int MinRandMoveVelocity { get; set; } = 50;\r\n\r\n\t\tprotected virtual int MaxRandMoveVelocity { get; set; } = 85;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7382413148880005, "alphanum_fraction": 0.7382413148880005, "avg_line_length": 35.61538314819336, "blob_id": "ca26c2b5af5f7ef284abe72a7f750c447ef6900b", "content_id": "b727158a0f4d58a631831be8cbeef59e835efbd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 491, "license_type": "no_license", "max_line_length": 134, "num_lines": 13, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/INIParserExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tclass InvalidLineInINIFileException : HollowAetherException {\r\n\t\tpublic InvalidLineInINIFileException(String line, String file) : base($\"'{line}' is invalid, in {file}\") { }\r\n\r\n\t\tpublic InvalidLineInINIFileException(String line, String file, Exception inner) : base($\"'{line}' is invalid, in {file}\", inner) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.704123854637146, "alphanum_fraction": 0.7202722430229187, "avg_line_length": 46.03205108642578, "blob_id": "68b857eef266c9aace1b98a1eda39bfe3e371c24", "content_id": "610314fc056c514447605c18bd39ed9463dcca07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7495, "license_type": "no_license", "max_line_length": 152, "num_lines": 156, "path": "/HollowAether/Lib/GAssets/HUD/PointDisplay.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing HollowAether.Lib.Exceptions;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\tclass PointDisplay : IPushable {\r\n\t\tstatic PointDisplay() {\r\n\t\t\tdisplayBase = GV.TextureCreation.GenerateBlankTexture(063, 033, 000);\r\n\t\t\tdisplayBaseOverlay = GV.TextureCreation.GenerateBlankTexture(255, 255, 255);\r\n\t\t\tbarDarkOverlay = GV.TextureCreation.GenerateBlankTexture(255, 211, 090);\r\n\t\t\tbarBrightOverlay = GV.TextureCreation.GenerateBlankTexture(255, 248, 073);\r\n\t\t\tmaxCornerYellow = GV.TextureCreation.GenerateBlankTexture(255, 237, 066);\r\n\t\t\tmaxCenterRed = GV.TextureCreation.GenerateBlankTexture(255, 076, 025);\r\n\t\t\ttimeLoadingDark = GV.TextureCreation.GenerateBlankTexture(073, 073, 255);\r\n\t\t\ttimeLoadingBright = GV.TextureCreation.GenerateBlankTexture(073, 215, 255);\r\n\t\t}\r\n\r\n\t\tpublic PointDisplay(Vector2 position) {\r\n\t\t\tPosition = position;\r\n\t\t\tBuildBarRects();\r\n\t\t}\r\n\r\n\t\tpublic void PushTo(Vector2 position, float over = 0.8f) {\r\n\t\t\tif (PushArgs.PushValid(position, Position))\r\n\t\t\t\tPush(new PushArgs(position, Position, over));\r\n\t\t}\r\n\r\n\t\tpublic void Push(PushArgs args) { if (!BeingPushed) PushPack = args; }\r\n\r\n\t\tpublic void Update(bool updateAnimation) {\r\n\t\t\tfloat elapsedTime = GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds * (float)Math.Pow(10, -3);\r\n\r\n\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) {\r\n\t\t\t\tPushPack = null; // Delete push pack\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tDrawRect(displayBase, baseUpperRect); DrawRect(displayBase, baseLowerRect); // Draw base\r\n\r\n\t\t\tDrawRect(displayBaseOverlay, baseOverlayRectA); DrawRect(displayBaseOverlay, baseOverlayRectB); // Draw overlay\r\n\r\n\t\t\tfloat burstPointPercentage = GV.MonoGameImplement.Player.burstPoints / (float)Player.maxBurstPoints;\r\n\t\t\tfloat tNM = GV.MonoGameImplement.Player.timeNotMoving; // Store locally to shorten access length, etc.\r\n\t\t\tfloat timeoutPercentage = tNM / Player.TIME_BEFORE_POINT_GEN;\r\n\r\n\t\t\tif (burstPointPercentage == 1) DrawMaxIndicator(); // if 100% bar complete, draw indicators\r\n\t\t\telse if (tNM > 0 && tNM < Player.TIME_BEFORE_POINT_GEN) {\r\n\t\t\t\t// If less than 100% burst points, draw timer behind regular display bar\r\n\t\t\t\tDrawPercentageBar(timeoutPercentage, timeLoadingBright, timeLoadingDark);\r\n\t\t\t}\r\n\r\n\t\t\tDrawPercentageBar(burstPointPercentage, barDarkOverlay, barBrightOverlay);\r\n\t\t}\r\n\r\n\t\tprivate void DrawPercentageBar(float percentage, Texture2D textureDark, Texture2D textureBright) {\r\n\t\t\tpercentage = GV.BasicMath.Clamp<float>(percentage, 0, 1); // Prevent > one\r\n\t\t\tint width = (int)(percentage * variedBarBase.Width); // Calculate partial width\r\n\r\n\t\t\tRectangle A = variedBarBase, B = variedBarOverlay; // Creates shallow clones\r\n\t\t\tA.Width = width; B.Width = width; // Change doesn't affect original reference\r\n\r\n\t\t\tDrawRect(textureDark, A); DrawRect(textureBright, B); // Draws bar textures\r\n\t\t}\r\n\r\n\t\tprivate void DrawMaxIndicator() {\r\n\t\t\tDrawRect(maxCenterRed, maxCenterRectUpper);\r\n\t\t\tDrawRect(maxCenterRed, maxCenterRectLower);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectTL);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectTR);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectBL);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectBR);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectCTL);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectCTR);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectCBL);\r\n\t\t\tDrawRect(maxCornerYellow, maxCornerRectCBR);\r\n\t\t}\r\n\r\n\t\tprivate void DrawRect(Texture2D texture, Rectangle rect) {\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(texture, position + rect.Location.ToVector2(), rect, Color.White);\r\n\t\t}\r\n\r\n\t\tprivate void BuildBarRects() {\r\n\t\t\tPoint position = Point.Zero; // Start with initial point of nothing\r\n\r\n\t\t\tint BOD = BASE_OVERLAY_DIMENSIONS, VBHO = VARIED_BAR_HEIGHT_OFFSET, VBOH = VARIED_BAR_OVERLAY_HEIGHT;\r\n\t\t\tint MCRW = MAX_CENTER_RECT_WIDTH;\r\n\r\n\t\t\tbaseUpperRect = new Rectangle(position.X, position.Y, WIDTH, HEIGHT);\r\n\t\t\tbaseLowerRect = new Rectangle(position.X + BOD, baseUpperRect.Bottom, WIDTH - BOD, BOD);\r\n\r\n\t\t\tbaseOverlayRectA = new Rectangle(position.X, position.Y, WIDTH - BOD, BOD);\r\n\t\t\tbaseOverlayRectB = new Rectangle(position.X, position.Y + HEIGHT - BOD, WIDTH - BOD, BOD);\r\n\r\n\r\n\t\t\tPoint variedBarSize = new Point(baseUpperRect.Width - BOD, baseUpperRect.Height - (2 * BOD) - VBHO);\r\n\t\t\tvariedBarBase = new Rectangle(baseUpperRect.Location + new Point(0, BOD), variedBarSize);\r\n\r\n\t\t\tPoint variedBarOverlaySize = new Point(variedBarBase.Width, VBOH);\r\n\t\t\tPoint variedBarOverlayPosition = new Point(variedBarBase.X, variedBarBase.Center.Y - (VBOH / 2));\r\n\t\t\t\r\n\t\t\tvariedBarOverlay = new Rectangle(variedBarOverlayPosition, variedBarOverlaySize);\r\n\r\n\r\n\t\t\tPoint topLeftPosition = new Point(baseOverlayRectA.X, baseOverlayRectA.Y);\r\n\t\t\tPoint bottomLeftPosition = topLeftPosition + new Point(0, baseUpperRect.Height-BOD);\r\n\r\n\t\t\tmaxCornerRectTL = new Rectangle(topLeftPosition, new Point(BOD));\r\n\t\t\tmaxCornerRectTR = new Rectangle(topLeftPosition + new Point(baseOverlayRectA.Width-BOD, 0), new Point(BOD));\r\n\t\t\tmaxCornerRectBL = new Rectangle(bottomLeftPosition, new Point(BOD));\r\n\t\t\tmaxCornerRectBR = new Rectangle(bottomLeftPosition + new Point(baseOverlayRectA.Width-BOD, 0), new Point(BOD));\r\n\t\r\n\r\n\t\t\tint maxCenterRectX = topLeftPosition.X + ((variedBarBase.Width - MCRW) / 2);\r\n\r\n\t\t\tmaxCenterRectUpper = new Rectangle(new Point(maxCenterRectX, topLeftPosition.Y), new Point(MCRW, BOD));\r\n\t\t\tmaxCenterRectLower = new Rectangle(new Point(maxCenterRectX, bottomLeftPosition.Y), new Point(MCRW, BOD));\r\n\r\n\t\t\tmaxCornerRectCTL = new Rectangle(maxCenterRectUpper.Location - new Point(BOD, 0), new Point(BOD));\r\n\t\t\tmaxCornerRectCTR = new Rectangle(maxCenterRectUpper.Location - new Point(BOD - MCRW, 0), new Point(BOD));\r\n\t\t\tmaxCornerRectCBL = new Rectangle(maxCenterRectLower.Location - new Point(BOD, 0), new Point(BOD));\r\n\t\t\tmaxCornerRectCBR = new Rectangle(maxCenterRectLower.Location - new Point(BOD - MCRW, 0), new Point(BOD));\r\n\t\t}\r\n\r\n\t\tpublic void OffsetPosition(Vector2 offset) { position += offset.ToPoint().ToVector2(); }\r\n\r\n\t\tpublic void OffsetPosition(float X, float Y) { OffsetPosition(new Vector2(X, Y)); }\r\n\r\n\t\tRectangle baseUpperRect, baseLowerRect, baseOverlayRectA, baseOverlayRectB, variedBarBase, variedBarOverlay;\r\n\t\tRectangle maxCornerRectTL, maxCornerRectTR, maxCornerRectBL, maxCornerRectBR;\r\n\t\tRectangle maxCornerRectCTL, maxCornerRectCTR, maxCornerRectCBL, maxCornerRectCBR;\r\n\t\tRectangle maxCenterRectUpper, maxCenterRectLower;\r\n\r\n\t\tstatic Texture2D displayBase, displayBaseOverlay, barDarkOverlay, barBrightOverlay, maxCornerYellow, maxCenterRed, timeLoadingDark, timeLoadingBright;\r\n\r\n\t\tprivate const int BASE_OVERLAY_DIMENSIONS = 4, VARIED_BAR_HEIGHT_OFFSET = 3, VARIED_BAR_OVERLAY_HEIGHT = 12;\r\n\r\n\t\tprivate Vector2 position;\r\n\r\n\t\tpublic Vector2 Position { get { return position; } set { position = value; } }\r\n\r\n\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\tpublic const int WIDTH = 302, HEIGHT = 32, MAX_CENTER_RECT_WIDTH = 70;\r\n\r\n\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.715871274471283, "alphanum_fraction": 0.715871274471283, "avg_line_length": 23.742856979370117, "blob_id": "4b2ae60c8c99798fd39cd1b9cb9d9cbe15bd82a0", "content_id": "a386ef4c760f5148e53ed8828d3c2939918c7fa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 903, "license_type": "no_license", "max_line_length": 96, "num_lines": 35, "path": "/HollowAether/Lib/GAssets/Items/HeartCanister.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic partial class HeartCanister : CollideableSprite, IInteractable, IItem, IContextualised {\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tthrow new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tthrow new NotImplementedException();\r\n\t\t}\r\n\r\n\t\tpublic void Interact() {\r\n\r\n\t\t}\r\n\r\n\t\tpublic bool OutputReady() {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tpublic String OutputString { get; set; }\r\n\t\tpublic bool Interacted { get; set; } = false;\r\n\t\tpublic bool CanInteract { get; set; } = true;\r\n\t\tpublic String ItemID { get; private set; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7303370833396912, "alphanum_fraction": 0.7355805039405823, "avg_line_length": 29.785715103149414, "blob_id": "97cd45682fc013821166b4e87ea73cffb5d634c0", "content_id": "f74d9fef9f2f464fe5252adeae31c24b5c6d554d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 102, "num_lines": 42, "path": "/HollowAether/Lib/GAssets/Items/Gates/Gate.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic abstract class Gate : CollideableSprite, IInteractable {\r\n\t\tpublic Gate(Vector2 position, Vector2 newZoneTarget) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT) {\r\n\t\t\tTakesToZone = newZoneTarget;\r\n\t\t\tInitialize(\"cs\\\\npcsym\");\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tpublic void Interact() {\r\n\t\t\tif (!Interacted && CanInteract) {\r\n\t\t\t\tGameWindow.GameRunning.invokeTransitionZone = true;\r\n\t\t\t\tGameWindow.GameRunning.transitionZoneEventArg_New = TakesToZone;\r\n\r\n\t\t\t\tInteracted = true; CanInteract = true; // Prevent re interaction\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool Interacted { get; private set; } = false;\r\n\r\n\t\tpublic abstract bool CanInteract { get; protected set; }\r\n\r\n\t\tpublic Vector2 TakesToZone { get; protected set; }\r\n\r\n\t\tpublic const int SPRITE_WIDTH = 32, SPRITE_HEIGHT = 48;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7324166893959045, "alphanum_fraction": 0.7392913699150085, "avg_line_length": 30.60344886779785, "blob_id": "7c004a1e8007a657acc5bd8bb8ce31baa3a9f4d0", "content_id": "88d35a9c84d202132cef93aacffe65e31d86babd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1893, "license_type": "no_license", "max_line_length": 119, "num_lines": 58, "path": "/HollowAether/Lib/Global/GameWindow/GamePaused.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GameWindow {\r\n\tpublic static class GamePaused {\r\n\t\tpublic static void Draw() {\r\n\t\t\tGameRunning.Draw(); // Set as backdrop\r\n\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false);\r\n\r\n\t\t\tvar span = new Rectangle(0, 0, GV.Variables.windowWidth, GV.Variables.windowHeight);\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.Draw(overlayTexture, span, Color.White * 0.75f);\r\n\r\n\t\t\tVector2 size = Font.MeasureString(\"Paused\"), position = new Vector2() {\r\n\t\t\t\tX = GV.Variables.windowWidth - size.X - 25, Y = 25 //GV.Variables.windowHeight\r\n\t\t\t};\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(Font, \"Paused\", position, Color.White);\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tpublic static void Update() {\r\n\t\t\tif (GV.PeripheralIO.ImplementWaitForInputToBeRemoved(ref WaitForInputToBeRemoved))\r\n\t\t\t\treturn; // If Still Waiting For Input Retrieval Then Return B4 Update\r\n\r\n\t\t\tif (GV.PeripheralIO.currentControlState.Pause) {\r\n\t\t\t\tGV.MonoGameImplement.gameState = GameState.GameRunning;\r\n\t\t\t\tGameRunning.WaitForInputToBeRemoved = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static void Reset() {\r\n\r\n\t\t}\r\n\r\n\t\tpublic static bool WaitForInputToBeRemoved = false;\r\n\r\n\t\tprivate static Texture2D overlayTexture { get { return GV.MonoGameImplement.textures[overlayTextureKey]; } }\r\n\t\tprivate static SpriteFont Font { get { return GV.MonoGameImplement.fonts[fontKey]; } }\r\n\r\n\t\tprivate static readonly String overlayTextureKey = @\"backgrounds\\windows\\playerdeadoverlay\", fontKey = @\"homescreen\";\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7187406420707703, "alphanum_fraction": 0.7196401953697205, "avg_line_length": 34.25, "blob_id": "bcbd8abff3b2333c3403b0555d5cd4eb6cd80043", "content_id": "a5cca6bf8911fd111e9167987af880e5f47f67da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3337, "license_type": "no_license", "max_line_length": 125, "num_lines": 92, "path": "/HollowAether/Lib/Global/GlobalVars/EntityGenerators.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\nusing System.IO;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing Microsoft.Xna.Framework.Media;\r\nusing Microsoft.Xna.Framework.Audio;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.InputOutput;\r\nusing HollowAether.Lib.GAssets;\r\nusing HollowAether.Lib.Encryption;\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\n#endregion\r\n\r\nusing System.Reflection;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic static partial class GlobalVars {\r\n\t\tpublic static class EntityGenerators {\r\n\t\t\tstatic EntityGenerators() {\r\n\t\t\t\tforeach (Type type in YieldTypesFromAssemblies(typeof(IInitializableEntity))) {\r\n\t\t\t\t\tMethodInfo info = type.GetMethod(\r\n\t\t\t\t\t\t\"GetAdditionalEntityAttributes\", // Get The Method That Defines Any Additional EntityAttributes\r\n\t\t\t\t\t\tBindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\tvar attributes = (ICollection<KeyValuePair<String, EntityAttribute>>)info.Invoke(null, new object[] { });\r\n\r\n\t\t\t\t\tGameEntity value = new GameEntity(type.Name.ToLower(), attributes.ToArray());\r\n\t\t\t\t\tentityTypes[type.Name.ToLower()] = new Tuple<Type, GameEntity>(type, value);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tprivate static IEnumerable<Type> YieldTypesFromAssemblies(Type desired) {\r\n\t\t\t\tFunc<Type, bool> IsValid = (type) => Misc.DoesExtend(type, desired) && !type.IsInterface;\r\n\r\n\t\t\t\tforeach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {\r\n\t\t\t\t\tforeach (Type type in assembly.GetTypes()) {\r\n\t\t\t\t\t\tif (type != typeof(object) && IsValid(type))\r\n\t\t\t\t\t\t\tyield return type; // Is Valid Type\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static System.Drawing.Rectangle? GetAnimationFromEntityName(string entityName) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tType type = entityTypes[entityName].Item1; // Get Entity Type\r\n\r\n\t\t\t\t\tMethodInfo info = type.GetMethod(\r\n\t\t\t\t\t\t\"GetEntityFrame\", // Get The Method That Defines What Frame To Display To Caller\r\n\t\t\t\t\t\tBindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t\treturn ((Frame)info.Invoke(null, new object[] { })).ToDrawingRect();\r\n\t\t\t\t} catch { return null; }\r\n\t\t\t}\r\n\r\n\t\t\tpublic static GameEntity StringToGameEntity(String entityName) {\r\n\t\t\t\ttry { return entityTypes[entityName.ToLower()].Item2.Clone() as GameEntity; } catch {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Could Not Find Entity '{entityName}'\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic static IMonoGameObject StringToMonoGameObject(String className) {\r\n\t\t\t\tType entityType; // Type corresponding to desired class name\r\n\r\n\t\t\t\ttry { entityType = entityTypes[className.ToLower()].Item1; } catch {\r\n\t\t\t\t\tthrow new Exception($\"Couldn't Find Entity Of Type '{className}'\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tIMonoGameObject IMGO = (IMonoGameObject)Activator.CreateInstance(entityType);\r\n\r\n\t\t\t\treturn IMGO; // Made using default parameterless constructor, Should be fine\r\n\t\t\t}\r\n\r\n\t\t\tpublic static Dictionary<String, Tuple<Type, GameEntity>> entityTypes = new Dictionary<String, Tuple<Type, GameEntity>>();\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6859062910079956, "alphanum_fraction": 0.6944290399551392, "avg_line_length": 37.00540542602539, "blob_id": "41f594ad6cc2e720a401b94871ab64a2b3853720", "content_id": "faa393de7ea1fdacc025736a28daa311441d10be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 14434, "license_type": "no_license", "max_line_length": 118, "num_lines": 370, "path": "/HollowAether/Lib/GAssets/HUD/Hud.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing HollowAether.Lib.GAssets.HUD;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic class HUD {\r\n\t\tpublic HUD(int heartCount = 16) {\r\n\t\t\tInitialiseHearts(heartCount);\r\n\t\t\tInitialisePointDisplay();\r\n\t\t\tInitialiseButtons();\r\n\t\t}\r\n\r\n\t\tprivate void InitialiseHearts(int heartCount) {\r\n\t\t\tVector2 positionVect = standardCornerOffset + new Vector2(0, PointDisplay.HEIGHT + 15);\r\n\r\n\t\t\tforeach (int X in Enumerable.Range(0, heartCount)) {\r\n\t\t\t\tif (X % MAX_X_SPAN == 0 && X != 0) // If maximum amount of hearts on given row has been reached \r\n\t\t\t\t\tpositionVect = new Vector2(standardCornerOffset.X, positionVect.Y + HEART_Y_OFFSET + HeartSprite.DEFAULT_HEIGHT);\r\n\r\n\t\t\t\thearts.Add(new HeartSprite(positionVect)); // Create new heart\r\n\t\t\t\tpositionVect.X += HeartSprite.DEFAULT_WIDTH + HEART_X_OFFSET;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void InitialisePointDisplay() {\r\n\t\t\tVector2 position; // Position for point display to be set to initially\r\n\r\n\t\t\tif (!GamePad.GetState(PlayerIndex.One).IsConnected) position = standardCornerOffset; //+ new Vector2(0, 30);\r\n\t\t\telse position = standardCornerOffset /*+ new Vector2(0, 30)*/ + HEART_OFFSET_WITH_BUTTONS;\r\n\r\n\t\t\tpointDisplay = new PointDisplay(position); // Create new display\r\n\t\t}\r\n\r\n\t\tprivate void InitialiseButtons() {\r\n\t\t\tint iconPush = -3; // Value by which icons should be offset by from there regular arrangement\r\n\r\n\t\t\ttopButtonPosition = standardCornerOffset + new Vector2(GamePadButtonIcon.SPRITE_WIDTH + iconPush, 0);\r\n\t\t\tbottomButtonPosition = topButtonPosition + new Vector2(0, 2 * (GamePadButtonIcon.SPRITE_HEIGHT + iconPush));\r\n\t\t\tleftButtonPosition = standardCornerOffset + new Vector2(0, GamePadButtonIcon.SPRITE_HEIGHT + iconPush);\r\n\t\t\trightButtonPosition = leftButtonPosition + new Vector2(2 * (GamePadButtonIcon.SPRITE_WIDTH + iconPush), 0);\r\n\r\n\t\t\tdash = new GamePadButtonIcon(leftButtonPosition, GamePadButtonIcon.GamePadButton.X, defaultTheme);\r\n\t\t\tjump = new GamePadButtonIcon(bottomButtonPosition, GamePadButtonIcon.GamePadButton.A, defaultTheme);\r\n\t\t\tinteract = new GamePadButtonIcon(topButtonPosition, GamePadButtonIcon.GamePadButton.Y, defaultTheme);\r\n\t\t\tother = new GamePadButtonIcon(rightButtonPosition, GamePadButtonIcon.GamePadButton.B, defaultTheme);\r\n\t\t\t\r\n\t\t\tif (GamePad.GetState(PlayerIndex.One).IsConnected) { // Push initially without transition\r\n\t\t\t\tgamepadButtonsDisplayed = true; // Display automatically\r\n\r\n\t\t\t\tforeach (HeartSprite sprite in hearts)\r\n\t\t\t\t\tsprite.OffsetSpritePosition(HEART_OFFSET_WITH_BUTTONS);\r\n\t\t\t} else {\r\n\t\t\t\tVector2 center = ButtonCenterPosition; // Store locally\r\n\r\n\t\t\t\tforeach (GamePadButtonIcon icon in GamePadIcons) {\r\n\t\t\t\t\ticon.SetPosition(center);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Update(bool updateAnimation) {\r\n\t\t\tforeach (HeartSprite heart in hearts) heart.Update(updateAnimation);\r\n\r\n\t\t\tif (!gamepadButtonsDisplayed && GV.PeripheralIO.gamePadConnected ||\r\n\t\t\t\t gamepadButtonsDisplayed && !GV.PeripheralIO.gamePadConnected)\r\n\t\t\t\tToggleControllerButtons();\r\n\r\n\t\t\tif (gamepadButtonsDisplayed) UpdateControllerIcons(updateAnimation);\r\n\r\n\t\t\tif (GV.PeripheralIO.CheckMultipleKeys(true, null, Keys.R))\r\n\t\t\t\tToggleControllerButtons();\r\n\r\n\t\t\tpointDisplay.Update(updateAnimation); // Update points display\r\n\t\t}\r\n\r\n\t\tpublic void SetHeartCount(int heartCount) {\r\n\t\t\tif (heartCount != HeartsCount) {\r\n\t\t\t\tif (heartCount > HeartsCount) { foreach (int X in Enumerable.Range(0, heartCount - HeartsCount)) AddHeart(); }\r\n\t\t\t\telse { foreach (int X in Enumerable.Range(0, HeartsCount - heartCount)) RemoveHeart(); }\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void SetHealth(int health) {\r\n\t\t\tint currentHealth = Health; // Store to prevent repeated calculation\r\n\r\n\t\t\tif (health != currentHealth) {\r\n\t\t\t\tif (health > currentHealth)\t\t AddHealth(health - currentHealth);\r\n\t\t\t\telse /* health < currentHealth */ TakeDamage(currentHealth - health);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void Draw() {\r\n\t\t\tGV.MonoGameImplement.InitializeSpriteBatch(false, SpriteSortMode.Deferred);\r\n\r\n\t\t\tforeach (HeartSprite heart in hearts) heart.Draw();\r\n\t\t\tif (gamepadButtonsDisplayed) DrawControllerIcons();\r\n\t\t\tpointDisplay.Draw(); // Display user points to screen\r\n\t\t\tDrawPoints(); // Draw monies and burst points to screen\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.End();\r\n\t\t}\r\n\r\n\t\tprivate void DrawPoints() {\r\n\t\t\tSpriteFont font = GV.MonoGameImplement.fonts[\"robotaur\"]; // Get sprite font\r\n\t\t\tString bp = GV.MonoGameImplement.Player.burstPoints.ToString().PadLeft(3, '0');\r\n\t\t\tString money = GV.MonoGameImplement.money.ToString().PadLeft(3, '0');\r\n\t\t\tString text = $\"BP: {bp}, Money: {money}\"; // String to output to screen\r\n\r\n\t\t\tVector2 pointsStringSize = font.MeasureString(text); // Get dimensions of string\r\n\t\t\tVector2 position = new Vector2(hearts[0].Position.X, hearts.Last().Position.Y + pointsStringSize.Y + 15);\r\n\r\n\t\t\tGV.MonoGameImplement.SpriteBatch.DrawString(font, text, position, Color.White);\r\n\t\t}\r\n\r\n\t\tprivate void ToggleControllerButtons() {\r\n\t\t\tif (gamepadButtonsDisplayed) HideControllerButtons();\r\n\t\t\telse\t\t\t\t\t\t DisplayControllerButtons();\r\n\t\t}\r\n\r\n\t\tprivate void DisplayControllerButtons() {\r\n\t\t\tif (gamePadTransitionTakingPlace) return; // Block transition access\r\n\t\t\telse gamePadTransitionTakingPlace = true; // Transition has begun\r\n\r\n\t\t\tAction UponCompletion = () => {\r\n\t\t\t\tgamepadButtonsDisplayed = true;\r\n\r\n\t\t\t\t_PushButtonSpritesToAppropriatePosition();\r\n\r\n\t\t\t\tjump.PushPack.PushCompleted += (s2, a2) => gamePadTransitionTakingPlace = false;\r\n\t\t\t}; // Begins Display & Push Of Controller Buttons \r\n\r\n\t\t\tif (hearts.Count == 0) { /* Hearts don't need to be pushed */ UponCompletion(); } else {\r\n\t\t\t\thearts[0].PushTo(hearts[0].Position + HEART_OFFSET_WITH_BUTTONS, 0.85f);\r\n\r\n\t\t\t\thearts[0].PushPack.SpriteOffset += (sprite, pushVect) => {\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(1, hearts.Count - 1)) {\r\n\t\t\t\t\t\thearts[X].OffsetSpritePosition(pushVect);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpointDisplay.Position += pushVect;\r\n\t\t\t\t}; // Pushes Hearts Forward\r\n\r\n\t\t\t\thearts[0].PushPack.SpriteSet += (sprite, newPos, oldPos) => {\r\n\t\t\t\t\tforeach (int X in Enumerable.Range(1, hearts.Count - 1)) {\r\n\t\t\t\t\t\thearts[X].OffsetSpritePosition(newPos - oldPos);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpointDisplay.Position += newPos - oldPos;\r\n\t\t\t\t}; // Accounts For Any Unexpected Heart Displacement\r\n\r\n\t\t\t\thearts[0].PushPack.PushCompleted += (sprite, args) => UponCompletion();\r\n\t\t\t}\r\n\r\n\t\t\t// pointDisplay.PushTo(pointDisplay.Position + HEART_OFFSET_WITH_BUTTONS, 0.85f);\r\n\t\t}\r\n\r\n\t\tprivate void HideControllerButtons() {\r\n\t\t\tif (gamePadTransitionTakingPlace) return; // Block transition\r\n\t\t\telse gamePadTransitionTakingPlace = true; // Begin transition\r\n\r\n\t\t\t#region PrimaryAction\r\n\t\t\t_PushButtonSpritesToCenter(); // Push button sprites back to center/origin\r\n\t\t\tjump.PushPack.PushCompleted += (sprite, args) => gamepadButtonsDisplayed = false;\r\n\t\t\t#endregion\r\n\r\n\t\t\tif (hearts.Count == 0) { gamePadTransitionTakingPlace = false; } else {\r\n\t\t\t\tjump.PushPack.PushCompleted += (sprite, args) => {\r\n\t\t\t\t\thearts[0].PushTo(hearts[0].Position - HEART_OFFSET_WITH_BUTTONS);\r\n\r\n\t\t\t\t\thearts[0].PushPack.SpriteOffset += (sprite2, pushVect) => {\r\n\t\t\t\t\t\tforeach (int X in Enumerable.Range(1, hearts.Count - 1)) {\r\n\t\t\t\t\t\t\thearts[X].OffsetSpritePosition(pushVect);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tpointDisplay.Position += pushVect;\r\n\t\t\t\t\t}; // Pushes Hearts backward\r\n\r\n\t\t\t\t\thearts[0].PushPack.SpriteSet += (sprite3, newPos, oldPos) => {\r\n\t\t\t\t\t\tforeach (int X in Enumerable.Range(1, hearts.Count - 1)) {\r\n\t\t\t\t\t\t\thearts[X].OffsetSpritePosition(newPos - oldPos);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tpointDisplay.Position += newPos - oldPos;\r\n\t\t\t\t\t}; // Accounts For Any Unexpected Heart Displacement\r\n\r\n\t\t\t\t\thearts[0].PushPack.PushCompleted += (sprite4, args2) => {\r\n\t\t\t\t\t\tgamePadTransitionTakingPlace = false;\r\n\t\t\t\t\t};\r\n\t\t\t\t};\r\n\t\t\t}\r\n\r\n\t\t\tjump.PushPack.PushCompleted += (sprite, args) => {\r\n\t\t\t\t// pointDisplay.PushTo(pointDisplay.Position - HEART_OFFSET_WITH_BUTTONS, 0.85f);\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t#region Push Methods\r\n\t\tprivate void _PushButtonSpritesToAppropriatePosition() {\r\n\t\t\tforeach (GamePadButtonIcon icon in GamePadIcons) {\r\n\t\t\t\ticon.PushTo(icon.initialPosition);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void _PushButtonSpritesToCenter() {\r\n\t\t\tVector2 center = ButtonCenterPosition;\r\n\r\n\t\t\tforeach (GamePadButtonIcon icon in GamePadIcons)\r\n\t\t\t\ticon.PushTo(center); // Initiate Push\r\n\t\t}\r\n\t\t#endregion\r\n\r\n\t\tprivate void UpdateControllerIcons(bool updateAnimation) {\r\n\t\t\tforeach (GamePadButtonIcon icon in GamePadIcons)\r\n\t\t\t\ticon.Update(updateAnimation);\r\n\r\n\t\t\t// Check whether to invalidate here\r\n\t\t\tdash.Active = GV.MonoGameImplement.Player.CanDash();\r\n\t\t\tjump.Active = GV.MonoGameImplement.Player.CanJump();\r\n\t\t\t//interact.Active = GV.MonoGameImplement.player.HasIntersectedTypes(GV.MonoGameImplement.InteractableTypes);\r\n\t\t}\r\n\r\n\t\tprivate void DrawControllerIcons() {\r\n\t\t\tforeach (GamePadButtonIcon icon in GamePadIcons)\r\n\t\t\t\ticon.Draw(); // Draw all game pad icons\r\n\t\t}\r\n\t\t\r\n\t\tpublic void AddHeart() {\r\n\t\t\tint active = GetIndexOfLastActiveHeart(); // Get current active heart\r\n\r\n\t\t\tVector2 newHeartPosition = GetNewHeartPosition(); // new pos\r\n\t\t\tint lastHeartHealth = hearts[active], newHeartHealth;\r\n\t\t\thearts[active].RefillHealth(); // refill\r\n\r\n\t\t\tif (active + 1 == hearts.Count) { // Last heart is active\r\n\t\t\t\tnewHeartHealth = lastHeartHealth; // don't worry\r\n\t\t\t} else { // Hearts exist between present and new ones\r\n\t\t\t\thearts[active + 1].Health = lastHeartHealth;\r\n\t\t\t\tnewHeartHealth = 0; // empty new heart, sorry\r\n\t\t\t}\r\n\r\n\t\t\thearts.Add(new HeartSprite(newHeartPosition, newHeartHealth));\r\n\t\t}\r\n\r\n\t\tpublic void RemoveHeart() {\r\n\t\t\tint active = GetIndexOfLastActiveHeart(), heartsFinal = HeartsCount - 1;\r\n\r\n\t\t\tif (heartsFinal < 0) throw new HollowAetherException($\"Cannot Have Negative HEarts\");\r\n\r\n\t\t\tint currentHeartHealth = hearts[active].Health; // Store before removal in case needed\r\n\t\t\tbool resetHealth = active == heartsFinal && hearts[active].Health != HeartSprite.HEART_SPAN;\r\n\r\n\t\t\thearts.RemoveAt(heartsFinal); // Remove heart at absolute end of hearts list\r\n\r\n\t\t\tif (HeartsCount >= 0 && resetHealth) hearts[HeartsCount - 1].SetHealth(currentHeartHealth);\r\n\t\t}\r\n\r\n\t\tprivate Vector2 GetNewHeartPosition() {\r\n\t\t\tint xIntoCount = HeartSprite.heartCount % MAX_X_SPAN, yIntoCount = HeartSprite.heartCount / MAX_X_SPAN;\r\n\r\n\t\t\tVector2 absPos = new Vector2(\r\n\t\t\t\txIntoCount * (HeartSprite.DEFAULT_WIDTH + HEART_X_OFFSET),\r\n\t\t\t\tyIntoCount * (HeartSprite.DEFAULT_HEIGHT + HEART_Y_OFFSET)\r\n\t\t\t);\r\n\r\n\t\t\treturn absPos + hearts[0].Position;\r\n\t\t}\r\n\r\n\t\tprivate int GetIndexOfLastActiveHeart() {\r\n\t\t\tfor (int X = hearts.Count - 1; X >= 0; X--) {\r\n\t\t\t\tif (hearts[X] != 0) return X;\r\n\t\t\t}\r\n\r\n\t\t\treturn 0; // Should be unreachable, JIC\r\n\t\t}\r\n\r\n\t\tpublic void AddHealth(int amount) {\r\n\t\t\tint incrementedHealth = GetDisplayedHealth() + amount, total = TotalHudHealth; // store to lower waste\r\n\t\t\tif (incrementedHealth > total) throw new HUDHealthAdditionException(total, incrementedHealth); // raise\r\n\r\n\t\t\tint span = HeartSprite.HEART_SPAN; // Store locally to minimise call length\r\n\r\n\t\t\tfor (int X = GetIndexOfLastActiveHeart(); X < hearts.Count; X++) {\r\n\t\t\t\tif (hearts[X] == span) continue; else {\r\n\t\t\t\t\tif (amount + hearts[X] > span) { amount -= span - hearts[X]; hearts[X].RefillHealth(); } else {\r\n\t\t\t\t\t\thearts[X].AddHealth(amount); break; // At this point, amount to add is equivalent to 0\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void TryAddHealth(int amount) {\r\n\t\t\tint displayed = GetDisplayedHealth();\r\n\r\n\t\t\tif (displayed != TotalHudHealth) {\r\n\t\t\t\tif (displayed + amount <= TotalHudHealth)\r\n\t\t\t\t\tAddHealth(amount); // Adds upto max\r\n\t\t\t\telse AddHealth(TotalHudHealth - displayed);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void TryTakeDamage(int amount) {\r\n\t\t\tint displayed = GetDisplayedHealth();\r\n\r\n\t\t\tif (displayed != 0) {\r\n\t\t\t\tif (displayed - amount >= 0)\r\n\t\t\t\t\tTakeDamage(amount); // Takes up to 0\r\n\t\t\t\telse TakeDamage(displayed);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic void TakeDamage(int damage) {\r\n\t\t\tint decrementedHealth = GetDisplayedHealth() - damage; // Store to lower ref memory waste and speed up\r\n\t\t\tif (decrementedHealth < 0) throw new HUDHealthSubtractionException(TotalHudHealth, decrementedHealth);\r\n\r\n\t\t\tfor (int X = GetIndexOfLastActiveHeart(); X >= 0; X--) {\r\n\t\t\t\t//if (hearts[X] != HeartSprite.HEART_SPAN) {\r\n\t\t\t\t\tif (damage > hearts[X]) { damage -= hearts[X]; hearts[X].EmptyHealth(); } else {\r\n\t\t\t\t\t\thearts[X].SubtractHealth(damage); // take away health from current heart\r\n\t\t\t\t\t\tbreak; // Break when damage has been reduced to nothing / 0\r\n\t\t\t\t\t}\r\n\t\t\t\t//}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic int GetDisplayedHealth() {\r\n\t\t\tint index = GetIndexOfLastActiveHeart(); // Get chosen index\r\n\t\t\treturn (HeartSprite.HEART_SPAN * index) + hearts[index].Health;\r\n\t\t}\r\n\r\n\t\tpublic void RefillHealth() {\r\n\t\t\tfor (int X = GetIndexOfLastActiveHeart(); X < hearts.Count; X++) {\r\n\t\t\t\thearts[X].RefillHealth(); // Refill health for all hearts\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic int TotalHudHealth { get { return hearts.Count * HeartSprite.HEART_SPAN; } }\r\n\r\n\t\tpublic int Health { get { return GetDisplayedHealth(); } }\r\n\r\n\t\tprivate Vector2 ButtonCenterPosition { get { return new Vector2(topButtonPosition.X, leftButtonPosition.Y); } }\r\n\r\n\t\tprivate GamePadButtonIcon[] GamePadIcons { get { return new GamePadButtonIcon[] { dash, jump, interact, other }; } }\r\n\r\n\t\tpublic int HeartsCount { get { return hearts.Count; } }\r\n\r\n\t\tpublic bool gamepadButtonsDisplayed = false;\r\n\r\n\t\tprivate PointDisplay pointDisplay;\r\n\t\tList<HeartSprite> hearts = new List<HeartSprite>();\r\n\t\tprivate const int MAX_X_SPAN = 8; // max hearts in row\r\n\t\tprivate Vector2 previousCameraPosition = Vector2.Zero;\r\n\t\tprivate GamePadButtonIcon dash, jump, interact, other;\r\n\t\tprivate const float HEART_X_OFFSET = 2, HEART_Y_OFFSET = 2;\r\n\t\tprivate static readonly Vector2 standardCornerOffset = new Vector2(25, 25);\r\n\t\tpublic GamePadButtonIcon.Theme defaultTheme = GamePadButtonIcon.Theme.Regular;\r\n\t\tprivate static readonly Vector2 HEART_OFFSET_WITH_BUTTONS = new Vector2(125, 0);\r\n\t\tprivate bool gamePadTransitionTakingPlace = false;\r\n\t\tprivate Vector2 topButtonPosition, bottomButtonPosition, leftButtonPosition, rightButtonPosition;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7301849126815796, "alphanum_fraction": 0.7387714385986328, "avg_line_length": 41.05555725097656, "blob_id": "4971e0c9374f7a06eadb4c45b5bca59989f33045", "content_id": "632740bf217857f7d74fadba72f1795be60cf7f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3028, "license_type": "no_license", "max_line_length": 88, "num_lines": 72, "path": "/README.md", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "<p>\n <a href=\"https://github.com/mohkale/HollowAether\">\n <img alt=\"header\" src=\"./.github/header.jpg\"/>\n </a>\n</p>\n\nThis is a repository for what was my final year project from [TRC][trc].\nA ~~tiny~~ 2D game engine (and level editor) written with C#, [MonoGame][monogame]\nand WinForms.\n\n[trc]: https://www.trc.ac.uk/\n[monogame]: https://www.monogame.net/\n\nI'm uploading it here for archival purposes, when I get a chance I might clean this\nrepository up a bit, but consider it archived :grin:.\n\n**NOTE**: I've been having some trouble getting this to compile inside a window VM, when\nI get a chance I'll install a new windows partition so that I can share a release\nbinary. In the meantime, in lieu of a demo video/gif, I'll just upload my final\n[report][report].\n\n[report]: ./report.pdf\n\n## The Game\nThe game itself is a simple platformer, I repurposed a lot of art from\n[Cave Story](https://store.steampowered.com/app/200900/Cave_Story/).\n\n<div>\n <img alt=\"cover\" src=\"./.github/image37.png\" />\n <img alt=\"cover\" src=\"./.github/image40.png\" />\n</div>\n\nThe main character has a sword hovering around them which they can throw forward.\nYou can call the sword back manually (by releasing the throw button) or wait until it\nreaches the apex of it's throw (at which point it'll return automatically).\n\nThere are chests scattered around the level which release coins, the simple aim is to\nget to a door at the end of the level while collecting as many coins as you can and\navoiding any monsters.\n\nThere are 4 monster types in the game:\n- The badeye hovers in a circle and releases projectiles towards the player.\n- The bat seeks out the player and harms him by coming in contact.\n- The jumper jumps up to collide with the player when they try going over him.\n- The crusher drops over the player (this enemy was taken from the Mario franchise).\n\n## Level Editor\n<img alt=\"Cover\" src=\"./.github/image31.png\" align=\"left\" />\n\nThe level editor is a WinForms application that lets you select sprites from a tile\nmap and then drop them into the map (or *zone*). Each dropped sprite has an Entity\ntype describing how other sprites interact with them. You can select an edit the\nproperties of one or more Entities or even modify their entity type. You can also\ncreate animations from tilemaps that you can later attach to sprites.\n\n<table><tbody><tr><th></th></tr></tbody></table>\n\nThe rest of this section just consists of some screenshots of the level editor in\naction (I seem to have taken quite a lot of these).\n\n<p align=\"center\">\n <img alt=\"Edit\" src=\"./.github/image29.png\"/>\n <img alt=\"Animation\" src=\"./.github/image32.png\"/>\n <img alt=\"Animation\" src=\"./.github/image33.png\"/>\n <img alt=\"Animation\" src=\"./.github/image27.png\"/>\n</p>\n\n## Credits\nI downloaded assets from multiple sources whilst developing, here's a list of the\nones I ended up using:\n- [sci-fi-platformer-tileset](https://opengameart.org/content/sci-fi-platformer-tileset)\n- [meditator-statues](https://opengameart.org/content/meditator-statues-32x32)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7510080933570862, "avg_line_length": 51.621620178222656, "blob_id": "329444162d26de4d7ff17eeb2ac2f64b51580228", "content_id": "0a7886997861d97a1d118927c8b4320dc36e8569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1986, "license_type": "no_license", "max_line_length": 164, "num_lines": 37, "path": "/HollowAether/Lib/Exceptions/ChildExceptions/SaveSystemExceptions.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Exceptions.CE {\r\n\tclass SaveSystemException : HollowAetherException {\r\n\t\tpublic SaveSystemException() : base() { }\r\n\t\tpublic SaveSystemException(String msg) : base(msg) { }\r\n\t\tpublic SaveSystemException(String msg, Exception inner) : base(msg, inner) { }\r\n\t\tpublic SaveSystemException(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t}\r\n\r\n\tclass SaveFileInvalidHeaderException : SaveSystemException {\r\n\t\tpublic SaveFileInvalidHeaderException(String fPath) : base($\"Save File '{fPath}' Lacks Correct Header\") { }\r\n\t\tpublic SaveFileInvalidHeaderException(String fPath, Exception inner) : base($\"Save File '{fPath}' Lacks Correct Header\", inner) { }\r\n\t}\r\n\r\n\tclass SaveFileDoesntExistAtChosenSlotException : SaveSystemException {\r\n\t\tpublic SaveFileDoesntExistAtChosenSlotException(int index, String path) : base($\"Save file {index} at path '{path}' doesn't exist\") { }\r\n\t\tpublic SaveFileDoesntExistAtChosenSlotException(int index, String path, Exception inner) : base($\"Save file {index} at path '{path}' doesn't exist\", inner) { }\r\n\t}\r\n\t\r\n\tclass SaveSlotOutOfRangeException : SaveSystemException {\r\n\t\tpublic SaveSlotOutOfRangeException(int chosen, int max) : base($\"The maximum index value for Saves is {max}, {chosen + 1} is invalid\") { }\r\n\t\tpublic SaveSlotOutOfRangeException(int chosen, int max, Exception inner) : base($\"The maximum index value for Saves is {max}, {chosen + 1} is invalid\", inner) { }\r\n\t}\r\n\r\n\tclass SaveFileCorruptedException : SaveSystemException {\r\n\t\tpublic SaveFileCorruptedException(String headerMissing) : base($\"Save file lacks '{headerMissing}' section\") { }\r\n\t\tpublic SaveFileCorruptedException(String headerMissing, Exception inner) : base($\"Save file lacks '{headerMissing}' section\", inner) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7014492750167847, "alphanum_fraction": 0.7030100226402283, "avg_line_length": 29.14583396911621, "blob_id": "8c6ba6ea49e8cb0a6d68838a43904158ac6cdcfc", "content_id": "9f5a67b87a425545a61c85f44ac9976c7096ea04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4487, "license_type": "no_license", "max_line_length": 102, "num_lines": 144, "path": "/HollowAether/Lib/Forms/LevelEditor/Assistive Classes/Forms/AnimationView/EditFrameDialog.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\nusing HollowAether.Lib.GAssets;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class EditFrameDialog : Form {\r\n\t\tpublic EditFrameDialog(AnimationSequence seq, int index) {\r\n\t\t\tInitializeComponent();\r\n\t\t\tsequence = seq; // Store reference\r\n\t\t\tframeIndex = index; // Store index\r\n\r\n\t\t\tsizeBeforeResize = MinimumSize;\r\n\t\t}\r\n\r\n\t\tprivate void EditFrameDialog_Load(object sender, EventArgs e) {\r\n\t\t\t#region TileBoxDef\r\n\t\t\ttileBox = new TileBox() {\r\n\t\t\t\tWidth = tilePanel.Width,\r\n\t\t\t\tHeight = tilePanel.Height\r\n\t\t\t};\r\n\r\n\t\t\ttilePanel.Controls.Add(tileBox);\r\n\t\t\t#endregion\r\n\r\n\t\t\ttextureComboBox.Items.AddRange(GV.LevelEditor.textures.Keys.ToArray());\r\n\t\t\ttextureComboBox.SelectedIndex = 0; // Select First Texture By Default\r\n\r\n\t\t\tresetButton.PerformClick();\r\n\t\t}\r\n\r\n\t\tpublic EditFrameDialog(AnimationSequence seq, int index, string currentTexture) : this(seq, index) {\r\n\t\t\ttextureComboBox.SelectedItem = currentTexture;\r\n\t\t}\r\n\r\n\t\tprivate Frame TextBoxesToFrame() {\r\n\t\t\tint x = CheckGetInt(xTextBox.Text);\r\n\t\t\tint y = CheckGetInt(yTextBox.Text);\r\n\t\t\tint width = CheckGetInt(widthTextBox.Text);\r\n\t\t\tint height = CheckGetInt(heightTextBox.Text);\r\n\t\t\tint bWidth = CheckGetInt(blockWidthTextBox.Text);\r\n\t\t\tint bHeight = CheckGetInt(blockHeightTextBox.Text);\r\n\t\t\tint count = CheckGetInt(countTextBox.Text);\r\n\r\n\t\t\treturn new Frame(x, y, width, height, bWidth, bHeight, count);\r\n\t\t}\r\n\r\n\t\tprivate void EditFrameDialog_Resize(object sender, EventArgs e) {\r\n\t\t\tSize deltaSize = Size - sizeBeforeResize;\r\n\t\t\tsizeBeforeResize = Size; // New size b4\r\n\r\n\t\t\tvariablesGroupBox.Location += deltaSize;\r\n\t\t\ttilePanel.Size += deltaSize;\r\n\t\t\ttileBox.Size\t\t\t += deltaSize;\r\n\t\t}\r\n\r\n\t\tprivate void comboBox1_TextChanged(object sender, EventArgs e) {\r\n\t\t\tString textureKey = textureComboBox.SelectedItem.ToString();\r\n\r\n\t\t\ttileBox.Texture = GV.LevelEditor.textures[textureKey].Item1;\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\tsequence.Frames[frameIndex] = TextBoxesToFrame();\r\n\t\t\tClose(); // Close form once updated values have been saved\r\n\t\t}\r\n\r\n\t\tprivate void resetButton_Click(object sender, EventArgs e) {\r\n\t\t\tFrame f = frame; // Resets all values in displayed form\r\n\r\n\t\t\txTextBox.Text = f.xPosition.ToString();\r\n\t\t\tyTextBox.Text = f.yPosition.ToString();\r\n\t\t\twidthTextBox.Text = f.frameWidth.ToString();\r\n\t\t\theightTextBox.Text = f.frameHeight.ToString();\r\n\t\t\tblockWidthTextBox.Text = f.blockWidth.ToString();\r\n\t\t\tblockHeightTextBox.Text = f.blockHeight.ToString();\r\n\t\t\tcountTextBox.Text = f.RunCount.ToString();\r\n\t\t}\r\n\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) { Close(); }\r\n\r\n\t\tprivate void showTileMapButton_Click(object sender, EventArgs e) {\r\n\t\t\tGV.LevelEditor.tileMap.Show();\r\n\r\n\t\t\tString textureKey = textureComboBox.SelectedItem.ToString();\r\n\r\n\t\t\tGV.LevelEditor.tileMap.ChangeImage(textureKey);\r\n\t\t}\r\n\r\n\t\tprivate int CheckGetInt(string text) {\r\n\t\t\tint? value = GV.Misc.StringToInt(text);\r\n\r\n\t\t\tif (value.HasValue) return value.Value; else {\r\n\t\t\t\treturn 0; // 0 = default value for error inputs\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void xTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void yTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void widthTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void heightTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void blockWidthTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void blockHeightTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\ttileBox.AssignFrame(TextBoxesToFrame());\r\n\t\t}\r\n\r\n\t\tprivate void countTextBox_TextChanged(object sender, EventArgs e) {\r\n\t\t\t// No Need To Handle Anything For This Event Handler\r\n\t\t}\r\n\r\n\t\tprivate Size sizeBeforeResize;\r\n\r\n\t\tprivate Frame frame { get { return sequence[frameIndex]; } }\r\n\r\n\t\tprivate AnimationSequence sequence;\r\n\r\n\t\tprivate TileBox tileBox;\r\n\r\n\t\tprivate int frameIndex = -1;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6663778424263, "alphanum_fraction": 0.6691941022872925, "avg_line_length": 30.279720306396484, "blob_id": "65aa19b35bb83dfb48cc43dcf8f148659706190e", "content_id": "1283139fb656573315679a96cdd953ecad77e839", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4620, "license_type": "no_license", "max_line_length": 152, "num_lines": 143, "path": "/HollowAether/Lib/Forms/ErrorMessage/ErrorMessage.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.Exceptions.CE;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Forms {\r\n\tpublic partial class ErrorMessage : Form {\r\n\t\tpublic ErrorMessage(params Exception[] _exceptions) {\r\n\t\t\tInitializeComponent();\r\n\t\t\texceptions.AddRange(_exceptions);\r\n\t\t}\r\n\r\n\t\tprivate void EMB_Load(object sender, EventArgs e) {\r\n\t\t\tBuildTextBox();\r\n\r\n\t\t\tContextMenu cm = new ContextMenu();\r\n\r\n\t\t\tcm.MenuItems.Add(new MenuItem(\"Copy\", new EventHandler(CopyButton_Click)));\r\n\t\t\tcm.MenuItems.Add(new MenuItem(\"Delete\", new EventHandler(ClearButton_Click)));\r\n\t\t\t\r\n\t\t\ttextBox.ContextMenu = cm;\r\n\t\t}\r\n\r\n\t\tpublic void BuildTextBox() {\r\n\t\t\tStringBuilder builder = new StringBuilder();\r\n\t\t\ttextBox.SelectionAlignment = HorizontalAlignment.Center;\r\n\t\t\tbuilder.AppendLine($\"{exceptions.Count.ToString().PadLeft(3, '0')} Exceptions Found\");\r\n\r\n\t\t\tforeach (Exception exc in exceptions) {\r\n\t\t\t\tbuilder.AppendLine(GetSeperator()); // Add ----- etc.\r\n\r\n\t\t\t\t#region DetailDefinitions\r\n\t\t\t\tString destination = (exc.TargetSite != null) ? exc.TargetSite.ToString() : \"Unknown\";\r\n\t\t\t\tString message = (exc.Message != null) ? exc.Message : \"Unknown\"; // Store a given message\r\n\t\t\t\t//String lineAndClass = (exc.StackTrace != null) ? exc.StackTrace.ToString().Split('\\\\').Last() : \"Unknown:Unknown\";\r\n\t\t\t\tString[] lineAndClassList = (exc.StackTrace != null) ? exc.StackTrace.Split('\\n')[0].Split('\\\\').Last().Split(' ') : null;\r\n\t\t\t\tString lineAndClass = (lineAndClassList != null) ? lineAndClassList[0] + ' ' + lineAndClassList[1].PadLeft(3).Replace('\\r',' ') : \"Unknown:Unknown\";\r\n\t\t\t\tString lineInFile = null, pathToFile = null, argRange = null, commandAssistanceString = null, commandLineCmd = null;\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\t#region ExtractDetailsFromException\r\n\t\t\t\tif (exc is AnimationException) {\r\n\r\n\t\t\t\t} else if (exc is CollisionException) {\r\n\r\n\t\t\t\t} else if (exc is FatalException) {\r\n\r\n\t\t\t\t} else if (exc is HollowAetherException) {\r\n\r\n\t\t\t\t} else if (exc is NullReferenceException) {\r\n\t\t\t\t\t\r\n\t\t\t\t} else { // Is Exception\r\n\r\n\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\r\n\t\t\t\t#region AppendToBuilder\r\n\t\t\t\tbuilder.AppendLine($\"Exception Of Type {exc.GetType()}\");\r\n\t\t\t\tbuilder.AppendLine($\"Thrown In Method: {destination}\");\r\n\r\n\t\t\t\tif (commandLineCmd != null) {\r\n\t\t\t\t\tbuilder.AppendLine($\"In Command Line Command: '{commandLineCmd}'\");\r\n\t\t\t\t\tbuilder.AppendLine($\"Which Can Accept: {argRange} Arguments\");\r\n\t\t\t\t\tbuilder.AppendLine($\"Command Help: {commandAssistanceString}\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbuilder.AppendLine($\"In Class\\\\Line: {lineAndClass}\");\r\n\t\t\t\tbuilder.AppendLine($\"Message: {message}\");\r\n\r\n\t\t\t\tif (pathToFile != null && lineInFile != null) {\r\n\t\t\t\t\tbuilder.AppendLine($\"In File: '{pathToFile}'. At Line: {lineInFile.PadLeft(3, '0')}\");\r\n\t\t\t\t} else if (pathToFile != null) {\r\n\t\t\t\t\tbuilder.AppendLine($\"In File: '{pathToFile}'\");\r\n\t\t\t\t} else if (lineInFile != null) {\r\n\t\t\t\t\tbuilder.AppendLine($\"At Line: {lineInFile.PadLeft(3, '0')}\");\r\n\t\t\t\t}\r\n\t\t\t\t#endregion\r\n\t\t\t}\r\n\r\n\t\t\ttextBox.Text = builder.ToString(); // Set Text To Builder Contents\r\n\t\t}\r\n\r\n\t\tpublic String GetSeperator(int span=50) {\r\n\t\t\treturn $\"\\n{(from X in Enumerable.Range(0, span) select \"—\").Aggregate((a, b) => a + b)}\";\r\n\t\t}\r\n\r\n\t\tpublic void Clear() {\r\n\t\t\ttextBox.Text = String.Empty;\r\n\t\t}\r\n\r\n\t\tpublic void AddException(Exception exc) {\r\n\t\t\texceptions.Add(exc);\r\n\t\t}\r\n\r\n\t\tprivate void EMB_KeyDown(object sender, KeyEventArgs e) {\r\n\t\t\tif (e.KeyCode == System.Windows.Forms.Keys.Escape) {\r\n\t\t\t\tApplication.Exit();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprivate void AbortButton_Click(object sender, EventArgs e) {\r\n\t\t\tApplication.Exit();\r\n\t\t}\r\n\r\n\t\tprivate void CopyButton_Click(object sender, EventArgs e) {\r\n\t\t\tString text;\r\n\r\n\t\t\tif (String.IsNullOrWhiteSpace(textBox.SelectedText))\r\n\t\t\t\ttext = textBox.Text; // If textbox doesn't have any selected characters\r\n\t\t\telse text = textBox.SelectedText; // If text box has selected characters\r\n\r\n\t\t\ttry { Clipboard.SetText(text); } catch { Clipboard.Clear(); }\r\n\t\t}\r\n\r\n\t\tprivate void ClearButton_Click(object sender, EventArgs e) {\r\n\t\t\tClear();\r\n\t\t}\r\n\r\n\t\tprotected override bool ShowWithoutActivation {\r\n\t\t\tget { return true; }\r\n\t\t}\r\n\r\n\t\tprivate List<Exception> exceptions = new List<Exception>();\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7414075136184692, "alphanum_fraction": 0.7422258853912354, "avg_line_length": 25.155555725097656, "blob_id": "20f6952e44537c4cb7bc22f76d6ec24280bf18d1", "content_id": "a5394b5542677fbaa3ead3f07dd124d5bef739cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1224, "license_type": "no_license", "max_line_length": 89, "num_lines": 45, "path": "/HollowAether/Lib/Interfaces/IMonoGameObject.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\nusing HollowAether.Lib.MapZone;\r\nusing HollowAether.Lib.GAssets;\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic interface IUpdateable { } // Functionality in children\r\n\r\n\tpublic interface IAnimationUpdateable : IUpdateable {\r\n\t\tvoid Update(bool updateAnimation);\r\n\t}\r\n\r\n\tpublic interface IGeneralUpdateable : IUpdateable {\r\n\t\tvoid Update();\r\n\t}\r\n\r\n\tpublic interface IDrawable {\r\n\t\tvoid Draw();\r\n\t}\r\n\r\n\t/// <summary> Interface for any objects which follow the MonoGame class Model </summary>\r\n\tpublic interface IMonoGameObject : IDrawable, IAnimationUpdateable {\r\n\t\tvoid Initialize(String textureKey);\r\n\t\tvoid LateUpdate();\r\n\t\t/*void ImplementEntityAttribute(String attributeName, Object value);\r\n\t\tType GetAttributeType(String attrName);*/\r\n\t\tvoid AttatchEntity(GameEntity entity);\r\n\t\t\r\n\t\tVector2 Position { get; set; }\r\n\t\tString SpriteID { get; set; }\r\n\t\tRectangle SpriteRect { get; }\r\n\t\tAnimation Animation { get; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7319587469100952, "alphanum_fraction": 0.7319587469100952, "avg_line_length": 20.384614944458008, "blob_id": "14ced943a97ebbe58a60a0680da940b9e866d8c8", "content_id": "c193cbd2fe857ef31d2649d4684a5aa66b648704", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 293, "license_type": "no_license", "max_line_length": 36, "num_lines": 13, "path": "/HollowAether/Lib/Interfaces/IContextualised.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether.Lib {\r\n\t// Outputs things to context window\r\n\tpublic interface IContextualised {\r\n\t\tbool OutputReady();\r\n\t\tString OutputString { get; }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.754050076007843, "alphanum_fraction": 0.754050076007843, "avg_line_length": 30.33333396911621, "blob_id": "82402e237ebea5930b443959d3a24492cd075680", "content_id": "f5c24abf65a9e017305b2d81bf85b97fd704baf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 681, "license_type": "no_license", "max_line_length": 106, "num_lines": 21, "path": "/HollowAether/Lib/Exceptions/HollowAetherException.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Runtime.Serialization;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.Exceptions {\r\n\t/// <summary>Root exception for all custom HollowAether Exceptions</summary>\r\n\tpublic class HollowAetherException : Exception {\r\n\t\tpublic HollowAetherException() : base() { }\r\n\r\n\t\tpublic HollowAetherException(String msg) : base(msg) { }\r\n\r\n\t\tpublic HollowAetherException(String msg, Exception inner) : base(msg, inner) { }\r\n\r\n\t\tpublic HollowAetherException(SerializationInfo info, StreamingContext context) : base(info, context) { }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.70189368724823, "alphanum_fraction": 0.7098350524902344, "avg_line_length": 29.480770111083984, "blob_id": "11c49644bb276c21750a15b22bc35cb8f9ca8e72", "content_id": "03d85a6be6ef8bfc1ef075f77923b7497443f5ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 105, "num_lines": 52, "path": "/HollowAether/Lib/GAssets/Items/Key.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets.Items {\r\n\tpublic sealed partial class Key : BodySprite, IInteractable, IItem, IContextualised {\r\n\t\tpublic enum keyType { Regular, Dark, White };\r\n\r\n\t\tpublic Key(Vector2 position, keyType _type=keyType.Regular) : base(position, 19, 19) {\r\n\t\t\ttype = _type; // Store type\r\n\t\t\tInitialize(\"cs\\\\npcsym\");\r\n\t\t\tItemID = \"Gray Skull\";\r\n\t\t\tOutputString = $\"{GV.MonoGameImplement.PlayerName} Got Key \\\"{ItemID}\\\" Now what? #sys:waitforinput;\";\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t\tImplementGravity(); // Needs to fall\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tFrame frame = new Frame(4 + (int)type, 14, 32, 32);\r\n\r\n\t\t\tAnimationSequence sequence = new AnimationSequence(0, frame);\r\n\r\n\t\t\tAnimation[GV.MonoGameImplement.defaultAnimationSequenceKey] = sequence;\r\n\t\t}\r\n\r\n\t\tpublic void Interact() { GameWindow.GameRunning.InvokeGotItem(this); }\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(this.SpriteRect));\r\n\t\t}\r\n\r\n\t\tpublic bool Interacted { get; private set; } = false;\r\n\t\tpublic bool CanInteract { get; set; } = true;\r\n\r\n\t\tpublic bool OutputReady() { return false; }\r\n\r\n\t\tpublic String ItemID { get; }\r\n\r\n\t\tpublic String OutputString { get; }\r\n\r\n\t\tprivate keyType type;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5553187131881714, "alphanum_fraction": 0.6041355729103088, "avg_line_length": 33.00746154785156, "blob_id": "c89f8e75c6cc2a9a1d4f00fcfbcddcf0fc4d73b0", "content_id": "452984cae2c218dd40500b9d43702430cb8984c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4693, "license_type": "no_license", "max_line_length": 102, "num_lines": 134, "path": "/HollowAether/Lib/GAssets/HUD/GamePadButtonIcon.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\nusing HollowAether.Lib.Exceptions;\r\n\r\nnamespace HollowAether.Lib.GAssets.HUD {\r\n\tpublic class GamePadButtonIcon : Sprite, IPushable {\r\n\t\tpublic enum Theme { Regular, Dark }\r\n\r\n\t\tpublic enum GamePadButton {\r\n\t\t\tA, // Active=(0, 0), Idle=(1, 0)\r\n\t\t\tX, // Active=(0, 1), Idle=(1, 1)\r\n\t\t\tY, // Active=(0, 2), Idle=(1, 2)\r\n\t\t\tB, // Active=(0, 3), Idle=(1, 3)\r\n\t\t\tLTrigger, // Active=(3, 2), Idle=(2, 2)\r\n\t\t\tRTrigger, // Active=(5, 2), Idle=(4, 2)\r\n\t\t\tLShoulder, // Active=(3, 3), Idle=(2, 3)\r\n\t\t\tRShoulder, // Active=(5, 3), Idle=(4, 3)\r\n\t\t\tUnknownLeft, // Active=(2, 1), Idle=(3, 1)\r\n\t\t\tUnknownRight, // Active=(4, 1), Idle=(5, 1)\r\n\t\t\tHome, // Active=(7, 1), Idle=Null\r\n\t\t\tMedia, // Active=(7, 0), Idle=Null\r\n\t\t\tBlank, // Active=(6, 3), Idle=Null\r\n\t\t\tLThumbstick, // Active=(6, 1), Idle=Null\r\n\t\t\tRThumbstick, // Active=(6, 2), Idle=Null\r\n\t\t\tDPadIdle, // Active=(2, 0), Idle=Null\r\n\t\t\tDPadLeft, // Active=(3, 0), Idle=Null\r\n\t\t\tDPadRight, // Active=(5, 0), Idle=Null\r\n\t\t\tDPadUp, // Active=(4, 0), Idle=Null\r\n\t\t\tDPadDown, // Active=(6, 0), Idle=Null\r\n\t\t}\r\n\r\n\t\tpublic GamePadButtonIcon(\r\n\t\t\t\tVector2 position, GamePadButton _button,\r\n\t\t\t\tTheme theme=Theme.Regular, int width=SPRITE_WIDTH,\r\n\t\t\t\tint height=SPRITE_HEIGHT, bool active=true\r\n\t\t\t) : base(position, width, height, true) {\r\n\t\t\tbutton = _button; // Store button to sprite instance, if change reinitialise. Needed for animation.\r\n\t\t\t_active = active; // Store active to assign initial animation used by button sprite.\r\n\t\t\tinitialPosition = position; // Store initial position to allow pushing to it at later points\r\n\t\t\tInitialize((theme == Theme.Regular) ? \"sprites\\\\gamepadicons\" : \"sprites\\\\gamepadiconsdark\");\r\n\t\t}\r\n\t\t\r\n\t\tpublic void PushTo(Vector2 position, float over=0.8f) {\r\n\t\t\tif (PushArgs.PushValid(position, Position))\r\n\t\t\t\tPush(new PushArgs(position, Position, over));\r\n\t\t}\r\n\r\n\t\tpublic void Push(PushArgs args) { if (!BeingPushed) PushPack = args; }\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tbase.Update(updateAnimation); // Updates elapsed time as well\r\n\r\n\t\t\tif (BeingPushed && !PushPack.Update(this, elapsedTime)) {\r\n\t\t\t\tPushPack = null; // Delete push pack\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tint X1, Y, X2; // Frame X & Y positions\r\n\r\n\t\t\tswitch ((int)button) {\r\n\t\t\t\tcase 00: X1 = 00; Y = 00; break;\r\n\t\t\t\tcase 01: X1 = 00; Y = 01; break;\r\n\t\t\t\tcase 02: X1 = 00; Y = 02; break;\r\n\t\t\t\tcase 03: X1 = 00; Y = 03; break;\r\n\t\t\t\tcase 04: X1 = 02; Y = 02; break;\r\n\t\t\t\tcase 05: X1 = 04; Y = 02; break;\r\n\t\t\t\tcase 06: X1 = 02; Y = 03; break;\r\n\t\t\t\tcase 07: X1 = 04; Y = 03; break;\r\n\t\t\t\tcase 08: X1 = 00; Y = 00; break;\r\n\t\t\t\tcase 09: X1 = 00; Y = 00; break;\r\n\t\t\t\tcase 10: X1 = 07; Y = 01; break;\r\n\t\t\t\tcase 11: X1 = 07; Y = 00; break;\r\n\t\t\t\tcase 12: X1 = 06; Y = 03; break;\r\n\t\t\t\tcase 13: X1 = 06; Y = 01; break;\r\n\t\t\t\tcase 14: X1 = 06; Y = 02; break;\r\n\t\t\t\tcase 15: X1 = 02; Y = 00; break;\r\n\t\t\t\tcase 16: X1 = 03; Y = 00; break;\r\n\t\t\t\tcase 17: X1 = 05; Y = 00; break;\r\n\t\t\t\tcase 18: X1 = 04; Y = 00; break;\r\n\t\t\t\tcase 19: X1 = 06; Y = 00; break;\r\n\t\t\t\tdefault: throw new HollowAetherException($\"Button '{(int)button}' out of range\");\r\n\t\t\t}\r\n\r\n\t\t\tX2 = ((int)button < 10) ? X1 + 1 : X1;\r\n\r\n\t\t\tAnimation[\"active\"] = new AnimationSequence(0, new Frame(X1, Y, 32, 32));\r\n\t\t\tAnimation[\"idle\"] = new AnimationSequence(0, new Frame(X2, Y, 32, 32));\r\n\r\n\t\t\tUpdateAnimationSequence();\r\n\t\t}\r\n\r\n\t\tprivate void UpdateAnimationSequence() {\r\n\t\t\tAnimation.SetAnimationSequence((Active) ? \"active\" : \"idle\");\r\n\t\t}\r\n\r\n\t\tpublic void ChangeButton(GamePadButton _button) {\r\n\t\t\tbutton = _button; // Re-store button\r\n\t\t\tBuildSequenceLibrary(); // Rebuild\r\n\t\t}\r\n\r\n\t\tpublic void Toggle() {\r\n\t\t\t_active = !_active; // Set to opposite of what it is\r\n\t\t\tUpdateAnimationSequence(); // Set to appropriate\r\n\t\t}\r\n\r\n\t\tprivate void SetActive(bool newVal) {\r\n\t\t\tif (_active != newVal) Toggle();\r\n\t\t}\r\n\r\n\t\tpublic GamePadButton Button { get { return button; } set { ChangeButton(value); } }\r\n\r\n\t\tpublic bool Active { get { return _active; } set { SetActive(value); } }\r\n\r\n\t\tpublic PushArgs PushPack { get; private set; } = null;\r\n\r\n\t\tpublic bool BeingPushed { get { return PushPack != null; } }\r\n\r\n\t\tpublic Vector2 initialPosition;\r\n\r\n\t\tprivate GamePadButton button;\r\n\r\n\t\tprivate bool _active;\r\n\r\n\t\tpublic const int SPRITE_WIDTH=40, SPRITE_HEIGHT=40;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7053686380386353, "alphanum_fraction": 0.7123041152954102, "avg_line_length": 37.724491119384766, "blob_id": "a566817b81fa7c7db4559e8fcdc5849e50311d90", "content_id": "c45e8a90d3e35dcc3a9fa6aa9165a61ca20a26f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3895, "license_type": "no_license", "max_line_length": 188, "num_lines": 98, "path": "/HollowAether/Lib/GAssets/Living/Enemies/Crusher.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\tpublic partial class Crusher : Enemy {\r\n\t\tpublic Crusher() : this(Vector2.Zero, 1) { }\r\n\r\n\t\tpublic Crusher(Vector2 position, int level) : base(position, SPRITE_WIDTH, SPRITE_HEIGHT, level, true) {\r\n\t\t\tInitialize(@\"enemies\\crusher\");\r\n\t\t\tinitialPosition = position;\r\n\t\t}\r\n\r\n\t\tprotected override void BuildBoundary() {\r\n\t\t\tboundary = new SequentialBoundaryContainer(SpriteRect, new IBRectangle(SpriteRect));\r\n\t\t}\r\n\r\n\t\tprotected override void BuildSequenceLibrary() {\r\n\t\t\tAnimation[\"Idle\"] = GV.MonoGameImplement.importedAnimations[@\"crusher\\idle\"]; // AnimationSequence.FromRange(FRAME_WIDTH, FRAME_HEIGHT, 0, 0, 3, FRAME_WIDTH, FRAME_HEIGHT, 25, true, 0);\r\n\t\t}\r\n\r\n\t\tprotected override void DoEnemyStuff() {\r\n\t\t\tif (!falling) {\r\n\t\t\t\tRectangle playerRect = GV.MonoGameImplement.Player.Boundary.Container; // Store player rectangle\r\n\r\n\t\t\t\tbool validLeft = playerRect.Left > SpriteRect.Left || playerRect.Right > SpriteRect.Left;\r\n\t\t\t\tbool validRight = playerRect.Left < SpriteRect.Right || playerRect.Right < SpriteRect.Right;\r\n\r\n\t\t\t\tif (playerRect.Bottom > SpriteRect.Bottom && validLeft && validRight)\r\n\t\t\t\t\tfalling = true; // Initiate falling motion until reaching block \r\n\t\t\t} else {\r\n\t\t\t\tif (returningToPosition) {\r\n\t\t\t\t\tfloat displacement = - verticalReturnVelocity * elapsedTime;\r\n\r\n\t\t\t\t\tif (GV.MonoGameImplement.Player.Intersects(this)) {\r\n\t\t\t\t\t\tString[] labels = GV.MonoGameImplement.Player.TrueBoundary.GetIntersectingBoundaryLabels(boundary);\r\n\t\t\t\t\t\tif (labels.Contains(\"Bottom\")) GV.MonoGameImplement.Player.OffsetSpritePosition(Y: displacement);\r\n\t\t\t\t\t\t// If player is standing atop crusher, push player up by same amount. Cheaty fix to annoying bug\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tOffsetSpritePosition(Y: displacement); // Push by displacement\r\n\r\n\t\t\t\t\tif (Position.Y <= initialPosition.Y) {\r\n\t\t\t\t\t\t// Has returned to initial expected position\r\n\t\t\t\t\t\tSetPosition(initialPosition); // To initial\r\n\t\t\t\t\t\treturningToPosition = false; // Reset vars\r\n\t\t\t\t\t\tfalling = false; // ------------ Reset vars\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (falling) ImplementGravity();\r\n\t\t\t}\r\n\r\n\t\t\tif (falling && !returningToPosition && GV.MonoGameImplement.Player.Intersects(this)) {\r\n\t\t\t\tString[] labels = GV.MonoGameImplement.Player.TrueBoundary.GetIntersectingBoundaryLabels(boundary);\r\n\r\n\t\t\t\tfloat bottomHeightDifferential = SpriteRect.Bottom - GV.MonoGameImplement.Player.Position.Y;\r\n\r\n\t\t\t\tif (labels.Contains(\"Top\") && !GV.MonoGameImplement.Player.Falling(0, bottomHeightDifferential)) {\r\n\t\t\t\t\tGV.MonoGameImplement.Player.OffsetSpritePosition(Y: bottomHeightDifferential); // Push to block\r\n\t\t\t\t\tGV.MonoGameImplement.Player.Attack(GV.MonoGameImplement.GameHUD.Health); // Kill player\r\n\t\t\t\t}\r\n\t\t\t\t// When crusher is directly atop players head, he's been crushed\\(valid collision has happened) & should be killed\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tprotected override uint GetHealth() { return 250; }\r\n\r\n\t\tprotected override void StopFalling() {\r\n\t\t\tbase.StopFalling(); // Base stop methods\r\n\r\n\t\t\treturningToPosition = true; // Begin return\r\n\t\t}\r\n\r\n\t\tprivate bool returningToPosition = false;\r\n\r\n\t\tprivate bool falling;\r\n\r\n\t\tprivate Vector2 initialPosition;\r\n\r\n\t\tprivate float verticalReturnVelocity = 50;\r\n\r\n\t\tprotected override bool CanGenerateHealth { get; set; }\r\n\r\n\t\tprotected override bool CausesContactDamage { get; set; } = false;\r\n\r\n\t\tpublic override float GravitationalAcceleration { get; protected set; } = 2 * GV.MonoGameImplement.gravity;\r\n\r\n\t\tpublic const int FRAME_WIDTH = 24, FRAME_HEIGHT = 32;\r\n\r\n\t\tpublic const int SPRITE_WIDTH = (int)(1.75 * FRAME_WIDTH), SPRITE_HEIGHT = (int)(1.75 * FRAME_HEIGHT);\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5751644372940063, "alphanum_fraction": 0.5812610387802124, "avg_line_length": 41.5874137878418, "blob_id": "10572eabb720b5b325e71d9b3ac887fd9390bb38", "content_id": "79682a504d54983227b3f434807839c1a6a5c662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6233, "license_type": "no_license", "max_line_length": 114, "num_lines": 143, "path": "/HollowAether/PyScripts/system_parser.py", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "# >> SystemParser Class Definition Version\\\\Rendition 2.00 || (C) M.K. 2016 << #\r\n\r\nimport sys # Import system so reference to OS library can be made. IronPython doesn't store python libraries.\r\nsys.path.append('\\\\'.join([sys.path[1], '..', 'PyScripts', 'os'])) # Add path to os library in current filesystem.\r\nimport os # Imports os module and references to all sub contained objects and methods within the os module.\r\n\r\nclass SystemParser(object):\r\n \"\"\"Class To Recursively Parse And Find All Files In a Given Directory\"\"\"\r\n class SystemParserExceptions(object):\r\n \"\"\"Exceptions utilized by SystemParser\"\"\"\r\n class UnidentifiableKeyException(TypeError):\r\n \"\"\"Thrown When The Search Function Is Utilized With an Unknown Arg\"\"\"\r\n pass\r\n\r\n class PathWrapper(object):\r\n \"\"\"Holder Class To Wrap Around SystemParser Class\"\"\"\r\n def generate_contents(self, path, key):\r\n \"\"\"Generates Contents (Dirs & Files) Of A Given System\"\"\"\r\n for entry in os.listdir(path):\r\n if (key(os.path.join(path, entry))):\r\n yield entry\r\n\r\n def generate_dirs(self, path):\r\n \"\"\"Generates All Directories In a Given System\"\"\"\r\n for X in self.generate_contents(path, self.dir_parser):\r\n yield X\r\n \r\n def generate_files(self, path):\r\n \"\"\"Generates All Files In a Given System\"\"\"\r\n for X in self.generate_contents(path, self.file_parser):\r\n yield X\r\n \r\n get_dirs = lambda self, path: [X for X in self.generate_contents(path, self.dir_parser)]\r\n get_files = lambda self, path: [X for X in self.generate_contents(path, self.file_parser)]\r\n dir_parser = staticmethod(os.path.isdir)\r\n file_parser = staticmethod(os.path.isfile)\r\n \r\n def __init__(self, work_path=None):\r\n \"\"\"Default constructor can build system around a given path\"\"\"\r\n if (work_path != None):\r\n self.initialise(work_path)\r\n\r\n def __str__(self):\r\n \"\"\"Converts instance of current class to a string object\"\"\"\r\n return \"SystemTraverser Object Of Path : {0} :\".format(self.root_path)\r\n\r\n def __call__(self, index=None):\r\n \"\"\"Allows Player To Call On SystemParser instance\"\"\"\r\n if (index != None):\r\n return self.system_container[index]\r\n else: return self.system_container\r\n\r\n def __len__(self):\r\n \"\"\"Calculates All Files And Directories In System\"\"\"\r\n return len(self(0)) + len(self(1))\r\n\r\n def __enter__(self):\r\n \"\"\"With Open Handler\"\"\"\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n \"\"\"With Open Handler\"\"\"\r\n return True\r\n\r\n def initialise(self, work_path):\r\n \"\"\"Initializes Current SystemParser instance around passed path\"\"\"\r\n gfe = lambda X: X.split('.')[-1].upper() # Get File Extension\r\n self.system_container = ([work_path], list()) # (Directories, Files)\r\n \r\n if not(os.path.exists(work_path)):\r\n raise FileNotFoundError(work_path)\r\n\r\n self.root_path = work_path; self._system_parse()\r\n self.system_container[0].pop(0) # Remove Root Directory\r\n self.file_types = list(set([gfe(X) for X in self(1)]))\r\n\r\n def _system_parse(self, counter=0):\r\n \"\"\"Nitty Gritty Of The Actual SystemParser Using Brute Force\"\"\"\r\n while True:\r\n for path in self.system_container[0]:\r\n for contents in [self.merge(path, X) for X in self.ls(path)]:\r\n appension_index = 0 if os.path.isdir(contents) else 1\r\n if not(contents in self.system_container[appension_index]):\r\n self.system_container[appension_index].append(contents)\r\n \r\n if not(len(self.system_container[0]) == counter):\r\n counter = len(self.system_container[0])\r\n else: break\r\n\r\n def get_files_of_type(self, *args):\r\n \"\"\"Returns Files With a Given Desired Extension\"\"\"\r\n if not(isinstance(args, str)):\r\n args = [X.upper() for X in args]\r\n else: args = [args.upper()]\r\n \r\n gfe = lambda X: X.split('.')[-1].upper() # Get File Extension\r\n return [X for X in self(1) if gfe(X) in args]\r\n\r\n def get_system(self):\r\n \"\"\"Returns All Files And Directories\"\"\"\r\n container = self(0)\r\n container.extend(self(1))\r\n return sorted(container)\r\n\r\n def search(self, key):\r\n \"\"\"Searches Given System Using An Argument\"\"\"\r\n system = self.get_system()\r\n \r\n if (isinstance(key, str)):\r\n return [X for X in system if key in X.lower()]\r\n elif (callable(key)):\r\n return [X for X in system if key(X)]\r\n else:\r\n raise SystemParser.SystemParserExceptions.UnidentifiableKeyException(\r\n \"Expected Function Or String Like Object, Not {0}\".format(type(key)))\r\n \r\n @staticmethod\r\n def generate_system_traverser(path, index=(0, 1)):\r\n \"\"\"Generates Entire System\"\"\"\r\n with System(path) as sys:\r\n if isinstance(index, tuple):\r\n array = sys(index[0])\r\n array.extend(sys(index[1]))\r\n elif isinstance(index, int):\r\n array = sys(index)\r\n else:\r\n raise SystemParser.SystemParserExceptions.UnidentifiableKeyException(\r\n \"Expected Tuple Or Integer Object, Not {0}\".format(type(key)))\r\n\r\n for path in array: yield path\r\n \r\n ls = staticmethod(os.listdir)\r\n merge = staticmethod(os.path.join)\r\n path_to_title = staticmethod(lambda X: X.split('\\\\')[-1])\r\n truncate_path = lambda self, X: X[len(self.root_path)+1:]\r\n wrapper = PathWrapper()\r\n\r\n get_truncated_files = lambda self: [self.truncate_path(X) for X in self(1)]\r\n get_truncated_dirs = lambda self: [self.truncate_path(X) for X in self(0)]\r\n get_file_titles = lambda self: [self.path_to_title(X) for X in self(1)]\r\n get_file_types = lambda self: self.file_types\r\n get_files = lambda self: self(1)\r\n get_dirs = lambda self: self(0)\r\n" }, { "alpha_fraction": 0.7427250742912292, "alphanum_fraction": 0.7442656755447388, "avg_line_length": 51.109092712402344, "blob_id": "9c8334dea673c96673e59d617d002ad9229dbd5d", "content_id": "9649332b6a46e3aca66d214ad2bf9158d2ff8eb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5844, "license_type": "no_license", "max_line_length": 118, "num_lines": 110, "path": "/HollowAether/Lib/StartUp/StartUpMethods.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region MicrosoftImports\r\nusing Microsoft.Scripting.Hosting;\r\n#endregion\r\n\r\n#region IPythonImports\r\nusing IronPython.Hosting;\r\nusing IronPython.Runtime;\r\n#endregion\r\n\r\nnamespace HollowAether {\r\n\t/// <summary>Methods to only be run on startup, because of *drastic* effects on run speed</summary>\r\n\tpublic static class StartUpMethods {\r\n\t\t/// <summary>Runs a given python script and returns whatever the script prints</summary>\r\n\t\t/// <param name=\"script\">String containing script to execute by py2.7 engine</param>\r\n\t\t/// <returns>Out And Error streams written to by the py2.7 engine</returns>\r\n\t\tpublic static Dictionary<String, String> ReadPyScriptExecution(String script) {\r\n\t\t\tScriptEngine pyEngine = Python.CreateEngine(); // Create Python RunTime Engine\r\n\t\t\tScriptScope pyScope = pyEngine.CreateScope(); // Create scope to access vars\r\n\t\t\tSystem.IO.MemoryStream outStream, errStream; // Add management streams to memory\r\n\t\t\toutStream = errStream = new System.IO.MemoryStream(); // Create instance of stream\r\n\t\t\tpyEngine.Runtime.IO.SetOutput(outStream, Encoding.Default); // set encoding\r\n\t\t\tpyEngine.Runtime.IO.SetErrorOutput(errStream, Encoding.Default); // set encoding\r\n\r\n\t\t\tpyEngine.Execute(script, pyScope); // execute given script in desired scope\r\n\r\n\t\t\treturn new Dictionary<string, string>() {\r\n\t\t\t\t{ \"out\", Encoding.Default.GetString(outStream.ToArray()) },\r\n\t\t\t\t{ \"error\", Encoding.Default.GetString(errStream.ToArray()) }\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t/// <summary>Uses InputParser python script to interperate command line arguments</summary>\r\n\t\t/// <param name=\"commandLineString\">String as it would appear in the user command line</param>\r\n\t\t/// <returns>Dictionary (Flag->Args). Default args with no flag is /0 or break char</returns>\r\n\t\tpublic static Dictionary<String, String[]> InputParserScriptInterpreter(String commandLineString) {\r\n\t\t\tScriptEngine pyEngine = Python.CreateEngine(); // Create Python RunTime Engine\r\n\t\t\tScriptSource source = pyEngine.CreateScriptSourceFromFile(@\"PyScripts\\input_parser.py\");\r\n\t\t\tScriptScope scope = pyEngine.CreateScope(); // Create scope for python runtime\r\n\t\t\tsource.Execute(scope); // Execute script to build python script objects\r\n\r\n\t\t\tdynamic InputParser = scope.GetVariable(\"InputParser\"); // grab class reference\r\n\t\t\tdynamic InputParserInstance = InputParser(); // Create new instance from reference\r\n\r\n\t\t\tPythonTuple parsedResults = InputParserInstance.parse_input(commandLineString);\r\n\r\n\t\t\tDictionary<String, String[]> parsed = new Dictionary<String, String[]>(); // Flag->Args\r\n\r\n\t\t\tforeach (PythonTuple sub in parsedResults) { // For Found Flags\r\n\t\t\t\tparsed[(sub[0] == null) ? \"\\0\" : sub[0].ToString()] =\r\n\t\t\t\t\t(from X in sub[1] as List select X.ToString()).ToArray();\r\n\t\t\t}\r\n\r\n\t\t\treturn parsed; // Returns found flags and arguments to caller\r\n\t\t}\r\n\r\n\t\t/// <summary>Uses SystemParser python script to recursively parse directories</summary>\r\n\t\t/// <param name=\"rootPath\">Path to retrieve all sub-directories from</param>\r\n\t\t/// <returns>All file found in a given directory including subdirectories</returns>\r\n\t\tpublic static String[] SystemParserScriptInterpreter(String rootPath) {\r\n\t\t\tScriptEngine pyEngine = Python.CreateEngine(); // Create Python RunTime Engine\r\n\t\t\tScriptSource source = pyEngine.CreateScriptSourceFromFile(@\"PyScripts\\system_parser.py\");\r\n\t\t\tScriptScope scope = pyEngine.CreateScope(); // Create scope for python runtime\r\n\t\t\tsource.Execute(scope); // Execute script to build python script objects\r\n\r\n\t\t\tdynamic SystemParser = scope.GetVariable(\"SystemParser\"); // Grab Class Reference\r\n\t\t\tdynamic ScriptParserInstance = SystemParser(rootPath); // create new instance from ref\r\n\r\n\t\t\tList parsedSystemFiles = ScriptParserInstance.get_files();\r\n\t\t\treturn (from X in parsedSystemFiles select X.ToString()).ToArray();\r\n\t\t}\r\n\r\n\t\t/// <summary>Uses SystemParser python script to recursively parse directories for files of a specific type</summary>\r\n\t\t/// <param name=\"rootPath\">Path to retrieve all sub-files of a given file type from</param>\r\n\t\t/// <param name=\"types\">Desired file types to parse directories for</param>\r\n\t\t/// <returns>All files found in a given directory including subdirectories of desired types</returns>\r\n\t\tpublic static String[] SystemParserTypeSpecificScriptInterpreter(String rootPath, params String[] types) {\r\n\t\t\tScriptEngine pyEngine = Python.CreateEngine(); // Create Python RunTime Engine\r\n\t\t\tScriptSource source = pyEngine.CreateScriptSourceFromFile(@\"PyScripts\\system_parser.py\");\r\n\t\t\tScriptScope scope = pyEngine.CreateScope(); // Create scope for python runtime\r\n\t\t\tsource.Execute(scope); // Execute script to build python script objects\r\n\r\n\t\t\tdynamic SystemParser = scope.GetVariable(\"SystemParser\"); // Grab Class Reference\r\n\t\t\tdynamic ScriptParserInstance = SystemParser(rootPath); // Create new instance from ref\r\n\r\n\t\t\tList parsedSystemFiles = ScriptParserInstance.get_files_of_type(types);\r\n\t\t\treturn (from X in parsedSystemFiles select X.ToString()).ToArray();\r\n\t\t}\r\n\r\n\t\tpublic static String[] SystemParserTruncatedScriptInterpreter(String rootPath) {\r\n\t\t\tScriptEngine pyEngine = Python.CreateEngine(); // Create Python RunTime Engine\r\n\t\t\tScriptSource source = pyEngine.CreateScriptSourceFromFile(@\"PyScripts\\system_parser.py\");\r\n\t\t\tScriptScope scope = pyEngine.CreateScope(); // Create scope for python runtime\r\n\t\t\tsource.Execute(scope); // Execute script to build python script objects\r\n\r\n\t\t\tdynamic SystemParser = scope.GetVariable(\"SystemParser\");\r\n\t\t\tdynamic ScriptParserInstance = SystemParser(rootPath);\r\n\r\n\t\t\tList parsedSystemFiles = ScriptParserInstance.get_truncated_files();\r\n\t\t\treturn (from X in parsedSystemFiles select X.ToString()).ToArray();\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6567460298538208, "alphanum_fraction": 0.6645299196243286, "avg_line_length": 42.57143020629883, "blob_id": "3d0059affee254a036c67c5cd458e8c60c16da5c", "content_id": "81e5f3fba292dea3b3101e1e30c7a7b7edac265b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6554, "license_type": "no_license", "max_line_length": 140, "num_lines": 147, "path": "/HollowAether/Lib/GAssets/Boundary/Shapes/Line.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib {\r\n\tpublic struct Line {\r\n\t\tpublic enum LineType { Normal, XEquals } // Type of line this line can be. Normal is Y equals\r\n\r\n\t\t/// <summary>Constructs angled line between two positions</summary>\r\n\t\t/// <param name=\"P1X\">X position of point 1</param> <param name=\"P1Y\">Y position of point 1</param>\r\n\t\t/// <param name=\"P2X\">X position of point 2</param> <param name=\"P2Y\">Y position of point 2</param>\r\n\t\tpublic Line(float P1X, float P1Y, float P2X, float P2Y) : this(new Vector2(P1X, P1Y), new Vector2(P2X, P2Y)) { }\r\n\r\n\t\t/// <summary>Constructs angled line between two positions</summary>\r\n\t\t/// <param name=\"P1\">Point 1</param> <param name=\"P2\">Point 2</param>\r\n\t\tpublic Line(Vector2 P1, Vector2 P2) {\r\n\t\t\tif (P1.X == P2.X && P1.Y == P2.Y) {\r\n\t\t\t\t//Console.WriteLine(\"Warning: Line of length 0 created\");\r\n\t\t\t}\r\n\r\n\t\t\tpointA = P1; pointB = P2; // Store Initial and Final Points\r\n\t\t\tgradient = CalculateGradient(P1, P2);\r\n\t\t\tyIntercept = CalculateYIntercept(P1, P2);\r\n\t\t}\r\n\r\n\t\t/// <summary>Calculates gradient between two lines</summary>\r\n\t\t/// <param name=\"pointA\">First point</param> <param name=\"pointB\">Second Point</param>\r\n\t\t/// <returns>Gradient of line between 2 points. Is infinity when equation is X equals</returns>\r\n\t\tpublic static float CalculateGradient(Vector2 pointA, Vector2 pointB) {\r\n\t\t\treturn (pointA.Y - pointB.Y) / (pointA.X - pointB.X);\r\n\t\t}\r\n\r\n\t\t/// <summary>Calculate Y Point where line crosses axis</summary>\r\n\t\t/// <param name=\"pointA\">First Point</param> <param name=\"pointB\">Second Point</param>\r\n\t\t/// <returns>Point where line crosses y axis</returns>\r\n\t\tpublic static float CalculateYIntercept(Vector2 pointA, Vector2 pointB) {\r\n\t\t\treturn pointA.Y - (CalculateGradient(pointA, pointB) * pointA.X); // C = Y - Mx\r\n\t\t}\r\n\r\n\t\tpublic override string ToString() {\r\n\t\t\tif (type == LineType.Normal)\r\n\t\t\t\treturn $\"Y = {gradient}x + {yIntercept} : {pointA} {pointB}\";\r\n\t\t\telse\r\n\t\t\t\treturn $\"X = {pointA.X} : {pointA} {pointB}\";\r\n\t\t}\r\n\r\n\t\t/// <summary>Check if line has collided with a given vector</summary>\r\n\t\t/// <param name=\"vect\">Vector to check intersection/collision with</param>\r\n\t\t/// <param name=\"useBoundaries\">Check wether intersection is within two argument points</param>\r\n\t\t/// <returns>Boolean indicating succesful collisions</returns>\r\n\t\tpublic bool Intersects(Vector2 vect, bool useBoundaries = true) {\r\n\t\t\tif (useBoundaries && vect.X > maxPointX && vect.X < minPointX && vect.Y > maxPointY && vect.Y < minPointY) {\r\n\t\t\t\treturn false; // return Vector outside bounds of current points of line;\r\n\t\t\t} else if (this.type == LineType.Normal) {\r\n\t\t\t\treturn vect.Y == (gradient * vect.X) + yIntercept; // return comparitive check\r\n\t\t\t} else { // if (this.type == LineType.XEquals)\r\n\t\t\t\treturn vect.X == this.pointA.X; // if x points match then collision has occured\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks wether two lines intersect</summary>\r\n\t\t/// <param name=\"A\">First line</param> <param name=\"B\">Second line</param>\r\n\t\t/// <returns>Boolean indicating collision</returns>\r\n\t\tpublic static bool Intersects(Line A, Line B) {\r\n\t\t\tif (A.type == LineType.Normal && B.type == LineType.Normal) {\r\n\t\t\t\treturn (GetIntersectionPoint(A, B).HasValue);\r\n\t\t\t} else if (A.type == B.type) { // both LineType.XEquals\r\n\t\t\t\treturn A.pointA.X == B.pointA.X; // X values match\r\n\t\t\t} else { // One is LineType.XEquals & one is LineType.Normal\r\n\t\t\t\tif (A.type == LineType.Normal) { // B.type = LineType.XEquals\r\n\t\t\t\t\treturn true; // Will always intersect at a given x value\r\n\t\t\t\t} else { // B.type = LineType.Normal & A.type = LineType.XEquals\r\n\t\t\t\t\treturn true; // Will always intersect at a given x value\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Checks whether this line intersects a given line </summary>\r\n\t\t/// <param name=\"line\">Line to check intersection with</param>\r\n\t\t/// <returns>Boolean indicating collision</returns>\r\n\t\tpublic bool Intersects(Line line) { return Intersects(this, line); }\r\n\r\n\t\tpublic static Vector2? GetIntersectionPoint(Line A, Line B) {\r\n\t\t\tif (A.gradient == B.gradient) return null; // same gradient hence never or infinite collide\r\n\r\n\t\t\tif (A.type == LineType.Normal && B.type == LineType.Normal) {\r\n\t\t\t\tfloat X = (B.yIntercept - A.yIntercept) / (A.gradient - B.gradient);\r\n\t\t\t\treturn new Vector2(X, A.GetYPoint(X)); // return intersection point\r\n\t\t\t} else if (A.type == B.type) {// both LineType.XEquals\r\n\t\t\t\treturn null; // no collision\r\n\t\t\t} else {\r\n\t\t\t\tif (A.type == LineType.Normal) { // B.type = LineType.XEquals\r\n\t\t\t\t\treturn new Vector2(B.pointA.X, A.GetYPoint(B.pointA.X));\r\n\t\t\t\t} else { // B.type = LineType.Normal & A.type = LineType.XEquals\r\n\t\t\t\t\treturn new Vector2(A.pointA.X, B.GetYPoint(A.pointA.X));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Gets intersecting point between this line and another line</summary>\r\n\t\t/// <param name=\"A\">Line to get collision with</param>\r\n\t\t/// <returns>Nullable vector indicating collision</returns>\r\n\t\tpublic Vector2? GetIntersectionPoint(Line A) {\r\n\t\t\treturn GetIntersectionPoint(this, A);\r\n\t\t}\r\n\r\n\t\t/// <summary>Y point on a line with a given X value</summary>\r\n\t\t/// <returns>Y value</returns>\r\n\t\tpublic float GetYPoint(float X) {\r\n\t\t\tif (this.type == LineType.Normal)\r\n\t\t\t\treturn (gradient * X) + yIntercept;\r\n\t\t\telse\r\n\t\t\t\treturn float.PositiveInfinity;\r\n\t\t}\r\n\r\n\r\n\t\t/// <summary>X point on a line with a given Y value</summary>\r\n\t\t/// <returns>X value</returns>\r\n\t\tpublic float GetXPoint(float Y) {\r\n\t\t\tif (this.type == LineType.Normal)\r\n\t\t\t\treturn (Y - yIntercept) / gradient;\r\n\t\t\telse\r\n\t\t\t\treturn pointA.X;\r\n\t\t}\r\n\r\n\t\tpublic Vector2 pointA, pointB;\r\n\r\n\t\tpublic float gradient, yIntercept; // M\r\n\r\n\t\tpublic float maxPointY { get { return (pointA.Y > pointB.Y) ? pointA.Y : pointB.Y; } }\r\n\t\tpublic float maxPointX { get { return (pointA.X > pointB.X) ? pointA.X : pointB.X; } }\r\n\t\tpublic float minPointY { get { return (pointA.Y < pointB.Y) ? pointA.Y : pointB.Y; } }\r\n\t\tpublic float minPointX { get { return (pointA.X < pointB.X) ? pointA.X : pointB.X; } }\r\n\t\tpublic float Length { get { return (float)Math.Sqrt(Math.Pow(pointA.X - pointB.X, 2) + Math.Pow(pointA.Y - pointB.Y, 2)); } }\r\n\t\tpublic LineType type { get { return (float.IsInfinity(gradient) || float.IsInfinity(yIntercept)) ? LineType.XEquals : LineType.Normal; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7148217558860779, "alphanum_fraction": 0.7288930416107178, "avg_line_length": 29.352941513061523, "blob_id": "d22b776c0df88efbfc356f2cf6c7a0399bc529cf", "content_id": "1668d2ebb0e71419d8a3ba63dacc0de3f0735830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 97, "num_lines": 34, "path": "/HollowAether/Lib/GAssets/Weapons/Sword.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n\r\nusing HollowAether.Lib.GAssets;\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets.Weapons {\r\n\tpublic class Sword : SwordLikeWeapon {\r\n\t\tpublic Sword(Vector2 position) : base(position, 28, 28, true) { Initialize(@\"weapons\\sword\"); }\r\n\r\n\t\tprotected override void FinishAttacking() { base.FinishAttacking(); }\r\n\r\n\t\tpublic override int HorizontalBoundaryOffset { get; protected set; } = 8;\r\n\r\n\t\tpublic override float AngularThrowVelocity { get; protected set; } = (float)Math.PI * 4;\r\n\r\n\t\tpublic override int FrameWidth { get; protected set; } = 28;\r\n\r\n\t\tpublic override int FrameHeight { get; protected set; } = 28;\r\n\r\n\t\tpublic override int ActualWeaponWidth { get; protected set; } = 13;\r\n\r\n\t\tpublic override int ActualWeaponHeight { get; protected set; } = 28;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7028423547744751, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 25.64285659790039, "blob_id": "b531526c2b721197e5e869d26949aedb9640f0b8", "content_id": "e0b72ec2528366d2caf61ca2675a383e859527b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 82, "num_lines": 42, "path": "/HollowAether/Lib/Forms/LevelEditor/Editor/Lib/Forms/Asset View/NewAssetDialog.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel;\r\nusing System.Data;\r\nusing System.Drawing;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Windows.Forms;\r\n\r\nnamespace HollowAether.Lib.Forms.LevelEditor {\r\n\tpublic partial class NewAssetDialog : Form {\r\n\t\tpublic NewAssetDialog() {\r\n\t\t\tInitializeComponent();\r\n\r\n\t\t\ttypeComboBox.Items.AddRange(new string[] {\r\n\t\t\t\t\"String\", \"Animation\", \"Vector\", \"Integer\", \"Float\", \"Bool\"\r\n\t\t\t});\r\n\r\n\t\t\ttypeComboBox.SelectedIndex = 0;\r\n\t\t}\r\n\r\n\t\tprivate void saveButton_Click(object sender, EventArgs e) {\r\n\t\t\tDialogResult = DialogResult.OK;\r\n\t\t\tClose(); // Closes form instance\r\n\t\t}\r\n\r\n\t\tprivate void cancelButton_Click(object sender, EventArgs e) {\r\n\t\t\tClose();\r\n\t\t}\r\n\r\n\t\tprivate void NewAssetDialog_FormClosing(object sender, FormClosingEventArgs e) {\r\n\t\t\tif (DialogResult != DialogResult.OK) DialogResult = DialogResult.Cancel;\r\n\t\t}\r\n\r\n\t\tpublic string AssetType { get { return typeComboBox.SelectedItem.ToString(); } }\r\n\r\n\t\tpublic string AssetID { get { return idTextBox.Text; } }\r\n\r\n\t\tpublic string AssetValue { get { return valueTextBox.Text; } }\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6690012216567993, "alphanum_fraction": 0.6708282828330994, "avg_line_length": 39.56962203979492, "blob_id": "113428f0eb60f0bbd6e90ab3940d8fdaff99d6ef", "content_id": "d504123110760aa12b0652963f6e127c0ac3fcbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3286, "license_type": "no_license", "max_line_length": 160, "num_lines": 79, "path": "/HollowAether/Lib/InputOutput/Parsers/IniParser.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing System.Text.RegularExpressions;\r\n\r\nnamespace HollowAether.Lib.InputOutput.Parsers {\r\n\tpublic static class INIParser { // Also used for save files\r\n\t\tpublic class SectionContainer : Dictionary<String, Dictionary<String, String>> {\r\n\t\t\tpublic SectionContainer() : base() { } // Type definition, other contructors unnecessary\r\n\r\n\t\t\tpublic void AddSection(String sectionHeader) {\r\n\t\t\t\tif (!Keys.Contains(sectionHeader)) // Just in case doesn't exist\r\n\t\t\t\t\tthis[sectionHeader] = new Dictionary<String, String>();\r\n\t\t\t}\r\n\r\n\t\t\tpublic String ToFileContents() {\r\n\t\t\t\tStringBuilder builder = new StringBuilder(); // Builder more efficient than string\r\n\r\n\t\t\t\tforeach (String sectionHeader in Keys) {\r\n\t\t\t\t\tbuilder.AppendLine($\"[{sectionHeader}]\");\r\n\r\n\t\t\t\t\tforeach (String key in this[sectionHeader].Keys)\r\n\t\t\t\t\t\tbuilder.AppendLine($\"{key}={this[sectionHeader][key]}\");\r\n\r\n\t\t\t\t\tbuilder.AppendLine(\"\"); // Leave trailing line break\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn builder.ToString(); // Cast to string and return to sender\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/// <summary>Parses INI file type contents</summary>\r\n\t\t/// <param name=\"fContents\">Contents of file</param>\r\n\t\t/// <param name=\"fpath\">Path to file, used for exception notification</param>\r\n\t\t/// <param name=\"throwExceptionOnInvalidLine\">Whether to ignore or let throw</param>\r\n\t\t/// <param name=\"throwExceptionOnValueWithoutSection\">Whether to ignore or let throw</param>\r\n\t\t/// <remarks>\r\n\t\t///\t\t!, # => Used for Commenting\r\n\t\t///\t\t[TEXT] => Used for section headers\r\n\t\t///\t\tKey=Value => Used for key value definitions\r\n\t\t/// </remarks>\r\n\t\t/// <returns>Complex data type consiting of key=section, key=key, value=value</returns>\r\n\t\tpublic static SectionContainer Parse(String fContents, String fpath, bool throwExceptionOnInvalidLine=false, bool throwExceptionOnValueWithoutSection=false) {\r\n\t\t\tString sectionHeader = null; // Header for current section\r\n\r\n\t\t\tSectionContainer sections = new SectionContainer(); // Dictionary<String, Dictionary<String, String>>();\r\n\r\n\t\t\tvar lines = (from X in fContents.Split('\\n') select X.Trim());\r\n\t\t\t// Gets rid of leading and trailing whitespace + makes into lines\r\n\r\n\t\t\tforeach (String line in lines) {\r\n\t\t\t\tif (line.Length == 0 || (new char[] { '!', '#' }).Contains(line[0]))\r\n\t\t\t\t\tcontinue; // Skip, blank line or comment line. Doesn't matter to me\r\n\r\n\t\t\t\tif (Regex.IsMatch(line, @\"\\[.+\\]\")) { // Section definition\r\n\t\t\t\t\tsectionHeader = line.Substring(1, line.Length - 2);\r\n\t\t\t\t\tsections.AddSection(sectionHeader); // Create new container\r\n\t\t\t\t} else if (Regex.IsMatch(line, @\".+=.*\")) { // Is key value definition\r\n\t\t\t\t\tif (String.IsNullOrEmpty(sectionHeader)) { // No section for var\r\n\t\t\t\t\t\tif (throwExceptionOnValueWithoutSection)\r\n\t\t\t\t\t\t\tthrow new Exception(\"\");\r\n\t\t\t\t\t\t// Else continue on to next line\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tString[] splitLine = line.Split('='); // Python wouldn't need this line :(\r\n\t\t\t\t\t\tsections[sectionHeader][splitLine[0]] = splitLine[1]; // Store key/value pair \r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (throwExceptionOnInvalidLine) {\r\n\t\t\t\t\tthrow new Exception($\"Unknown line {line}\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn sections; // All sections within argument file\r\n\t\t}\r\n\r\n\t\t\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6774924397468567, "alphanum_fraction": 0.6774924397468567, "avg_line_length": 25.020408630371094, "blob_id": "03f59b2a7fc10e1bd720a5d38d0182e5b73c731e", "content_id": "ed46b8817e9ed288fb56b7f2a2ff6dbd15a47c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 83, "num_lines": 49, "path": "/HollowAether/Lib/Entity/Flag.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace HollowAether {\r\n\t/// <summary>Holder class that can contain a bool</summary>\r\n\tpublic class Flag : Object {\r\n\t\tpublic Flag(bool initialValue = false) {\r\n\t\t\t_value = defaultValue = initialValue;\r\n\t\t\tFlagChanged = (s, e) => { s._value = e; };\r\n\t\t}\r\n\t\t\r\n\t\tpublic override string ToString() {\r\n\t\t\treturn $\"Flag '{_value}'\";\r\n\t\t}\r\n\r\n\t\tpublic void ChangeFlag(bool updatedValue) {\r\n\t\t\tValue = updatedValue;\r\n\t\t}\r\n\r\n\t\tpublic bool ValueChangedFromDefault() {\r\n\t\t\treturn defaultValue != Value;\r\n\t\t}\r\n\r\n\t\tprivate void _ChangeFlag(bool updatedValue) {\r\n\t\t\tif (_value != updatedValue) {\r\n\t\t\t\tFlagChanged(this, updatedValue);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static implicit operator Boolean(Flag self) {\r\n\t\t\treturn self._value;\r\n\t\t}\r\n\r\n\t\t/// <summary>Event called when flag value has been changed/updated etc.</summary>\r\n\t\tpublic event FlagChanged_EventHandler FlagChanged;\r\n\r\n\t\tpublic delegate void FlagChanged_EventHandler(Flag self, bool flagValue);\r\n\r\n\t\t/// <summary>Actual value represented by flag instance</summary>\r\n\t\tprivate bool _value;\r\n\r\n\t\tpublic bool Value { get { return _value; } set { _ChangeFlag(value); } }\r\n\r\n\t\tpublic readonly bool defaultValue; // Default Value Assigned At Flag Start\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.7375457286834717, "alphanum_fraction": 0.738500714302063, "avg_line_length": 34.109195709228516, "blob_id": "ba7f73e5d5e5425259eddac622ce7eba5614e2f2", "content_id": "307d3fb21ea1c751bf25d092e8f96f2f7f5f750c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6285, "license_type": "no_license", "max_line_length": 108, "num_lines": 174, "path": "/HollowAether/Lib/GAssets/Volatile/Implementation.cs", "repo_name": "mohkale/HollowAether", "src_encoding": "UTF-8", "text": "#region SystemImports\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n#endregion\r\n\r\n#region XNAImports\r\nusing Microsoft.Xna.Framework;\r\nusing Microsoft.Xna.Framework.Graphics;\r\nusing Microsoft.Xna.Framework.Input;\r\nusing GV = HollowAether.Lib.GlobalVars;\r\n#endregion\r\n\r\n#region HollowAetherImports\r\nusing HollowAether.Lib.Exceptions.CE;\r\nusing HollowAether.Lib.Exceptions;\r\nusing HollowAether.Lib.MapZone;\r\n#endregion\r\n\r\nnamespace HollowAether.Lib.GAssets {\r\n\t/// <summary>Volatile namespace to seperate manager from implementation</summary>\r\n\tnamespace Volatile {\r\n\t\tpublic abstract class VolatilityManager {\r\n\t\t\tprotected VolatilityManager(object arg, bool implementerReadOnly) {\r\n\t\t\t\tImplementerCanBeChanged = !implementerReadOnly;\r\n\t\t\t\tif (arg != null) InitialiseVolatility(arg);\r\n\t\t\t}\r\n\r\n\t\t\tpublic static VolatilityManager GetManager(VolatilityType type, object arg=null, bool readOnly=false) {\r\n\t\t\t\tswitch (type) {\r\n\t\t\t\t\tcase VolatilityType.Timeout: return new TimeoutVolatilityManager(arg, readOnly);\r\n\t\t\t\t\tcase VolatilityType.Other: return new OtherVolatilityManager(arg, readOnly);\r\n\t\t\t\t\tdefault: throw new HollowAetherException($\"Unknown Volatility Type {type}\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic void InitialiseVolatility(object volatilityArg) {\r\n\t\t\t\tif (ValidArg(volatilityArg)) Implementer = volatilityArg; else {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Invalid Volatility Arg\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic void ChangeImplementer(object arg) {\r\n\t\t\t\tif (ImplementerCanBeChanged) InitialiseVolatility(arg); else {\r\n\t\t\t\t\tthrow new HollowAetherException($\"Manager Implementation Can't Be Changed\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Delete(IMonoGameObject self) {\r\n\t\t\t\tGV.MonoGameImplement.removalBatch.Add(self);\r\n\t\t\t\tDeleting(); // Trigger deleting event handler\r\n\t\t\t}\r\n\r\n\t\t\tpublic void Update(IMonoGameObject self) {\r\n\t\t\t\tif (ReadyToDelete(self)) Delete(self); else UponNonDeletion(self);\r\n\t\t\t}\r\n\r\n\t\t\tpublic abstract bool ValidArg(object arg);\r\n\r\n\t\t\tprotected abstract bool ReadyToDelete(IMonoGameObject self);\r\n\r\n\t\t\tprotected abstract void UponNonDeletion(IMonoGameObject self);\r\n\r\n\t\t\tpublic object Implementer { get; protected set; } // VolatilityArg\r\n\r\n\t\t\tpublic bool ImplementerCanBeChanged { get; private set; }\r\n\r\n\t\t\tpublic event Action Deleting = () => { };\r\n\t\t}\r\n\r\n\t\tpublic sealed class OtherVolatilityManager : VolatilityManager {\r\n\t\t\tpublic OtherVolatilityManager(object arg=null, bool implementerReadOnly=true) \r\n\t\t\t\t: base(arg, implementerReadOnly) { }\r\n\r\n\t\t\tpublic override bool ValidArg(object arg) {\r\n\t\t\t\treturn arg is ImplementVolatility;\r\n\t\t\t}\r\n\r\n\t\t\tprotected override bool ReadyToDelete(IMonoGameObject _object) {\r\n\t\t\t\treturn ((ImplementVolatility)Implementer)((IMonoGameObject)_object);\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void UponNonDeletion(IMonoGameObject self) {\r\n\t\t\t\t// Do Nothing // throw new NotImplementedException();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic sealed class TimeoutVolatilityManager : VolatilityManager {\r\n\t\t\tpublic TimeoutVolatilityManager(object arg=null, bool implementerReadOnly=true)\r\n\t\t\t\t: base(arg, implementerReadOnly) { }\r\n\r\n\t\t\tpublic void IncrementImplementer(int value) {\r\n\t\t\t\tChangeImplementer((int)Implementer + value);\r\n\t\t\t}\r\n\r\n\t\t\tpublic void DecrementImplementer(int value) {\r\n\t\t\t\tChangeImplementer((int)Implementer - value);\r\n\t\t\t}\r\n\r\n\t\t\tprotected override bool ReadyToDelete(IMonoGameObject self) {\r\n\t\t\t\treturn (int)Implementer < 0;\r\n\t\t\t}\r\n\r\n\t\t\tprotected override void UponNonDeletion(IMonoGameObject self) {\r\n\t\t\t\tImplementer = (int)Implementer - GV.MonoGameImplement.gameTime.ElapsedGameTime.Milliseconds;\r\n\t\t\t}\r\n\r\n\t\t\tpublic override bool ValidArg(object arg) {\r\n\t\t\t\ttry { Convert.ToInt32(arg); return true; } catch { return false; }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// <summary>Enumeration representing acceptable volatility types</summary>\r\n\tpublic enum VolatilityType { Timeout, Other } // other uses ImplementVolatility Enumeration\r\n\t// FrameTimeout is buggy and needs re-assesment, ignore use until such a time when it functions correctly\r\n\r\n\t/// <summary>Acceptable delegate to pass as arg to volatileManager or IVolatile class Initializer</summary>\r\n\t/// <param name=\"iv\">IVolatile class instance for check purposes; doesn't have to be used</param>\r\n\t/// <returns>Boolean telling class wether or not the class is ready to be deleted</returns>\r\n\tpublic delegate bool ImplementVolatility(IMonoGameObject _volatile); // for other check\r\n\r\n\t#region Implementations\r\n\tpublic abstract partial class VolatileSprite : Sprite, IVolatile {\r\n\t\tpublic VolatileSprite(Vector2 position, int width, int height, bool animationRunning = true)\r\n\t\t\t: base(position, width, height, animationRunning) {}\r\n\r\n\t\tpublic void InitializeVolatility(VolatilityType vt, object arg) {\r\n\t\t\tVolatilityManager = Volatile.VolatilityManager.GetManager(vt, arg);\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tVolatilityManager.Update(this);\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t}\r\n\t\t\r\n\t\tpublic Volatile.VolatilityManager VolatilityManager { get; private set; }\r\n\t}\r\n\r\n\tpublic abstract class VolatileCollideableSprite : CollideableSprite, IVolatile {\r\n\t\tpublic VolatileCollideableSprite(Vector2 position, int width, int height, bool animationRunning = true)\r\n\t\t\t: base(position, width, height, animationRunning) { }\r\n\r\n\t\tpublic void InitializeVolatility(VolatilityType vt, object arg) {\r\n\t\t\tVolatilityManager = Volatile.VolatilityManager.GetManager(vt, arg);\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tVolatilityManager.Update(this);\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t}\r\n\t\t\r\n\t\tpublic Volatile.VolatilityManager VolatilityManager { get; private set; }\r\n\t}\r\n\r\n\tpublic abstract class VolatileBodySprite : BodySprite, IVolatile {\r\n\t\tpublic VolatileBodySprite(Vector2 position, int width, int height, bool animationRunning = true)\r\n\t\t\t: base(position, width, height, animationRunning) { }\r\n\r\n\t\tpublic void InitializeVolatility(VolatilityType vt, object arg) {\r\n\t\t\tVolatilityManager = Volatile.VolatilityManager.GetManager(vt, arg);\r\n\t\t}\r\n\r\n\t\tpublic override void Update(bool updateAnimation) {\r\n\t\t\tVolatilityManager.Update(this);\r\n\t\t\tbase.Update(updateAnimation);\r\n\t\t}\r\n\r\n\t\tpublic Volatile.VolatilityManager VolatilityManager { get; private set; }\r\n\t}\r\n\t#endregion\r\n}\r\n" } ]
168
Therapoid/django-assent
https://github.com/Therapoid/django-assent
05114c1f2c9885dd2a7231aff1e217ff0b67b1ba
2cd9914f48704ae6737f36309fba311df974fa77
6fac742d52bc4a97da009302f48fc482626591b5
refs/heads/master
2023-02-12T07:27:51.624437
2017-02-15T03:43:58
2017-02-15T03:43:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6612021923065186, "alphanum_fraction": 0.6748633980751038, "avg_line_length": 23, "blob_id": "a7d4cee3817758a7717d17a68a9ae6fbbb1384a9", "content_id": "eab460c6f26508e588b3a1b6bb0b9b43fd22f450", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1464, "license_type": "permissive", "max_line_length": 80, "num_lines": 61, "path": "/tests/conftest.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport os\nimport pytest\n\nfrom django import setup\nfrom django.utils import timezone\nfrom django.contrib.auth import get_user_model\n\nfrom assent.models import Agreement, AgreementUser, AgreementVersion\n\n\ndef pytest_configure():\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')\n setup()\n\n\[email protected]\ndef user():\n obj = get_user_model().objects.create(email='[email protected]', username='test_user')\n return obj\n\n\[email protected]\ndef agreement():\n obj = Agreement.objects.create(\n document_key='test key',\n description='test description',\n short_description='test short description',\n latest_version=None,\n date_modified=None,\n )\n return obj\n\n\[email protected]\ndef agreement_version(agreement):\n obj = AgreementVersion.objects.create(\n agreement=agreement,\n short_title='test version',\n full_title='test version',\n content='test content',\n content_format='TEXT',\n release_date=None,\n )\n agreement.latest_version = obj\n agreement.date_modified = obj.release_date\n agreement.save()\n return obj\n\n\[email protected]\ndef agreement_user(agreement_version, user):\n acceptance_date = timezone.now()\n obj = AgreementUser.objects.create(\n user=user,\n agreement_version=agreement_version,\n acceptance_date=acceptance_date,\n ip_address='2001:db8:85a3:0:0:8a2e:370:7334'\n )\n return obj\n" }, { "alpha_fraction": 0.6010679006576538, "alphanum_fraction": 0.604881763458252, "avg_line_length": 23.259260177612305, "blob_id": "aefcb28d961b473b7a42cefb142d2a2e99f1b1cd", "content_id": "1be29de9f7306f6acbb77e60fca907dcae6daf87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "permissive", "max_line_length": 95, "num_lines": 54, "path": "/tasks.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nfrom invoke import task\n\nBUILDDIR = \"build\"\nPROJECT = \"assent\"\n\n\n@task\ndef clean(ctx):\n \"\"\"Removes all the cache files\"\"\"\n ctx.run(\"find . -type d -name __pycache__ | xargs rm -rf\")\n ctx.run('rm -rf ./.cache')\n builddir = os.path.join(__file__, BUILDDIR)\n if os.path.exists(builddir):\n print('Removing builddir {}'.format(builddir))\n ctx.run('rm -rf {}'.format(builddir))\n\n\n@task\ndef install(ctx):\n \"\"\"Installs the libraries required to run the application\"\"\"\n ctx.run(\"pip install -U pip\")\n ctx.run(\"pip install -qr requirements/base.txt\")\n\n\n@task(install)\ndef develop(ctx):\n \"\"\"Installs all the libraries used for development\"\"\"\n ctx.run(\"pip install -qr requirements/dev.txt\")\n\n\n@task\ndef checks(ctx):\n \"\"\"Runs pep8/flake8 checks on the code\"\"\"\n excl = \"--exclude='build/,*migrations/*'\"\n ctx.run(\"pep8 {} .\".format(excl))\n ctx.run(\"flake8 {} .\".format(excl))\n\n\n@task(develop)\ndef test(ctx):\n \"\"\"Runs the tests\"\"\"\n ctx.run(\n 'PYTHONPATH=`pwd` '\n \"py.test --cov-config .coveragerc --cov-report html --cov-report term --cov={}\".format(\n PROJECT\n ),\n pty=True\n )\n\n if sys.platform == 'darwin':\n ctx.run('open {}/coverage/index.html'.format(BUILDDIR))\n\n" }, { "alpha_fraction": 0.588870644569397, "alphanum_fraction": 0.59779292345047, "avg_line_length": 49.10588073730469, "blob_id": "04df3901dbd4fd65f25b1edbe647a18159d13021", "content_id": "a28804c14053900a2a4511d69b7787655f7dd394", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4259, "license_type": "permissive", "max_line_length": 178, "num_lines": 85, "path": "/assent/migrations/0001_initial.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.5 on 2017-02-15 03:43\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Agreement',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('document_key', models.CharField(default='', max_length=255, unique=True, verbose_name='document key')),\n ('slug', models.SlugField(default='', max_length=255, verbose_name='slug')),\n ('description', models.CharField(default='', max_length=4096, verbose_name='description')),\n ('short_description', models.CharField(default='', max_length=255, verbose_name='short description')),\n ('date_modified', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False, null=True)),\n ],\n options={\n 'verbose_name': 'agreement',\n 'verbose_name_plural': 'agreements',\n },\n ),\n migrations.CreateModel(\n name='AgreementUser',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('acceptance_date', models.DateTimeField(blank=True, null=True, verbose_name='acceptance date')),\n ('ip_address', models.GenericIPAddressField(blank=True, null=True, verbose_name='IP address')),\n ],\n options={\n 'verbose_name': 'agreement user',\n 'verbose_name_plural': 'agreement users',\n },\n ),\n migrations.CreateModel(\n name='AgreementVersion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('short_title', models.CharField(default='', max_length=255, verbose_name='short title')),\n ('full_title', models.CharField(default='', max_length=1023, verbose_name='full title')),\n ('content', models.TextField(blank=True, default='', verbose_name='content')),\n ('content_format', models.CharField(default='', max_length=4, verbose_name='Content format')),\n ('release_date', models.DateTimeField(auto_now_add=True, verbose_name='release date')),\n ('agreement', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='versions', to='assent.Agreement', verbose_name='agreement')),\n ('users', models.ManyToManyField(related_name='agreement_versions', through='assent.AgreementUser', to=settings.AUTH_USER_MODEL, verbose_name='users')),\n ],\n options={\n 'verbose_name': 'agreement version',\n 'get_latest_by': ('release_date',),\n 'verbose_name_plural': 'agreement versions',\n 'ordering': ('-release_date',),\n },\n ),\n migrations.AddField(\n model_name='agreementuser',\n name='agreement_version',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='agreement_users', to='assent.AgreementVersion', verbose_name='agreement_version'),\n ),\n migrations.AddField(\n model_name='agreementuser',\n name='user',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='agreement',\n name='latest_version',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='agreement_latest_version', to='assent.AgreementVersion'),\n ),\n migrations.AlterUniqueTogether(\n name='agreementuser',\n unique_together=set([('user', 'agreement_version')]),\n ),\n ]\n" }, { "alpha_fraction": 0.6784350872039795, "alphanum_fraction": 0.6822519302368164, "avg_line_length": 32.80644989013672, "blob_id": "54e8a643f9b080b9e9e207e8cfbdf36a5d74c463", "content_id": "da77eaa48410c74c7255f4957dd7478f0cf001bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "permissive", "max_line_length": 111, "num_lines": 31, "path": "/tests/test_models.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport pytest\n\n\[email protected]_db\nclass TestAgreement:\n def test_str(self, agreement):\n assert str(agreement) == 'test key'\n\n\[email protected]_db\nclass TestAgreementVersion:\n def test_str(self, agreement_version):\n timestamp = agreement_version.release_date\n assert str(agreement_version) == 'Agreement: \"test key\" released: {0:%Y-%m-%d %H:%M}'.format(timestamp)\n\n def test_plain_text_render(self, agreement_version):\n assert agreement_version.get_rendered_content() == '<p>test content</p>'\n\n\[email protected]_db\nclass TestAgreementUser:\n def test_str(self, agreement_version, agreement_user, user):\n # Assign user to having signed the agreement\n assert str(agreement_user) == \"User: {0}, agreement: {1}\".format(\n user, agreement_version)\n\n def test_relationships(self, agreement_user, agreement_version, user):\n assert agreement_version in list(user.agreement_versions.all())\n assert user in list(agreement_version.users.all())\n" }, { "alpha_fraction": 0.6372092962265015, "alphanum_fraction": 0.6395348906517029, "avg_line_length": 24.294116973876953, "blob_id": "7ab35ebf9d320867915f91a481ee921a610efc4b", "content_id": "509747fb2c275642cb963350378b10e44718288a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "permissive", "max_line_length": 90, "num_lines": 17, "path": "/assent/urls.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url, include\n\n\nfrom .views import (\n AgreementDetailView,\n AgreementListView,\n AgreementFormView,\n)\n\n\nurlpatterns = [\n url(r'^$', AgreementListView.as_view(), name='agreement_list'),\n url(r'^(?P<slug>[^/]+)/$', AgreementDetailView.as_view(), name='agreement_detail'),\n url(r'^(?P<slug>[^/]+)/accept/$', AgreementFormView.as_view(), name='agreement_form'),\n]\n" }, { "alpha_fraction": 0.6023738980293274, "alphanum_fraction": 0.6073194742202759, "avg_line_length": 28.764705657958984, "blob_id": "549f6f4fe90f8249a166591f2a46641622996135", "content_id": "af52df3195d26e30774c13967c33a94145be1d06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1011, "license_type": "permissive", "max_line_length": 91, "num_lines": 34, "path": "/assent/templates/assent/agreement_form.html", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "{% extends \"assent/base.html\" %}\n{% load bootstrap3 breadcrumb_tags i18n l10n staticfiles %}\n\n\n{% block title %}{{ agreement_version.full_title }} - {{ block.super }}{% endblock title %}\n\n\n{% block heading %}\n {{ agreement_version.full_title }}\n{% endblock %}\n\n\n{% block breadcrumb %}\n {{ block.super }}\n {% blocktrans asvar accept_agreement %}Agreements{% endblocktrans %}\n {% breadcrumb_url accept_agreement 'assent:home' %}\n {% breadcrumb agreement_version.full_title %}\n{% endblock %}\n\n\n\n{% block content %}\n <form action=\"\" enctype=\"multipart/form-data\" method=\"post\">\n {% csrf_token %}\n {% bootstrap_form form %}\n <div class=\"agreement\">\n {{ agreement_version.get_rendered_content|safe }}\n </div>\n <button class=\"btn btn-primary\" type=\"submit\">{% trans \"Accept\" %}</button>\n <button class=\"btn btn-default\" type=\"cancel\">{% trans \"Cancel\" %}</button>\n </form>\n {{ form.media.css }}\n {{ form.media.js }}\n{% endblock content %}" }, { "alpha_fraction": 0.5948795080184937, "alphanum_fraction": 0.5963855385780334, "avg_line_length": 27.869565963745117, "blob_id": "439b3bb166f8e11f37dc92513a9e7f7c82cad9a5", "content_id": "09fd170f2db156f5db4e0b3675f87845db65da81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "permissive", "max_line_length": 75, "num_lines": 23, "path": "/assent/views/forms.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django import forms\n\nfrom ..models import AgreementUser\n\n\nclass AgreementForm(forms.ModelForm):\n hidden_fields = (\n 'user', 'agreement_version', 'ip_address', 'acceptance_date', )\n\n class Meta:\n model = AgreementUser\n fields = (\n 'user', 'agreement_version', 'ip_address', 'acceptance_date', )\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Hides any fields listed in the class property: hidden_fields.\n \"\"\"\n super(AgreementForm, self).__init__(*args, **kwargs)\n for fld in self.hidden_fields:\n self.fields[fld].widget = forms.widgets.HiddenInput()\n" }, { "alpha_fraction": 0.6652960777282715, "alphanum_fraction": 0.6674890518188477, "avg_line_length": 33.74285888671875, "blob_id": "6781892c01975b1c9b4c18aff4bcc99874e279ac", "content_id": "c8d5c970a4f540e6a77409821f09e002730068b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3648, "license_type": "permissive", "max_line_length": 80, "num_lines": 105, "path": "/assent/views/assent.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import timezone\nfrom django.utils.decorators import method_decorator\nfrom django.utils.functional import cached_property\nfrom django.views.generic import DetailView, ListView\nfrom django.views.generic.detail import SingleObjectTemplateResponseMixin\nfrom django.views.generic.edit import ModelFormMixin, ProcessFormView\n\nfrom ..models import Agreement, AgreementUser\nfrom .forms import AgreementForm\n\n\n@method_decorator(login_required, name='dispatch')\nclass AgreementListView(ListView):\n model = AgreementUser\n template_name = 'assent/agreement_list.html'\n\n def get_queryset(self):\n \"\"\"\n Override to use the user from the request as part of the query.\n \"\"\"\n queryset = super(AgreementListView, self).get_queryset()\n queryset = queryset.filter(user=self.request.user)\n return queryset\n\n\nclass AgreementMixin(object):\n @cached_property\n def agreement(self):\n \"\"\"\n Returns the Agreement specified in the url\n \"\"\"\n slug = self.kwargs.get('slug', None)\n return get_object_or_404(Agreement, slug=slug)\n\n def get_object(self, queryset=None):\n agreement_version = self.agreement.latest_version\n if queryset is None:\n queryset = self.get_queryset()\n obj = queryset.filter(\n user=self.request.user, agreement_version=agreement_version).first()\n return obj\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Ensures agreement and its latest_version are in the context.\n \"\"\"\n context = super(AgreementMixin, self).get_context_data(**kwargs)\n context['agreement'] = self.agreement\n context['agreement_version'] = self.agreement.latest_version\n return context\n\n\n@method_decorator(login_required, name='dispatch')\nclass AgreementDetailView(AgreementMixin, DetailView):\n model = AgreementUser\n template_name = 'assent/agreement_detail.html'\n\n\n@method_decorator(login_required, name='dispatch')\nclass AgreementFormView(AgreementMixin, SingleObjectTemplateResponseMixin,\n ModelFormMixin, ProcessFormView):\n \"\"\"\n This is essentially a CreateOrUpdateView. If the object dosn't exist, it is\n created. If it already does, then it is updated.\n \"\"\"\n model = AgreementUser\n template_name = 'assent/agreement_form.html'\n form_class = AgreementForm\n success_url = reverse_lazy('assent:agreement_list')\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super(AgreementFormView, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super(AgreementFormView, self).post(request, *args, **kwargs)\n\n @cached_property\n def client_ip_address(self):\n \"\"\"\n Attempts to return the user's IP address.\n :return:\n \"\"\"\n x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = self.request.META.get('REMOTE_ADDR')\n return ip\n\n def get_initial(self):\n initial = self.initial.copy()\n initial.update({\n 'user': self.request.user,\n 'agreement_version': self.agreement.latest_version,\n 'acceptance_date': timezone.now(),\n 'ip_address': self.client_ip_address,\n })\n return initial\n" }, { "alpha_fraction": 0.5319148898124695, "alphanum_fraction": 0.5531914830207825, "avg_line_length": 14.666666984558105, "blob_id": "95aaf806932b21a47f317c038120f49278a3b069", "content_id": "279f3a6116a90c9a9be07760abcc77cf7b8bf333", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 47, "license_type": "permissive", "max_line_length": 23, "num_lines": 3, "path": "/assent/views/__init__.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom .assent import *\n" }, { "alpha_fraction": 0.6359236240386963, "alphanum_fraction": 0.6429147720336914, "avg_line_length": 36.189998626708984, "blob_id": "023552c61834597bf29de617e23f1f73229855a6", "content_id": "35950bf45a599294a03c432f6901cc40ea93ff7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3719, "license_type": "permissive", "max_line_length": 77, "num_lines": 100, "path": "/assent/models.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom transcode.render import render\n\n\nclass Agreement(models.Model):\n document_key = models.CharField(\n _('document key'), max_length=255, blank=False, default='',\n unique=True)\n slug = models.SlugField(\n _('slug'), max_length=255, blank=False, default='')\n description = models.CharField(\n _('description'), max_length=4096, blank=False, default='')\n short_description = models.CharField(\n _('short description'), max_length=255, blank=False, default='')\n\n latest_version = models.OneToOneField(\n 'assent.AgreementVersion', blank=True, null=True,\n related_name='agreement_latest_version')\n # Note, this should only be updated when we add a new version\n # This is currently done in AgreementVersion.save()\n date_modified = models.DateTimeField(\n default=timezone.now, blank=True, null=True, editable=False)\n\n class Meta:\n verbose_name = _('agreement')\n verbose_name_plural = _('agreements')\n\n def get_absolute_url(self):\n return reverse('assent:agreement_detail', kwargs={'slug': self.slug})\n\n def __str__(self):\n return self.document_key\n\n\nclass AgreementUser(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL)\n agreement_version = models.ForeignKey(\n to='assent.AgreementVersion',\n verbose_name=_('agreement_version'),\n related_name='agreement_users', blank=False)\n acceptance_date = models.DateTimeField(\n _('acceptance date'), blank=True, null=True)\n ip_address = models.GenericIPAddressField(\n _('IP address'), blank=True, null=True)\n\n class Meta:\n verbose_name = _('agreement user')\n verbose_name_plural = _('agreement users')\n unique_together = (('user', 'agreement_version', ), )\n\n def __str__(self):\n return _('User: {0}, agreement: {1}').format(\n self.user, self.agreement_version)\n\n\nclass AgreementVersion(models.Model):\n users = models.ManyToManyField(\n to=settings.AUTH_USER_MODEL, through='assent.AgreementUser',\n related_name='agreement_versions', verbose_name=_('users'))\n agreement = models.ForeignKey(\n to='assent.Agreement', verbose_name=_('agreement'),\n related_name='versions', blank=False)\n short_title = models.CharField(\n _('short title'), max_length=255, blank=False, default='')\n\n full_title = models.CharField(\n _('full title'), max_length=1023, blank=False, default='')\n content = models.TextField(\n _('content'), blank=True, default='')\n content_format = models.CharField(\n _('Content format'), max_length=4, blank=False, default='')\n release_date = models.DateTimeField(\n _('release date'), auto_now_add=True)\n\n class Meta:\n ordering = ('-release_date', )\n get_latest_by = ('release_date', )\n verbose_name = _('agreement version')\n verbose_name_plural = _('agreement versions')\n\n def __str__(self):\n return _('Agreement: \"{0}\" released: {1:%Y-%m-%d %H:%M}').format(\n self.agreement.document_key, self.release_date)\n\n def get_rendered_content(self):\n return render(self.content, self.content_format)\n\n def save(self, *args, **kwargs):\n super(AgreementVersion, self).save(*args, **kwargs)\n if self.pk is not None and self.agreement_id:\n self.agreement.latest_version = self\n self.agreement.date_modified = self.release_date\n self.agreement.save()\n" }, { "alpha_fraction": 0.5284823179244995, "alphanum_fraction": 0.5293139219284058, "avg_line_length": 25.72222137451172, "blob_id": "2326edb4de7c83d9b2d39613c582a337dca49a17", "content_id": "b5ceae653ffe10cdf58151eb3efde7223ceaa389", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2405, "license_type": "permissive", "max_line_length": 80, "num_lines": 90, "path": "/assent/admin.py", "repo_name": "Therapoid/django-assent", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.contrib import admin\nfrom django.utils.translation import ugettext as _\n\nfrom transcode.conf import get_content_formatters\n\nfrom .models import Agreement, AgreementUser, AgreementVersion\n\nContentFormat = get_content_formatters('ASSENT_FORMATTERS')\n\n\n# ===== INLINES ===============================================================\n\nclass AgreementVersionForm(forms.ModelForm):\n content_format = forms.ChoiceField(\n label=_('Content Format'), required=True, choices=ContentFormat.CHOICES)\n\n class Meta:\n model = AgreementVersion\n fields = (\n 'short_title',\n 'full_title',\n 'content',\n 'content_format',\n )\n\n def __init__(self, *args, **kwargs):\n super(AgreementVersionForm, self).__init__(*args, **kwargs)\n instance = self.instance\n if not instance or not instance.content_format:\n self.fields['content_format'].initial = ContentFormat.DEFAULT\n\n\nclass AgreementVersionInlineAdmin(admin.StackedInline):\n model = AgreementVersion\n extra = 0\n readonly_fields = ('release_date', )\n form = AgreementVersionForm\n fieldsets = (\n (None, {\n 'fields': (\n 'short_title',\n 'full_title',\n 'content',\n 'content_format',\n 'release_date',\n )\n }),\n )\n\n# ===== ADMINS ================================================================\n\n\nclass AgreementAdmin(admin.ModelAdmin):\n inlines = (AgreementVersionInlineAdmin, )\n prepopulated_fields = {\"slug\": (\"document_key\",)}\n fieldsets = (\n (None, {\n 'fields': (\n 'document_key',\n 'slug',\n 'description',\n 'short_description',\n 'latest_version',\n )\n }),\n )\n\n\nadmin.site.register(Agreement, AgreementAdmin)\n\n\nclass AgreementUserAdmin(admin.ModelAdmin):\n list_display = ('user', 'agreement_version', 'acceptance_date', )\n readonly_fields = ('acceptance_date', 'ip_address', )\n fieldsets = (\n (None, {\n 'fields': (\n 'user',\n 'agreement_version',\n 'acceptance_date',\n 'ip_address',\n )\n }),\n )\n\n\nadmin.site.register(AgreementUser, AgreementUserAdmin)\n" } ]
11
danigrim/flaskclassifier
https://github.com/danigrim/flaskclassifier
b375aa3035fa7933043404270acec6d3562e4288
1bdeb086c8171178095206fffa7a598b95d29d64
3375e4d220db973518ac3b94cf0d37592c8197be
refs/heads/main
2023-02-13T04:10:13.780235
2021-01-12T14:11:31
2021-01-12T14:11:31
328,407,579
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6240963935852051, "alphanum_fraction": 0.6481927633285522, "avg_line_length": 26.086956024169922, "blob_id": "bc74648430c4b9ee2b387cb4d86de229c4b8a3f6", "content_id": "def8dd737bb39ccb4c1abab5cdc5cb5ac3c0d124", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 171, "num_lines": 46, "path": "/flaskclassifier.py", "repo_name": "danigrim/flaskclassifier", "src_encoding": "UTF-8", "text": "import sys\n\nfrom flask import Flask, request, jsonify\nimport pickle\nimport pandas as pd\nimport json\nimport os\n\nfilename = 'rfc_model3.pkl'\napp = Flask(__name__)\nmodel = pickle.load(open(filename,'rb'))\n\[email protected](\"/\")\ndef home_view():\n return \"<h1>Welcome to my Web-Application for Heart Disease Forecasting</h1>\"\n\n\[email protected]('/predict_single', methods=['GET'])\ndef predict_single():\n try:\n df = pd.DataFrame.from_dict({feat: [float(request.args.get(feat))] for feat in request.args})\n prediction = model.predict(df)[0]\n except:\n return \"URL not properly formatted. Try format: /predict_single?age=10&sex=1&trestbps=140&chol=193&fbs=0.0&restecg=0.0&thalach=145&exang=1.0&oldpeak=1.0&slope=2.0\"\n return str(prediction)\n\n\[email protected]('/predict_many', methods=['POST'])\ndef predict_many():\n try:\n content = json.loads(request.get_json())\n df = pd.DataFrame(content)\n prediction = model.predict(df)\n except Exception as e:\n return jsonify({'error':\"JSON wrong format\" })\n lists = prediction.tolist()\n return json.dumps(lists)\n\n\nif __name__ == \"main\":\n port = os.environ.get('PORT')\n\n if port:\n app.run(host='0.0.0.0', port=int(port))\n else:\n app.run()" } ]
1
mattdbrown17/MMFE
https://github.com/mattdbrown17/MMFE
9b28a828cd848818ae966ac1bc3537d51c8a57e4
b0fc50deba5ccabf83eda9437f228e04d41f5a71
2dcc1580dc677800a8a6293695011856ac29fb27
refs/heads/master
2020-04-23T11:40:00.007961
2019-02-21T20:37:16
2019-02-21T20:37:16
171,143,847
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5247030854225159, "alphanum_fraction": 0.5501187443733215, "avg_line_length": 28.507246017456055, "blob_id": "d0a6f2cb506e8ad185d9ad692c6fe709816c7071", "content_id": "988ef6d7c7053abb8152aa61815d1e2f5d4da042", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4210, "license_type": "no_license", "max_line_length": 156, "num_lines": 138, "path": "/BSM_binomial.py", "repo_name": "mattdbrown17/MMFE", "src_encoding": "UTF-8", "text": "import itertools as it\r\nimport numpy as np\r\n\r\ndef main_program():\r\n ''' This is where I will implement the main method.'''\r\n S_0 = input(\"Please enter the initial stock price: \")\r\n S_0 = float(S_0)\r\n r = input(\"Please enter the interest rate: \")\r\n r = float(r)\r\n u = input(\"Please enter a value for 'u' (up factor): \")\r\n u = float(u)\r\n d = input(\"Please enter a value for 'd' (down factor)): \")\r\n d = float(d)\r\n type = input(\"What type of option are you pricing? This program can handle put and call options. For a call option enter 1. For a put option enter 2: \")\r\n type = int(type)\r\n if (type==1) | (type==2):\r\n K = input(\"Please enter the strike price for the option: \")\r\n K = float(K)\r\n T = input(\"Please enter the maturity date of the option (T=?): \")\r\n T = int(T)\r\n else:\r\n print(\"INVALID INPUT\")\r\n\r\n V_T = define_final_Vs(S_0, u, d, T, K, type)\r\n V_second_to_last = np.zeros(2)\r\n\r\n stock_matrix = get_stock_price_matrix(S_0,u,d,T)\r\n #print(stock_matrix)\r\n #print(V_T)\r\n\r\n for i in range(1, T+1):\r\n if (len(V_T)==2):\r\n V_second_to_last = V_T\r\n #print(\"Printing second to last V vector\")\r\n #print(V_second_to_last)\r\n V_Tm1 = np.zeros(2**(T-i))\r\n for k in range(0, 2**(T-i)):\r\n V_Tm1[k] = v_prev(V_T[2*k], V_T[2*k+1], u, d, r)\r\n V_T = V_Tm1\r\n\r\n #print(V_T)\r\n\r\n #print(V_second_to_last)\r\n print(\"To replaicate the option, you should purchase \" + str(delta_0(stock_matrix[:,1],V_second_to_last)) + \" shares.\")\r\n print(\"The price of the option at time 0 is: $\" + str(V_Tm1[0]))\r\n return V_Tm1[0]\r\n\r\n\r\ndef get_stock_price_matrix(S_0,u,d,T):\r\n States = np.array(list(it.product([u, d], repeat=T)), dtype=float)\r\n\r\n S = np.zeros_like(States, dtype=float)\r\n S_0col = np.array([S_0]*(2**T))\r\n S_0col.shape = (2**T, 1)\r\n S = np.hstack((S_0col, S))\r\n\r\n for i in range(1, T+1):\r\n S[:,i] = S[:,i-1] * States[:,i-1]\r\n\r\n return S\r\n\r\ndef define_final_Vs(S_0, u, d, T, K, type):\r\n ''' This subprogram defines the final values that the option can take.\r\n S_0, u, and d are required to show how the stock price evolves. T tells\r\n us how many possibilities there are for the different prices. type determines\r\n the procedure for actually computing the Vs (Put, Call, or Exotic).'''\r\n\r\n\r\n S = get_stock_price_matrix(S_0,u,d,T)\r\n\r\n\r\n ''' Now, determine the option value for each type of option!\r\n Call Option: V = S_T - K, where this is positive\r\n Put Option: V = K - S_T, where this is positive\r\n Exotic Option: ??? '''\r\n\r\n if type == 1:\r\n V_T = S[:,T] - K\r\n # Some fancy indexing...\r\n mask = V_T[V_T<0]\r\n V_T[V_T<0] = 0\r\n if type == 2:\r\n V_T = K - S[:,T]\r\n # Some fancy indexing...\r\n mask = V_T[V_T<0]\r\n V_T[V_T<0] = 0\r\n\r\n return V_T\r\n\r\ndef v_prev(VH, VT, u, d, r):\r\n '''\r\n This function computes V_0 from equation (3.9). It requires as\r\n input the future V(H) and V(T) as well as parameters u, d, and r.\r\n It returns a scalar.\r\n '''\r\n V_0 = (1/(1+r))*(((1+r-d)/(u-d))*VH + ((u-(1+r))/(u-d))*VT)\r\n return V_0\r\n\r\ndef delta_0(stock_values_year_1, V_second_to_last):\r\n '''\r\n This function returns delta_0 from as from eqn (3.13).\r\n '''\r\n\r\n #print(stock_values_year_1)\r\n\r\n length_col = len(stock_values_year_1)\r\n\r\n location_H = (length_col/2)-1\r\n location_T = (length_col/2)\r\n\r\n denom = stock_values_year_1[int(location_H)] - stock_values_year_1[int(location_T)]\r\n numer = V_second_to_last[0] - V_second_to_last[1]\r\n\r\n #print(numer)\r\n #print(denom)\r\n\r\n return numer/denom\r\n \r\n\r\n\r\n #delta_0 = (V_second_to_last[0]-V_second_to_last[1])/(stock_matrix[:,1][middle_entry-1]-stock_matrix[:,1][middle_entry])\r\n\r\n #return delta_0\r\n\r\n\r\n#test\r\n#print(define_final_Vs(50,2,.5,2,9,\"Call\"))\r\n\r\n#test_matrix = get_stock_price_matrix(8,2,.5,2)\r\n#print(test_matrix)\r\n\r\n#delta_0 = 1/((test_matrix[:,1][2-1])-(test_matrix[:,1][2]))\r\n#print(delta_0)\r\n#print(delta_prev())\r\n#print(\" ------------------------- \")\r\nmain_program()\r\n#print(v_prev(1, 0, 2, .5, .02))\r\n#main_program()\r\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 7, "blob_id": "ac3bf62573fb1e9eaa1135a6fa18071961f01b1a", "content_id": "bd3937ef49bf6cd2f3330ba91c9548f8cb2422b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 8, "num_lines": 2, "path": "/README.md", "repo_name": "mattdbrown17/MMFE", "src_encoding": "UTF-8", "text": "# MMFE\nFor MMFE\n" } ]
2
kylophone/SVG-Box2dWeb
https://github.com/kylophone/SVG-Box2dWeb
937aa0620c0d0f912e85ee1184ffeb88a5693e48
bd555cb78b22afdb4bfa816fadaa22ad24d2efc4
5a8429bece5e8129a471a00e7dbfeeadcf07c235
refs/heads/master
2021-01-20T10:19:31.404899
2017-05-23T19:32:36
2017-05-23T19:32:36
31,115,983
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7529183030128479, "alphanum_fraction": 0.7626459002494812, "avg_line_length": 63.25, "blob_id": "24f36d2a44750a86569f738b078d3623f1665a97", "content_id": "5f32c0e6ee26b84362bd93f37fda9156472ac8a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 514, "license_type": "no_license", "max_line_length": 409, "num_lines": 8, "path": "/README.md", "repo_name": "kylophone/SVG-Box2dWeb", "src_encoding": "UTF-8", "text": "# SVG-Box2dWeb\n\nParses all the circles, rectangles, and polygons in your SVG drawing. Defines and initalizes a Box2dWeb world with all its physics bodies & fixtures. Takes an SVG as an input, and outputs javascript that no one should ever have to code by hand. Note that all of your SVG elements should have a unique id attribute. Run the script with an SVG you've created and then have a look at `demo.html` in your browser.\n## Usage\n```bash\ncd SVG-Box2dWeb\npython svg-box2dweb.py ./test.svg > ./js/level1.js\n```\n" }, { "alpha_fraction": 0.6131206750869751, "alphanum_fraction": 0.6304201483726501, "avg_line_length": 36.720340728759766, "blob_id": "95d029fcbcbb80ce0229eea21e6111fce90a0b2f", "content_id": "d24ac5881eeda97706c60d87f6dfba91ca86f446", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4451, "license_type": "no_license", "max_line_length": 113, "num_lines": 118, "path": "/svg-box2dweb.py", "repo_name": "kylophone/SVG-Box2dWeb", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\nimport sys\n\n\ndef print_circle_list(circle_list):\n\tfor s in circle_list:\n\t\tthis_cx = s.attributes['cx'].value\n\t\tthis_cy = s.attributes['cy'].value\n\t\tthis_r = s.attributes['r'].value\n\t\tthis_id = s.attributes['id'].value\n\t\tthisBodyDef = \"bodyDef\" + this_id\n\t\tthisFixDef = \"fixDef\" + this_id\n\n\t\tprint \"\\t//\" + this_id + \" (circle)\"\n\t\tprint \"\\tvar \" + thisBodyDef + \" = new b2BodyDef;\"\n\t\tprint \"\\tvar \" + thisFixDef + \" = new b2FixtureDef;\"\n\t\tprint \"\\t\" + thisFixDef + \".density = 0.5;\"\n\t\tprint \"\\t\" + thisFixDef + \".friction = 0.5;\" \n\t\tprint \"\\t\" + thisFixDef + \".restitution = 0.6;\"\n\t\tprint \"\\t\" + thisBodyDef + \".type = b2Body.b2_dynamicBody;\"\n\t\tprint \"\\t\" + thisFixDef + \".shape = new b2CircleShape(\" + this_r + \" / SCALE);\"\n\t\tprint \"\\t\" + thisBodyDef + \".position.Set(\" + this_cx + \" / SCALE, \" + this_cy + \" / SCALE);\"\n\t\tprint \"\\tworld.CreateBody(\" + thisBodyDef + \").CreateFixture(\" + thisFixDef + \");\"\n\t\tprint \"\\n\"\n\n\ndef print_rect_list(rect_list):\n\tfor s in rect_list:\n\t\tthis_x = s.attributes['x'].value\n\t\tthis_y = s.attributes['y'].value\n\t\tthis_height = s.attributes['height'].value\n\t\tthis_width = s.attributes['width'].value\n\t\tthis_id = s.attributes['id'].value\n\t\tthis_half_height = str(float(this_height) / 2)\n\t\tthis_half_width = str(float(this_width) / 2)\n\t\tthis_cy = str(float(this_y) + (float(this_height) / 2))\n\t\tthis_cx = str(float(this_x) + (float(this_width) / 2))\n\t\tthisBodyDef = \"bodyDef\" + this_id\n\t\tthisFixDef = \"fixDef\" + this_id\n\n\t\tprint \"\\t//\" + this_id + \" (rect)\"\n\t\tprint \"\\tvar \" + thisBodyDef + \" = new b2BodyDef;\"\n\t\tprint \"\\tvar \" + thisFixDef + \" = new b2FixtureDef;\"\n\t\tprint \"\\t\" + thisFixDef + \".density = 0.5;\"\n\t\tprint \"\\t\" + thisFixDef + \".friction = 0.5;\"\n\t\tprint \"\\t\" + thisFixDef + \".restitution = 0.2;\"\n\t\tprint \"\\t\" + thisBodyDef + \".type = b2Body.b2_staticBody;\"\n\t\tprint \"\\t\" + thisFixDef + \".shape = new b2PolygonShape;\"\n\t\tprint \"\\t\" + thisFixDef + \".shape.SetAsBox(\" + this_half_width + \" / SCALE, \" + this_half_height + \" / SCALE);\"\n\t\tprint \"\\t\" + thisBodyDef + \".position.Set(\" + this_cx + \" / SCALE, \" + this_cy + \" / SCALE);\"\n\t\tprint \"\\tworld.CreateBody(\" + thisBodyDef + \").CreateFixture(\" + thisFixDef + \");\"\n\t\tprint \"\\n\"\n\n\ndef print_polygon_list(polygon_list):\n\tfor s in polygon_list:\n\t\tthis_id = s.attributes['id'].value\n\t\tthese_points = s.attributes['points'].value.split()\n\t\tnumber_of_verticies = len(these_points)\n\t\torigin_x = these_points[0].split(',')[0]\n\t\torigin_y = these_points[0].split(',')[1]\n\t\tthisBodyDef = \"bodyDef\" + this_id\n\t\tthisFixDef = \"fixDef\" + this_id\n\n\t\tprint \"\\t//\" + this_id + \" (polygon)\"\n\t\tprint \"\\tvar \" + thisBodyDef + \" = new b2BodyDef;\"\n\t\tprint \"\\tvar \" + thisFixDef + \" = new b2FixtureDef;\"\n\t\tprint \"\\t\" + thisFixDef + \".density = 0.5;\"\n\t\tprint \"\\t\" + thisFixDef + \".friction = 0.5;\"\n\t\tprint \"\\t\" + thisFixDef + \".restitution = 0.4;\"\n\t\tprint \"\\t\" + thisBodyDef + \".type = b2Body.b2_staticBody;\"\n\t\tprint \"\\t\" + thisFixDef + \".shape = new b2PolygonShape;\"\n\t\tprint \"\\t\" + thisBodyDef + \".position.Set(\" + origin_x + \" / SCALE, \" + origin_y + \" / SCALE);\"\n\t\tprint \"\\t\" + thisFixDef + \".shape.SetAsArray([\"\n\t\tprint \"\\t\\tnew b2Vec2(0 / SCALE, 0 / SCALE),\"\n\n\t\tfor this_point in these_points[1:]:\n\t\t\tthis_x = str(float(this_point.split(',')[0]) - float(origin_x))\n\t\t\tthis_y = str(float(this_point.split(',')[1]) - float(origin_y))\n\t\t\tprint \"\\t\\tnew b2Vec2(\" + this_x + \" / SCALE, \" + this_y + \" / SCALE),\"\n\n\t\tprint \"\\t], \" + str(number_of_verticies) + \");\"\n\t\tprint \"\\tworld.CreateBody(\" + thisBodyDef + \").CreateFixture(\" + thisFixDef + \");\"\n\t\tprint \"\\n\"\t\n\n\ndef print_top():\n\tprint \"function level1(world) {\"\n\tprint \"\\tvar b2BodyDef = Box2D.Dynamics.b2BodyDef;\"\n\tprint \"\\tvar b2Body = Box2D.Dynamics.b2Body;\"\n\tprint \"\\tvar b2FixtureDef = Box2D.Dynamics.b2FixtureDef;\"\n\tprint \"\\tvar b2Fixture = Box2D.Dynamics.b2Fixture;\"\n\tprint \"\\tvar b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;\"\n\tprint \"\\tvar b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;\"\n\tprint \"\\tvar b2Vec2 = Box2D.Common.Math.b2Vec2;\"\n\tprint \"\\tvar SCALE = 30;\"\n\tprint \"\\n\"\n\n\ndef print_bottom():\n\tprint \"}\"\n\n\ndef main():\n\tsvgdoc = minidom.parse(sys.argv[1])\n\tpolygon_list = svgdoc.getElementsByTagName('polygon')\n\tcircle_list = svgdoc.getElementsByTagName('circle')\n\trect_list = svgdoc.getElementsByTagName('rect')\n\n\tprint_top()\n\tprint_rect_list(rect_list)\n\tprint_circle_list(circle_list)\n\tprint_polygon_list(polygon_list)\n\tprint_bottom()\n\n\nif __name__ == \"__main__\": \n\tmain()\n" } ]
2
yuuuuuya/python_practice
https://github.com/yuuuuuya/python_practice
552465e39b1d5e96ebffb52a9676427c0f838588
8422c55c68318c404011a6eb8d8ea156942e6601
f3791fee46768882881f5aacea78ead464bb1ca4
refs/heads/master
2021-05-04T13:54:44.630226
2018-02-05T15:28:47
2018-02-05T15:28:47
120,322,967
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6415637731552124, "alphanum_fraction": 0.6703703999519348, "avg_line_length": 27.928571701049805, "blob_id": "918188ebcefe1a305954ddaa03e96e7043fc160d", "content_id": "cb62d0ec906233430be179270843c63833f15774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2450, "license_type": "no_license", "max_line_length": 122, "num_lines": 84, "path": "/pra_src/img_util.py", "repo_name": "yuuuuuya/python_practice", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pdb\nimport os\n'''\nThe first line import \"Numetric(suuti) calsurlation module\"\nThe second line enable to indicate(hyoujisuru) a image and achart.\nThe third line enable to talk with a python.\nThe fourth line import os module. Refarence URL:\"http://nonbiri-tereka.hatenablog.com/entry/2014/03/14/195241\"\n'''\n\nfigsaveTo = '../figures/'\n'''\nどこで使っているか。\n'''\n\ndef color_adjust(image):\n return image[:, :, [2,1,0]]\n'''\nThis adjust(tyousei) the RGB color order of the image array.\n'''\n\ndef rotateLeft_bi90(image):\n aligned_img= image.transpose([1,0,2])\n new_Xindices = aligned_img.shape[0] - np.array(range(aligned_img.shape[0])) -1\n img2=aligned_img[new_Xindices]\n return img2\n'''\nThis adjust is \"relotate of the image\"\n'''\n\ndef extract_image(img, faceLoc, color = True):\n\n cornerX, cornerY, lenX, lenY = faceLoc\n xRange = range(cornerX, cornerX + lenX)\n yRange = range(cornerY, cornerY + lenY)\n return img[cornerX:(cornerX+lenX), cornerY:(cornerY+lenY), :]\n'''\nThe order extract(nukidasu) picture range of cornerX+lenX to cornerY+lenY.\nRefarenceURL:http://qiita.com/supersaiakujin/items/d63c73bb7b5aac43898a\n'''\n\ndef fix_face_location(rects):\n rectsNew = rects.copy()\n for k in range(len(rects)):\n rectsNew[k][1] = rects[k][0]\n rectsNew[k][0] = rects[k][1]\n return rectsNew\n'''\ncopy() is contents of for\n'''\n\ndef draw_rectangle(img, faceLoc, color = [255, 255, 255], thickness = 5):\n locX= faceLoc[0]\n locY= faceLoc[1]\n lenX= faceLoc[2]\n lenY= faceLoc[3]\n newimg = img.copy()\n newimg[locX:locX+thickness, locY: locY+lenY] = color\n newimg[locX: locX+lenX, locY:locY+thickness] = color\n newimg[locX +lenX:locX +lenX+thickness, locY: locY+lenY] = color\n newimg[locX: locX+lenX, locY+lenY:locY+lenY+thickness] = color\n\n #newimg[locX:locX+lenX+thickness, locY: locY+lenY] = color\n return newimg\n\n\ndef draw_multiple_rectangles(img, faceRects, color = [255, 255, 255], thickness = 5, save = False, filename = 'test.jpg'):\n imgnow = img\n\n for k in range(len(faceRects)):\n\n faceLoc = faceRects[k]\n #pdb.set_trace()\n\n imgnow = draw_rectangle(imgnow, faceLoc, color = color, thickness = thickness)\n\n if save:\n plt.figure(figsize = (20,20) )\n plt.imshow(imgnow)\n figpath = os.path.join(figsaveTo, filename)\n plt.savefig(figpath)\n\n return imgnow\n" }, { "alpha_fraction": 0.6852367520332336, "alphanum_fraction": 0.6908078193664551, "avg_line_length": 18.77777862548828, "blob_id": "d9720385a08c29796cb416e0810305b8cdcc07cf", "content_id": "0a0888eef2717de79f850083a612e3f595587aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/pra_src/bete_util.py", "repo_name": "yuuuuuya/python_practice", "src_encoding": "UTF-8", "text": "import numpy as np \nfrom scipy.stats import beta\nfrom matplotlib.pyplot import hist, plot, show\n\n'''\nコメント!!\n何をしている書く。英語で、(笑)\n'''\n\ndef betaVar(alpha,Beta):\n denom=(alpha+Beta)**2*(alpha+Beta+1)\n numer=(alpha*Beta)\n value=numer/denom\n return value#outputしてください。\n\ndef betaM(alpha,Beta):\n value=alpha/(alpha+Beta)\n return value#outputしてください。\n\n\n\n" } ]
2
Formalin564/VM
https://github.com/Formalin564/VM
6f65481554f99fa3fafac62f469e173f35d3eaae
22472bc66b8b6929dc61c2e66eac93d96ede005b
525738091e0d7f99289cedc16d78724e8ad85d1c
refs/heads/master
2022-12-14T02:23:48.684833
2020-02-07T09:50:00
2020-02-07T09:50:00
238,885,279
0
1
null
2020-02-07T09:22:47
2020-02-07T09:50:38
2022-12-08T03:34:15
Python
[ { "alpha_fraction": 0.7067307829856873, "alphanum_fraction": 0.7211538553237915, "avg_line_length": 33.66666793823242, "blob_id": "d2b4eea9ff655c24135922ec02c112e512196e39", "content_id": "900bcd4bb3d1669521f24ecda82e353daad27dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 43, "num_lines": 6, "path": "/Vm/models.py", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "from django.db import models\nclass address_info(models.Model):\n name = models.TextField()\n longitude = models.FloatField()\n latitude = models.FloatField()\n data = models.CharField(max_length=200)\n" }, { "alpha_fraction": 0.6732824444770813, "alphanum_fraction": 0.6732824444770813, "avg_line_length": 42.733333587646484, "blob_id": "1e70f55ae134fedf7e09cdeb7645ece35fefdb6f", "content_id": "561eeeaed42dfc98acc09ac0aa6876a43873abfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "no_license", "max_line_length": 111, "num_lines": 15, "path": "/Vm/view.py", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport json\nfrom .models import address_info\ndef hello(request):\n address_point = address_info.objects.all()\n address_longitude = []\n address_latitude = []\n address_data = []\n for i in range(len(address_point)):\n address_longitude.append(address_point[i].longitude)\n address_latitude.append(address_point[i].latitude)\n address_data.append(address_point[i].data)\n return render(request, 'map.html',\n {'address_longitude': json.dumps(address_longitude),\n 'address_latitude': json.dumps(address_latitude), 'address_data': json.dumps(address_data)})" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 14.333333015441895, "blob_id": "5f0c0d086333a2af1a5c76a2cca272c2e17bb882", "content_id": "67910696ff539bc559b978d137119cb0e0a87215", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/Vm/urls.py", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "from .import view\nfrom django.urls import path\n\nurlpatterns = [\n path('', view.hello),\n]\n" }, { "alpha_fraction": 0.448888897895813, "alphanum_fraction": 0.6844444274902344, "avg_line_length": 15.142857551574707, "blob_id": "116c7ae761a41c07042ca876ccc5d604e07f803d", "content_id": "ece33ce56350d3553acd04b99d59c5bb6224b47e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 225, "license_type": "no_license", "max_line_length": 22, "num_lines": 14, "path": "/requirements.txt", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\ncertifi==2019.11.28\nDjango==3.0.3\ndjango-leaflet==0.26.0\nGDAL==3.0.2\nmkl-fft==1.0.15\nmkl-random==1.1.0\nmkl-service==2.3.0\nnumpy==1.18.1\npsycopg2==2.8.4\npytz==2019.3\nsix==1.14.0\nsqlparse==0.3.0\nwincertstore==0.2" }, { "alpha_fraction": 0.586928129196167, "alphanum_fraction": 0.5947712659835815, "avg_line_length": 21.52941131591797, "blob_id": "c716e558f9563df40e4f7ec2ad95c2cf6e72a54a", "content_id": "8a410eeb5f3ae48a2c808564bf54386be280ad02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 89, "num_lines": 34, "path": "/Vm/sn.py", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport urllib.parse\nimport urllib.request\nimport json\n\nkey = 'iq9mhXfEXPYMlLyn070A3uvFFx968kpq'\n\n#属性名1:x 用于存储经度 类型 float\n#属性名2:y 用于存储纬度 类型 float\n\n#逆地址编码的方法\n\nclass locationXY:\n def __init__(self,x,y):\n self.x=x\n self.y=y\n\n#正/逆地理编码\ndef getLocation(address):\n\n data = urllib.parse.urlencode({'address': address, 'output': 'json','ak':key})\n response = urllib.request.urlopen('http://api.map.baidu.com/geocoding/v3/?%s' % data)\n html = response.read()\n data = html.decode('utf-8')\n result=json.loads(data)\n \n if result['status'] == 0 :\n lng = result['result']['location']['lng'] # 纬度\n lat = result['result']['location']['lat'] # 经度\n l=locationXY(lng,lat)\n return l\n\n else:\n print(address+\"没找到\")" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 17.399999618530273, "blob_id": "959c6a38ffed45fdb249dc108567d0938b29e9a8", "content_id": "1df9df6529ef7fe9d1bc42aac5fce9c49367d315", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/vm_notice/apps.py", "repo_name": "Formalin564/VM", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass VmNoticeConfig(AppConfig):\n name = 'vm_notice'\n" } ]
6
marcusfreire0504/pythonbrasil13-site
https://github.com/marcusfreire0504/pythonbrasil13-site
fe6cbf1e816e8a902ea7d92789047285f28d4d08
a8a288efa1529d71ea10464cf482d8c521ce1ec0
8a0a80a54e138339ae481694ec15b8c7db8aeafc
refs/heads/master
2021-09-05T16:33:27.363023
2018-01-29T16:46:32
2018-01-29T16:46:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6182559728622437, "alphanum_fraction": 0.6342534422874451, "avg_line_length": 25.34710693359375, "blob_id": "39a91f305d385935ecb5f2cc2a7418506ca7d2e8", "content_id": "ace59d94b56e6b09b2f74ebd6593e353d2a81898", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 3188, "license_type": "no_license", "max_line_length": 78, "num_lines": 121, "path": "/fabfile.py", "repo_name": "marcusfreire0504/pythonbrasil13-site", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2016, cloudez Adm. Sis. SA. <[email protected]>\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# On Debian systems, you can find the full text of the license in\n# /usr/share/common-licenses/GPL-2\n\nimport time\n\nfrom fabric.api import env, local, puts\n\n\n#\n# available environments\n#\ndef production():\n env.user = 'pythonbrasil'\n env.deploy_path = '/srv/2017.pythonbrasil.org.br/www'\n env.current_path = '/srv/2017.pythonbrasil.org.br/www/current'\n env.releases_path = '/srv/2017.pythonbrasil.org.br/www/releases'\n env.releases_limit = 2\n env.git_origin = 'https://github.com/pythonbrasil/pythonbrasil13-site.git'\n env.git_branch = 'master'\n env.virtual_environment = '/srv/2017.pythonbrasil.org.br/activate'\n#\n# end available environments\n#\n\n\n#\n# available commands\n#\ndef deploy():\n start = time.time()\n\n setup()\n checkout()\n run_pelican()\n releases()\n symlink()\n cleanup()\n\n final = time.time()\n puts('deploy execution finished in %.2fs' % (final - start))\n\n\ndef run_pelican():\n local('. {} && cd {} && make html'.format(\n env.virtual_environment, env.current_release))\n local('ln -nfs {}/fabfile.py {}/output'.format(\n env.current_release, env.current_release))\n\n\ndef rollback():\n start = time.time()\n\n setup()\n releases()\n rollback_code()\n\n final = time.time()\n puts('execution finished in %.2fs' % (final - start))\n#\n# end available commands\n#\n\n\n#\n# internal commands\n#\ndef setup():\n local('mkdir -p {}'.format(env.deploy_path))\n local('mkdir -p {}/releases'.format(env.deploy_path))\n\n\ndef checkout():\n env.current_release = '{0}/{1:.0f}'.format(env.releases_path, time.time())\n local('cd {0}; git clone -q -b {1} -o deploy --depth 1 {2} {3}'.format(\n env.releases_path, env.git_branch, env.git_origin,\n env.current_release))\n\n\ndef releases():\n env.releases = sorted(\n local('ls -x {}'.format(env.releases_path), capture=True).split())\n\n\ndef symlink():\n local('ln -nfs {0} {1}'.format(env.current_release, env.current_path))\n\n\ndef cleanup():\n if len(env.releases) > env.releases_limit:\n directories = env.releases\n directories.reverse()\n del directories[:env.releases_limit]\n env.directories = ' '.join(['{0}/{1}'.format(\n env.releases_path, release) for release in directories])\n local('rm -rf {}'.format(env.directories))\n\n\ndef rollback_code():\n if len(env.releases) > 1:\n env.current_release = env.releases[-1]\n env.previous_revision = env.releases[-2]\n env.current_release = '{0}/{1}'.format(\n env.releases_path, env.current_revision)\n env.previous_release = '{0}/{1}'.format(\n env.releases_path, env.previous_revision)\n command = 'rm {0}; ln -s {1} {0} && rm -rf {2}'\n local(command.format(\n env.current_path, env.previous_release, env.current_release))\n#\n# end internal commands\n#\n" }, { "alpha_fraction": 0.6870131492614746, "alphanum_fraction": 0.7515932321548462, "avg_line_length": 30.79729652404785, "blob_id": "1f8fbaeefd1d2bb4eafb1c33e04112cffddc8c49", "content_id": "11dba6d76e013704817708945fec44483fe61272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7166, "license_type": "no_license", "max_line_length": 175, "num_lines": 222, "path": "/content/pages/informacoes-sobre-locais.md", "repo_name": "marcusfreire0504/pythonbrasil13-site", "src_encoding": "UTF-8", "text": "Title: Informações sobre locais\nDate: 2017-10-03\n\n# Restaurantes:\n\n\\* Oferece opções veganas\n\n- **Pão de Queijaria**\n\nEndereço: R. Antônio de Albuquerque, 856 - Funcionários, Belo Horizonte - MG\n\nCafé e várias opções de pães de queijo recheados.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d6542167-Reviews-A_Pao_De_Queijaria-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Duke n' duke\\***\n\nEndereço: Augusto de Lima, 245 Centro, Belo Horizonte\n\nAlmoço e também Hamburgers.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d9764553-Reviews-Duke_n_Duke-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Cosmopolitan**\n\nEndereço: R. Pernambuco, 797 - Savassi, Belo Horizonte - MG\n\nAlmoço, Hamburgers e pizza.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d7173302-Reviews-Cosmopolitan_Hamburgueria-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Restaurante Jorge Americano**\n\nEndereço: Mercado Central de 170 30190-922, Av. Augusto de Lima, 744 - L-2 - Centro, Belo Horizonte - MG,\n\nAlmoço\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d8424808-Reviews-Restaurante_Jorge_Americano-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Restaurante da Léia**\n\nEndereço: R. Antônio José de Carvalho, 55 - Caiçaras, Belo Horizonte - MG\n\nQuem quer comer um excelente tropeiro.\n\n[Link](https://kekanto.com.br/biz/restaurante-da-leia)\n\n- **Espaço Suricato**\n\nEndereço: R. Souza Bastos, 175 - Floresta, Belo Horizonte - MG\n\nÉ um bar/restaurante/galeria de arte de um projeto social para quem tem transtornos mentais. Na quinta é literária, sexta e sábado são sempre musicais. A comida é maravilhosa.\n\n[Link](https://pt.foursquare.com/v/espa%C3%A7o-suricato/54cd5660498ebdd6b193b5fc)\n\n- **Queijo Mania**\n\nEndereço: Rua dos Guaranis, 482 - Centro, Belo Horizonte - MG\n\nLanchonete, recomendado por seu pão de queijo.\n\n[Link](https://kekanto.com.br/biz/queijo-mania-lanches)\n\n- **San Ro Restaurante Vegetariano\\***\n\nEndereço: Rua Professor Moraes, 651 - Funcionários\n\nRestaurante com opções veganas.\n\n[Link](https://www.tripadvisor.com/Restaurant_Review-g303374-d2361558-Reviews-San_Ro-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Black Burguer\\***\n\nEndereço: Av. Francisco Sá, 154 - Prado, Belo Horizonte - MG\n\nHamburguer Artesal com opções veganas\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d10125825-Reviews-Black_Burger_Artesanal-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **GUAJA\\***\n\nEndereço: Av. Afonso Pena, 2881 - Centro, Belo Horizonte - MG\n\nCafé, Internet e hamburgueria a noite (com opções veganas)\n\n[Link](http://guaja.cc/)\n\n- **Estação Parada do Cardoso**\n\nEndereço: R. Dores do Indaiá, 409 - Santa Teresa, Belo Horizonte - MG\n\nPizzaria\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d4534214-Reviews-Parada_do_Cardoso-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Yan Shan Zay\\***\n\nEndereço: Av. Getúlio Vargas, 1220 - Funcionários, Belo Horizonte\n\nBuffet de pratos vegetarianos e integrais em espacinho rústico e aconchegante, com influências de Taiwan.\n\n[Link](https://www.tripadvisor.com/Restaurant_Review-g303374-d8027277-Reviews-Yan_Shan_Zay-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Las Chicas Vegan\\***\n\nEndereço: Maleta, Avenida Augusto de Lima, 233 - Sobreloja 20\n\nRestaurante vegetariano/vegano em Belo Horizonte. Opções de almoço e hamburgers.\n\n[Link](https://www.tripadvisor.com/Restaurant_Review-g303374-d10461157-Reviews-Las_Chicas_Vegan-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Mr. Hoppy Tiradentes**\n\nEndereço: Praça Tiradentes, 41 - Funcionários, Belo Horizonte - MG, 30130-020\n\nHamburger e cervejas artesanais\n\n[Link](https://www.facebook.com/mrhoppypcatiradentes/)\n\n- **Café cultura**\n\nEndereço: R. da Bahia, 1416 - Lourdes, Belo Horizonte - MG\n\nCerveja gelada, música boa, ambiente divertido.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d5648529-Reviews-Cafe_Cultura-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Wals GastroPub**\n\nEndereço: R. Levindo Lopes, 358 - Savassi, Belo Horizonte - MG\n\nDiversos tipos de chopes e cervejas artesanais, além de petiscos e pratos, em ambiente rústico e descontraído.\n\n[Link](https://www.tripadvisor.com/Restaurant_Review-g303374-d8830710-Reviews-Wals_Gastropub-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Svärten Mugg Taverna**\n\nEndereço: R. Santa Rita Durão, 1056 - Savassi, Belo Horizonte - MG\n\nCervejas especiais, drinks e comidas típicas nórdica/viking e germânica em belo horizonte. Preço um mais elevado.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d10297004-Reviews-Svarten_Mugg_Taverna-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n# Espaços para trabalhar:\n\n- **Guaja Coworking**\n\nEndereço: Av. Afonso Pena, 2881 - Centro, Belo Horizonte - MG\n\n[Link](http://guaja.cc/)\n\n- **Café Coworking Pátio Savassi**\n\nEndereço: Shopping Pátio Savassi - Av. do Contorno, 6061, Piso L3 - São Pedro - Belo Horizonte, MG\n\n[Link](https://beerorcoffee.com/coworking/space/cafe-coworking-patio-savassi--belo-horizonte)\n\n- **Mr. Black coffee boulevard**\n\nEndereço: Av dos Andradas, 3000 | Loja 3008, Belo Horizonte, Minas Gerais 30260-070, Brasil\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d7253370-Reviews-Mr_Black_Cafe_Gourmet_Boulevard_Shopping-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Wals GastroPub**\n\nEndereço: R. Levindo Lopes, 358 - Savassi, Belo Horizonte - MG\n\nDiversos tipos de chopes e cervejas artesanais, além de petiscos e pratos, em ambiente rústico e descontraído.\n\n[Link](https://www.tripadvisor.com/Restaurant_Review-g303374-d8830710-Reviews-Wals_Gastropub-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n- **Svärten Mugg Taverna**\n\nEndereço: R. Santa Rita Durão, 1056 - Savassi, Belo Horizonte - MG\n\nCervejas especiais, drinks e comidas típicas nórdica/viking e germânica em belo horizonte. Preço um mais elevado.\n\n[Link](https://www.tripadvisor.com.br/Restaurant_Review-g303374-d10297004-Reviews-Svarten_Mugg_Taverna-Belo_Horizonte_State_of_Minas_Gerais.html)\n\n# Baladinhas:\n\n- **Karaokê - Bar da Cácia**\n\nEndereço: Rua Rio de Janeiro, 1411. Bairro Lourdes, Belo Horizonte - MG\nTelefone: (31) 3222-3260\n\nKarokê bastante animado e com cerveja gelada. Recebe bem todos os públicos mas com destaque o público LGBT.\n\n[Link](https://www.facebook.com/pages/Bar-da-C%C3%A1cia/199640383410644)\n\n- **O Mercado**\n\nEndereço: Av. Olegário Maciel, 742. Belo Horizonte - MG\nTelefone: (31) 3271-9181\n\n[Link](https://www.facebook.com/mercadobelohorizonte/)\n\n- **NECUP**\n\nEndereço: Av. Nossa Senhora de Fátima, 3312. Bairro Prado, Belo Horizonte - MG\nTelefone: (31) 3295-0716\n\n[Link](https://www.facebook.com/necup)\n\n\n# Cerveja Artesanal:\n\n- **Ateliê Wäls**\nEndereço: Rua Gabriela de Melo, 566, Olhos D'água\nTelefone: (31) 3197-2450\nFuncionamento: Terça a sexta: 17h-00h | Sábado: 12h-01h | Domingo: 12h-19h\n[Link](http://www.wals.com.br/app/webroot/atelie/)\n\n- **Cervejaria Backer - Templo Cervejeiro**\nEndereço: Rua Santa Rita, 220, Olhos d'Água\nFuncionamento: Terça 11h30-15h | Quarta e Quinta 11h30-15h30 e 18h | Sexta e Sábado 11h30-01h | Domingo 11h-16h\n[Link](http://www.cervejariabacker.com.br/templo-do-cervejeiro)\n\n- **Uamii - Brew Pub**\nEndereço: Rua Grão Mogol, 1176, Sion \nTelefone: (31) 3285-3435 \n[Link](https://www.facebook.com/Uaimii/)\n\n\n" } ]
2
cmontemuino/dbschools
https://github.com/cmontemuino/dbschools
e15d4d03a3d2f0e1ee1fa47b8ce9748b7f09cdbc
d3ee1fdc5c36274e5d5f7834ca1110b941d097b9
07eb17b45ce5414282a2464c69f50197968c312d
refs/heads/master
2021-01-16T21:16:56.427183
2015-08-02T17:09:43
2015-08-02T17:09:43
6,158,940
0
0
null
2012-10-10T14:49:16
2015-08-11T08:34:59
2015-10-15T12:41:13
HTML
[ { "alpha_fraction": 0.664202094078064, "alphanum_fraction": 0.6759088039398193, "avg_line_length": 26.982759475708008, "blob_id": "4b784f2f52dbd4250ca75e26d177fd8d22bd7f38", "content_id": "8b46c1e040dc193d7b437c3dc92048d8bad090ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1623, "license_type": "no_license", "max_line_length": 77, "num_lines": 58, "path": "/stusched/app/models.py", "repo_name": "cmontemuino/dbschools", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Course(models.Model):\n name = models.CharField(max_length=100)\n description = models.TextField()\n\n def __str__(self):\n return self.name.__str__()\n\nPROPOSED = 1\nACCEPTING = 2\nSCHEDULED = 3\n\nstatuses = {\n PROPOSED: 'proposed',\n ACCEPTING: 'accepting',\n SCHEDULED: 'scheduled'\n}\n\n\nclass Section(models.Model):\n start_time = models.DateTimeField()\n duration_per_day = models.DurationField()\n num_days = models.DecimalField(max_digits=3, decimal_places=0, default=1)\n course = models.ForeignKey(Course)\n price = models.DecimalField(max_digits=6, decimal_places=2)\n min_students = models.IntegerField(default=3)\n max_students = models.IntegerField(default=6)\n scheduled_status = models.IntegerField()\n\n def end_time(self): return self.start_time + self.duration_per_day\n\n def __str__(self):\n return \"At %s\" % (self.start_time.__str__())\n\nclass Parent(models.Model):\n name = models.CharField(max_length=100)\n email = models.EmailField()\n\n def __str__(self):\n return self.name.__str__()\n\nclass Student(models.Model):\n name = models.CharField(max_length=100)\n parent = models.ForeignKey(Parent)\n sections = models.ManyToManyField(Section, blank=True)\n\n def proposed_sections(self):\n return self.sections.filter(scheduled_status=PROPOSED)\n\n def accepting_sections(self):\n return self.sections.filter(scheduled_status=ACCEPTING)\n\n def scheduled_sections(self):\n return self.sections.filter(scheduled_status=SCHEDULED)\n\n def __str__(self):\n return self.name.__str__()\n" }, { "alpha_fraction": 0.7713414430618286, "alphanum_fraction": 0.7743902206420898, "avg_line_length": 22.428571701049805, "blob_id": "dadc7aa58c009fda567e14240b3f5c39fc877012", "content_id": "365d919cb33166b7b20c44599518b4021c3b8b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/stusched/app/admin.py", "repo_name": "cmontemuino/dbschools", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import *\n\nclass StudentInline(admin.TabularInline):\n model = Student\n extra = 0\n\nclass ParentAdmin(admin.ModelAdmin):\n inlines = [StudentInline]\n\nadmin.site.register(Course)\nadmin.site.register(Section)\nadmin.site.register(Parent, ParentAdmin)\nadmin.site.register(Student)\n" }, { "alpha_fraction": 0.5251572132110596, "alphanum_fraction": 0.544025182723999, "avg_line_length": 24.440000534057617, "blob_id": "719d370417354defef304b64a42131b42c7600f7", "content_id": "349999a635dea0a3da4ac39430022aa50ad0a75e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 636, "license_type": "no_license", "max_line_length": 71, "num_lines": 25, "path": "/music-gradebook/src/main/webapp/js/metronome.js", "repo_name": "cmontemuino/dbschools", "src_encoding": "UTF-8", "text": "var go = false;\nvar tempoBpm = 60;\nvar metroSoundNum = 1;\n\nfunction metro() {\n var metronome = $('#metronome');\n if (go) {\n metronome.removeClass('active');\n go = false;\n } else {\n metronome.addClass('active');\n go = true;\n beep();\n }\n}\nfunction beep() {\n if (go) {\n var startTime = new Date().getTime();\n document.getElementById('audioControl' + metroSoundNum).play();\n var elapsed = new Date().getTime() - startTime;\n var bps = tempoBpm == 0 ? 1 : tempoBpm / 60.0;\n var msDelay = 1000 / bps;\n setTimeout(\"beep()\", msDelay - elapsed);\n }\n}\n" }, { "alpha_fraction": 0.6740139126777649, "alphanum_fraction": 0.6740139126777649, "avg_line_length": 36.4782600402832, "blob_id": "1243cd6596aa41fd1c44a486ed10b3e682abf5a6", "content_id": "2b2a4d2e471a69e564d6a5d226148ec87cde3010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 115, "num_lines": 23, "path": "/stusched/app/views.py", "repo_name": "cmontemuino/dbschools", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Course, Section, Parent\n\nclass ScheduledCourse(object):\n def __init__(self, name, description, sections):\n self.name = name\n self.description = description\n self.sections = sections\n\n def __str__(self, *args, **kwargs):\n return self.name + ' ' + self.description\n\ndef index(request):\n sections = Section.objects.order_by('start_time')\n scheduled_courses = set((s.course for s in sections))\n courses = (ScheduledCourse(c.name, c.description,\n [s for s in sections if s.course == c]) for c in Course.objects.order_by('name') if c in scheduled_courses)\n\n return render(request, 'app/courses.html', {'courses': courses})\n\ndef status(request):\n parents = Parent.objects.order_by('name')\n return render(request, 'app/status.html', {'parents': parents})\n" } ]
4
Mr-Pi-a/direct_message
https://github.com/Mr-Pi-a/direct_message
b1b31cdaf91f64fff1071d1ae2dbb8e6cbc3a488
45fd4861e86cc12ad1e8463847991bd42eaaa04b
7721f3dc4003fa4e72321c1fbf6bd21dd43f3a50
refs/heads/main
2023-07-09T12:40:23.254561
2021-08-11T16:34:10
2021-08-11T16:34:10
319,646,523
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7623931765556335, "alphanum_fraction": 0.7623931765556335, "avg_line_length": 28.25, "blob_id": "964d981c59ed8847b66cd564146b207a46ceeb48", "content_id": "b68c0402723e5f11dec4ec91ef5a3da7a84fd038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 585, "license_type": "no_license", "max_line_length": 126, "num_lines": 20, "path": "/README.md", "repo_name": "Mr-Pi-a/direct_message", "src_encoding": "UTF-8", "text": "# direct_message\nsome times while working we come to situations where we need to send message to a particular person without saving his number \nso i made this simple to use tool \nwhich is fast to use and super handy\n\nCOMMANDS\n$ pkg install git -y\n$ pkg install python -y\n$ git clone https://github.com/Mr-Pi-a/direct_message.git\n$ cd direct\n$ python direct.py\n\nmade for termux & kali linux only\n\nif you are using any application in phone open \"for_phone.py\" copy the source code and paste it in app\n\nif you are using windows use message.exe\n\nfor any query or upgrade \nmail to: [email protected]\n" }, { "alpha_fraction": 0.4086378812789917, "alphanum_fraction": 0.49311816692352295, "avg_line_length": 35.625, "blob_id": "28752478fbe3ea5b1395ffe361d76b418e7c095f", "content_id": "f3c1efb5a9cdcb9262de0f4d6b03a6c5f9481c96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2107, "license_type": "no_license", "max_line_length": 104, "num_lines": 56, "path": "/main.py", "repo_name": "Mr-Pi-a/direct_message", "src_encoding": "UTF-8", "text": "import os\r\n\r\nos.system(\"clear\")\r\nwhile True:\r\n print(\" \\033[1;32;40mDirect message sender\\033[1;32;40m \")\r\n print(\" \\033[93mCHOOSE COUNTRY YOU WANNA SEND MESSAGE TO \\033[93m\")\r\n print(\"\\033[92mOPTION 1...INDIA\\033[92m\")\r\n print(\"OPTION 2...PAKISTAN\")\r\n print(\"OPTION 3...AMERICA\")\r\n print(\"OPTION 4...CANADA\")\r\n print(\"OPTION 5...GERMANY\")\r\n print(\"OPTION 6...UNITED KINGDOM\")\r\n print(\"OPTION 7...CUSTOM\")\r\n q = input(\"\\033[91m\\n\\nENTER OPTION ==>>>\\033[91m\\033[92m\\033[92m \")\r\n\r\n while True:\r\n print(\"\\n\\npress q to exit\\n\\n\")\r\n number = input(\"\\033[91mENTER THE PHONE NUMBER===>>>\\033[91m\\033[92m\\033[92m \").replace(\" \", \"\")\r\n if number==\"q\":\r\n exit()\r\n if not len(number) == 10:\r\n print(\"\\n \\033[91m Please enter a correct number ..!\\033[91m\\n\")\r\n print(\" \\033[91m ENTER VALID 10 DIGIT NUMBER\\n\\n\\033[91m\")\r\n else:\r\n break\r\n \r\n if (q == \"india\" or q == \"1\"):\r\n new_number = \"+91\" + number\r\n elif (q == \"pakistan\" or q == \"2\"):\r\n new_number = \"+92\" + number\r\n elif (q == \"america\" or q == \"3\"):\r\n new_number = \"+1\" + number\r\n elif (q == \"canada\" or q == \"4\"):\r\n new_number = \"+1\" + number\r\n elif (q == \"germany\" or q == \"5\"):\r\n new_number = \"+49\" + number\r\n elif (q == \"united kingdom\" or q == \"6\"):\r\n new_number = \"+44\" + number\r\n elif q==\"q\":\r\n exit()\r\n elif (q == \"custom\" or q == \"7\"):\r\n custom_code = input(\"\\033[91m\\n\\nENTER COUNTRY CODE==>>>\\033[91m\\033[92m\\033[92m\")\r\n if custom_code.startswith(\"+\"):\r\n new_number = custom_code + number\r\n else:\r\n new_number = \"+\" + custom_code + number\r\n else:\r\n print(\"ERROR!!!\")\r\n\r\n\r\n whatsapp = 'https://api.whatsapp.com/send?phone=' + new_number\r\n os.system(\"xdg-open \" + whatsapp)\r\n os.system(\"clear\")\r\n print(\" \\033[1;32;40mDONE !!!!\\033[1;32;40m\")\r\n print(\" \\033[91m|---------|\\033[91m\")\r\n print(\"\\033[0m\\033[0m\")\r\n" } ]
2
rorysavage77/python-scripts
https://github.com/rorysavage77/python-scripts
8083cd133e93d97167588ddc57fbbc26f38c6f71
d4c253a6dec4459c25f8d5c741a309848d6cb8de
1988d0cbf6a9942a6234807914e4413f23f79eda
refs/heads/master
2021-05-30T03:26:58.905835
2015-12-23T03:25:01
2015-12-23T03:25:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6427043080329895, "alphanum_fraction": 0.6486949324607849, "avg_line_length": 28.582279205322266, "blob_id": "6f085a4ee60cdeed75ce904398344e2ec78f1d05", "content_id": "1e9101a6bcf3d46afcc746dbf01bbced3e7e0900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2337, "license_type": "no_license", "max_line_length": 85, "num_lines": 79, "path": "/pm.py", "repo_name": "rorysavage77/python-scripts", "src_encoding": "UTF-8", "text": "\"\"\"Paramiko Interactive Shell\"\"\"\nimport base64\nimport getpass\nimport os\nimport socket\nimport sys\nimport traceback\nfrom paramiko.py3compat import input\nimport paramiko\ntry:\n import interactive as interactive\nexcept ImportError:\n from . import interactive as interactive\n\n\"\"\"Setup Logging\"\"\"\nparamiko.util.log_to_file('pm.log')\n\"\"\"Client configuration\"\"\"\nUseGSSAPI = False \nDoGSSAPIKeyExchange = False \nport = 22\n\n\"\"\"Get hostname\"\"\"\nusername = ''\nif len(sys.argv) > 1:\n hostname = sys.argv[1]\n if hostname.find('@') >= 0:\n username, hostname = hostname.split('@')\nelse:\n hostname = input('Hostname: ')\nif len(hostname) == 0:\n print('*** Hostname required.')\n sys.exit(1)\n\nif hostname.find(':') >= 0:\n hostname, portstr = hostname.split(':')\n port = int(portstr)\n\n\"\"\"Obtain username\"\"\"\nif username == '':\n default_username = getpass.getuser()\n username = input('Username [%s]: ' % default_username)\n if len(username) == 0:\n username = default_username\nif not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):\n password = getpass.getpass('Password for %s@%s: ' % (username, hostname))\n\n\"\"\"Use paramiko to setup ssh2 client connection\"\"\"\ntry:\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.WarningPolicy())\n print('Connecting to host: %s\\n' % (hostname))\n if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):\n client.connect(hostname, port, username, password)\n else:\n # SSPI works only with the FQDN of the target host\n hostname = socket.getfqdn(hostname)\n try:\n client.connect(hostname, port, username, gss_auth=UseGSSAPI,\n gss_kex=DoGSSAPIKeyExchange)\n except Exception:\n password = getpass.getpass('Password for %s@%s: ' % (username, hostname))\n client.connect(hostname, port, username, password)\n\n chan = client.invoke_shell()\n print(repr(client.get_transport()))\n print('Connected to host: %s\\n' % (hostname))\n interactive.interactive_shell(chan)\n chan.close()\n client.close()\n\nexcept Exception as e:\n print('*** Caught exception: %s: %s' % (e.__class__, e))\n traceback.print_exc()\n try:\n client.close()\n except:\n pass\n sys.exit(1)\n" } ]
1